我正在制作一个版本的“康威的生命游戏”,在蟒蛇和蟒蛇游戏,但我在寻找附近的细胞有困难。下面是大部分代码。我编辑了不必要的部分,因为问题在于cell.get_neighbors()函数。如果你想看它的其余部分,你可以阅读它这里。
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个看似随机的单元变成黑色。我制作了这屏幕记录来演示这个问题。正如您所看到的,如果我在左上角或顶部单击,它的工作方式就像它应该做的那样,但是当我在中间单击时,它会执行如下操作:
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):应该防止它返回板外的任何单元格,也不能返回自己。(因为细胞不可能是自己的邻居)。
任何帮助都是非常感谢的!
发布于 2014-06-25 20:40:08
在你贴出的代码里
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是零。还请注意,如果单击的窗口越远,步进就会变得更加夸张。
将正在运行的代码更改为您发布的代码,它应该可以正常工作。
https://stackoverflow.com/questions/24417658
复制相似问题