gpt4 book ai didi

python - 使用 pygame 在 "Game of life"中查找相邻单元格的错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:15 25 4
gpt4 key购买 nike

我正在用 python 和 pygame 制作一个版本的“Conway's game of life”,但我无法找到相邻的单元格。下面是大部分代码。我删除了不必要的部分,因为问题出在 cell.get_neighbors() 函数上。想看剩下的可以看下here .

def main():
while True:

draw_board()
update_cells()

pygame.display.update()
fpsClock.tick(FPS)

def update_cells():
event_handling()

if clicked == True:
cell = where_clicked(mousex, mousey)
if cell != None:
print (cell.get_neighbors())

class cell:
#The problem is with this function
def get_neighbors(self):
neighbors = []
for y in (-1, 0, 1):
for x in (-1, 0, 1):
neighbor = find_cell(x + self.x, y + self.y)
if neighbor not in (None, self):
neighbors.append(neighbor)
#I added neighbor.switch() so that I could easily see which cells were being returned by the get_neighbors() function.
neighbor.switch()
return neighbors

def switch(self):
if self.alive == False:
self.alive = True
else:
self.alive = False

def find_cell(x, y):
for CELL in board:
if CELL.x == x:
if CELL.y == y:
return CELL

if __name__ == '__main__':
main()

上面写的 get_neighbors() 函数应该将所有 8 个相邻的单元格变成黑色,但它会将 4-10 个看似随机的单元格变成黑色。我做了 this屏幕录像来演示问题。如您所见,如果我单击左上角或顶部,它会正常工作,但当我单击中间时,它会执行如下操作:

http://www.imagesup.net/?di=8140372670715

或者这个:

http://www.imagesup.net/?di=1514037265628

或者这个:

http://www.imagesup.net/?di=1014037266308

我错过了什么吗?因为 cell.get_neighbors() 应该可以正常工作。 find_cell() 工作正常,并且

for y in (-1, 0, 1):
for x in (-1, 0, 1):
...
find_cell(x, y)

应该像这样找到每个相邻的单元格。

(-1, -1), (-1, 0), (-1, 1)
( 0, -1), ( 0, 0), ( 0, 1)
( 1, -1), ( 1, 0), ( 1, 1)

if neighbor not in (None, self):

应该防止它返回板外的任何单元格,并防止它返回自己。 (因为一个单元格不能是它自己的邻居)。

感谢任何帮助!

最佳答案

在你发布的代码中你有

neighbor = find_cell(x + self.x, y + self.y)

但是,在您的链接代码中有

for y in (-1, 0, 1):
for x in (-1, 0, 1):
x += self.x
y += self.y

请注意在您的图像中,切换后的单元格似乎是向下移动的。这是因为您在内循环中修改了 y 三次,然后才将其重置为 [-1, 0, 1] 值之一。只运行循环并打印出值,您会看到内循环中的 y 发生了不应该发生的变化。

点击顶部时看起来不错,因为递增的 y 值 self.y 为零。另请注意,您单击的窗口越往下,步进如何变得越夸张。

将您的运行代码更改为您发布的代码,它应该可以正常工作。

关于python - 使用 pygame 在 "Game of life"中查找相邻单元格的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24417658/

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