Home > OS >  Python Updating Object in 2D List
Python Updating Object in 2D List

Time:10-15

I am making Conway's Game of Life using pygame and am trying to update the state of the position when the board is clicked. Each position on the board is a Cell object with a variable 'state' set to 0 by default.

This is how the 2D list of Cell() objects 'board' is created.

block_size = 25
board = []
rows, cols = (int((window_height - 100)/ block_size), int(window_width / block_size))
for i in range(rows):
    cell = Cell()
    col = []
    for j in range(cols):
        col.append(cell)
    board.append(col)

This is the code to update the position. mouse_round() is used to round the mouse_pos down to a multiple of 25 and block_size is the size in pixels of the squares on the screen.

if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    if mouse_pos[1] < window_height - 100:  # if a square in the board is clicked
        block_size = 25
        x, y = pygame.mouse.get_pos()
        rect = pygame.Rect(mouse_round(x), mouse_round(y), block_size, block_size)
  
        board_pos_x = int(mouse_round(y) / block_size)  
        board_pos_y = int(mouse_round(x) / block_size)

        current_pos = board[board_pos_x][board_pos_y]
        
        if current_pos.state == 0:  # if the color where they clicked is black, make it white
            current_pos.state = 1
            pygame.draw.rect(window, white, rect)

        else:  # if the color where they clicked is white, make it black  
            pygame.draw.rect(window, black, rect)
            current_pos.state = 0
        

The problem I am encountering is the state of every cell object in the row is being changed to 1 when a black square is clicked and I cannot for the life of me figure it out.

CodePudding user response:

because only 1 cell gets created per row. that same cell then gets appended to every column for that row. move the cell creation inside the column loop. i.e.

for i in range(rows):
    col = []
    for j in range(cols):
        cell = Cell()
        col.append(cell)

CodePudding user response:

Your problem is here :

for i in range(rows):
    cell = Cell()
    col = []
    for j in range(cols):
        col.append(cell)
    board.append(col)

for each row, you create a cell that will be added cols times to the column (and since Python lists are height first, I guess your whole column of identical references to the same cell becomes a row). The cell init should be in the second loop :

for i in range(rows):
    col = []
    for j in range(cols):
        cell = Cell()
        col.append(cell)
    board.append(col)
  • Related