我正在使用 pygame 制作 Conway's Game of Life,并嘗試在單擊棋盤時更新位置狀態。板上的每個位置都是一個 Cell 物件,默認情況下變數“狀態”設定為 0。
這就是創建 Cell() 物件“板”的二維串列的方式。
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,而我終生無法弄清楚。
uj5u.com熱心網友回復:
因為每行只創建 1 個單元格。然后將相同的單元格附加到該行的每一列。在列回圈內移動單元格創建。IE
for i in range(rows):
col = []
for j in range(cols):
cell = Cell()
col.append(cell)
uj5u.com熱心網友回復:
你的問題在這里:
for i in range(rows):
cell = Cell()
col = []
for j in range(cols):
col.append(cell)
board.append(col)
對于每一行,您創建一個單元格,該單元格將向cols該列添加時間(并且由于 Python 串列是高度優先的,我猜您對同一單元格的相同參考的整列變成了一行)。單元格初始化應該在第二個回圈中:
for i in range(rows):
col = []
for j in range(cols):
cell = Cell()
col.append(cell)
board.append(col)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314354.html
上一篇:根據給定的條件組成一個數字
