首页 > 解决方案 > Python 更新二维列表中的对象

问题描述

我正在使用 pygame 制作康威的生命游戏,并尝试在单击棋盘时更新位置状态。棋盘上的每个位置都是一个 Cell 对象,其变量“状态”默认设置为 0。

这就是如何创建 Cell() 对象“板”的 2D 列表的方式。

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)

这是更新位置的代码。mouse_round() 用于将 mouse_pos 向下舍入为 25 的倍数,block_size 是屏幕上正方形的像素大小。

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
        

我遇到的问题是,当单击黑色方块时,行中每个单元格对象的状态都更改为 1,而我终生无法弄清楚。

标签: pythonpython-3.xlistobject

解决方案


因为每行只创建 1 个单元格。然后将同一单元格附加到该行的每一列。在列循环内移动单元格创建。IE

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

推荐阅读