gpt4 book ai didi

python - 康威的生命游戏 pygame 实现不使用网格副本,不使用 numpy

转载 作者:行者123 更新时间:2023-12-04 09:43:39 25 4
gpt4 key购买 nike

我正在尝试使用 pygame 在 python 中实现康威的生活游戏。但是,主循环中每个单元格的计算似乎都有问题。为确保每个计算同时完成,我创建了网格的副本并在该网格上进行了计算。然而,该程序不起作用,我无法弄清楚。这是我的代码的副本。

import pygame
import time

def create_grid(ROWS, COLS, SCREEN):
"""Creates a grid, sets all values to 0"""
assert ROWS > 0, "ROWS must be greater than 0"
assert COLS > 0, "COLS must be greater than 0"

grid = []
for i in range(ROWS):
grid.append([])
for j in range(COLS):
grid[i].append(0)
return grid

pygame.init()

#SCREEN setup
ScreenHeight = 700
ScreenWidth = 700
SCREEN_COLOR = (20, 20, 20)

SCREEN = pygame.display.set_mode((ScreenWidth, ScreenHeight)) #Create Screen
SCREEN.fill(SCREEN_COLOR)


#Number of ROWS and COLUMNS
ROWS = 30
COLS = 40

#How far will the next cube be placed
SQUARESTEPY = ScreenWidth / ROWS
SQUARESTEPX = ScreenWidth / COLS

GREY = (70, 70, 70)
WHITE = (255, 255, 255)

#draw grid
grid = create_grid(ROWS, COLS, SCREEN)

# grid[0][0] = 1
# grid[1][0] = 1
# grid[0][1] = 1

while True:

#create a copy of the grid to calculate the condition of all cells at the same time
copy_of_grid = grid[:]

for ev in pygame.event.get():
#Quit the game
if ev.type == pygame.QUIT:
pygame.quit()

#if mouse click draws or erases a cell
if pygame.MOUSEBUTTONDOWN == ev.type:
posX, posY = pygame.mouse.get_pos()
print(posX, posY)
posX, posY = int(posX / SQUARESTEPX), int(posY / SQUARESTEPY)
grid[posY][posX] = 1 - grid[posY][posX]

#calculate conway's rules and draw each cell
for y in range(ROWS):
for x in range(COLS):
neighbors = copy_of_grid[(y - 1) % ROWS][(x - 1) % COLS] + \
copy_of_grid[y % ROWS][(x - 1) % COLS] + \
copy_of_grid[(y + 1) % ROWS][(x - 1) % COLS] + \
copy_of_grid[(y - 1) % ROWS][x % COLS] + \
copy_of_grid[(y + 1) % ROWS][x % COLS] + \
copy_of_grid[(y - 1) % ROWS][(x + 1) % COLS] + \
copy_of_grid[y % ROWS][(x + 1) % COLS] + \
copy_of_grid[(y + 1) % ROWS][(x + 1) % COLS]
#print(x, y, "neighbors: {}, ON: {}".format(neighbors, grid[y][x]))

#A dead cell surrounded by exactly 3 cells will revive
if copy_of_grid[y][x] == 0 and (neighbors == 3 or neighbors == 2):
grid[y][x] = 1

#A living cell surrounded by less than 2 or more than 3 neighbors wil die
elif grid[y][x] == 1 and (neighbors < 2 or neighbors > 3):
grid[y][x] = 0

#paint
if grid[y][x] == 1:
pygame.draw.rect(SCREEN, WHITE, (SQUARESTEPX * x, SQUARESTEPY * y, SQUARESTEPX, SQUARESTEPY))
else:
pygame.draw.rect(SCREEN, SCREEN_COLOR , (SQUARESTEPX * x, SQUARESTEPY * y, SQUARESTEPX, SQUARESTEPY))


pygame.display.flip()
time.sleep(0.1)

pygame.quit()

最佳答案

copy_of_grid = grid[:]不是网格的副本。它是外部列表的浅拷贝(见 Lists)。但是列表中的元素copy_of_grid仍然与列表中的元素相同 grid .
您必须在循环中复制嵌套列表:

copy_of_grid = []
for row in grid:
copy_of_grid.append(row[:])

关于python - 康威的生命游戏 pygame 实现不使用网格副本,不使用 numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62221456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com