Skip to content Skip to sidebar Skip to footer

How To Check If Element Is Orthogonally Adjacent (next To) To Existing Elements?

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 ca

Solution 1:

Try this code:

defbuild(place: str, what: int, first_build: bool = False):
    iflen(place) == 2and0 <= what < len(building_list):  # check the arguments
        x, 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 buildif0 <= x <= width and0 <= y <= height and board[y][x] == ''and \
                (first_build orany(
                    0 <= x + dx <= width and0 <= 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')  # headerfor i inrange(height + 1):
    print(str(i) + row.format(*board[i]), line, sep='\n')

Output:

     A     B     C     D   
  +-----+-----+-----+-----+
0 |     |     |     |     |
  +-----+-----+-----+-----+
1 |     |     |     |     |
  +-----+-----+-----+-----+
2 |     | SHP |     |     |
  +-----+-----+-----+-----+
3 | HSE | FAC |     |     |
  +-----+-----+-----+-----+

Post a Comment for "How To Check If Element Is Orthogonally Adjacent (next To) To Existing Elements?"