How to check if element is orthogonally adjacent (next to) to existing elements?

2024/9/20 13:47:49

I'm trying to make a simple game where a building placed in a nested list must be next to another building. The problem I face is that if the building was placed at the sides, I can't use for loops to check for existing buildings since it would not be part of the list anymore, since there is nothing on some sides of the building.

board = [['', '', '', ''],['', '', '', ''],['', '', '', ''],['', '', '', '']]building_list = ['HSE', 'FAC', 'SHP', 'HWY', 'BCH']

Output:

Turn 2A     B     C     D+-----+-----+-----+-----+
1|     |     |     |     |+-----+-----+-----+-----+
2|     | HSE |     |     |+-----+-----+-----+-----+
3|     |     |     |     |+-----+-----+-----+-----+
4|     |     |     |     |+-----+-----+-----+-----+
1. Build a HWY
2. Build a HWY
3. See remaining buildings
4. See current score5. Save game
0. Exit to main menu
Your choice? 1
Build where? a3
You must build next to an existing building.

My current code:

def build_buildings():global turna = 0m = 1j = 1k = 1i = 1if option == 1:building = option1else:building = option2location = input('Build where? ')location.split()col = location[0]row = int(location[1]) - 1if col == 'a':col = 0elif col == 'b':col = 1elif col == 'c':col = 2else:col = 3if turn > 1:if col == 0:m = -1if row == 0:j = 0if col == 3:k = -1if row == 3:i = 0if (board[int(row + i)][col] or board[int(row - j)][col] or board[int(row)][col + k]or board[int(row)][col - m]) != '':board[int(row)][col] = buildingelse:board[int(row)][col] = ''print('You must build next to an existing building.')print()turn -= 1else:board[int(row)][col] = building
Answer

Try this code:

def build(place: str, what: int, first_build: bool = False):if len(place) == 2 and 0 <= what < len(building_list):  # check the argumentsx, y = x_axe.get(place[0].upper(), -1), int(place[1]) if place[1].isdigit() else -1  # get the x,y coordinates# check the conditions to buildif 0 <= x <= width and 0 <= y <= height and board[y][x] == '' and \(first_build or any(0 <= x + dx <= width and 0 <= y + dy <= height and board[y + dy][x + dx] != '' for dy, dx in((-1, 0), (0, 1), (1, 0), (0, -1)))):board[y][x] = building_list[what]  # build!# global variables
board = [['', '', '', ''],['', '', '', ''],['', '', '', ''],['', '', '', '']]
building_list = ['HSE', 'FAC', 'SHP', 'HWY', 'BCH']
x_axe = {'A': 0, 'B': 1, 'C': 2, 'D': 3}  # make dict with x indexes for use in build()
# get the max coordinates of the board
height = len(board) - 1
width = len(board[0]) - 1# simple examples; replace with your code
build('a3', 0, True)  # first build with True as third argument
build('b3', 1)  # other buildings; will be built
build('d3', 2)  # will not be built because of conditions
build('B2', 2)  # will be built
build('S9', 3)  # will not be built due to wrong symbol and wrong y coordinate# output the board. first, make the format strings for the table
line = f"  {'+-----' * (width + 1)}+"  # +-----+-----+-----+-----+
row = f" {'|{:^5}' * (width + 1)}|"  # |{:^5}|{:^5}|{:^5}|{:^5}|
header = f"   {'{:^6}' * (width + 1)}"  # {:^6}{:^6}{:^6}{:^6}
print(header.format(*x_axe.keys()), line, sep='\n')  # header
for i in range(height + 1):print(str(i) + row.format(*board[i]), line, sep='\n')

Output:

     A     B     C     D   +-----+-----+-----+-----+
0 |     |     |     |     |+-----+-----+-----+-----+
1 |     |     |     |     |+-----+-----+-----+-----+
2 |     | SHP |     |     |+-----+-----+-----+-----+
3 | HSE | FAC |     |     |+-----+-----+-----+-----+
https://en.xdnf.cn/q/119326.html

Related Q&A

How to add new column(header) to a csv file from command line arguments

The output of the following code:-import datetime import csv file_name=sample.txt with open(file_name,rb) as f: reader = csv.reader(f,delimiter=",") …

Pattern matching and replacing in Python

Im trying to take a string that can be anything like "Hello here is a [URL]www.url.com[/URL] and its great." and be able to extract whatever is between [URL] and [/URL] and then modify the st…

In Python word search, searching diagonally, printing result of where word starts and ends

I have a friend of mine tutoring me in learning Python and he gave me this project where a user will read a word search into the program and the file includes a list of words that will be in the word s…

Selenium python : element not interactable

I am trying to scrape information from this website example website I need to get the version 2021 and search by code. Here is my code: from selenium import webdriver from selenium.webdriver.chrome.opt…

Date into matplotlib graph

How can I use a date from a Sqlite database on the x-axis to make a bar graph with matplotlib?If I convert the date to unix timestamp the graph works, but I would like to get something like this: http…

Non blocking IO - Programming model

In non blocking IO programming model, a thread blocked on data available channels, as shown below, in python,while True:readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select()for re…

How to globally change xticks label relplot in Seaborn

I am facing an issue to globally changed the x-tick label for plot render using the relplot The idea was to change the int to string x-tick label for both plot. The desired label is [a,b,c,d] However, …

How to solve MatplotlibDeprecationWarning: scipy.stats.norm.pdf warning?

I am using matplotlib in my Python code. I got following warning: xxx.py:88: MatplotlibDeprecationWarning: scipy.stats.norm.pdfy = 100 * mlab.normpdf(bin_middles, mu, sigma)*bin_width I was wondering…

time data 42:53.700 does not match format %H:%M:%S.%f (match)

I am trying to convert a column in string format to DateTime format, However, I am getting the following error, could somebody please help? The error:time data 42:53.700 does not match format %H:%M:%S…

How can I import .py file? [duplicate]

This question already has answers here:Adding a directory to sys.path with pathlib(4 answers)Closed last year.Below is my code: from pathlib import Path import os import sys sys.path.insert(0, os.path.…