Luk*_*lor 15 python conways-game-of-life
我的Conway在Python中的生活游戏实现似乎没有正确遵循规则,我无法弄清楚可能出错的地方.当我将最终配置放入Golly时,它会继续超出我的范围.
我首先通过将我的程序停止进入Golly的配置来识别程序,然后注意到它可以进一步传送.
我还把我的游戏中的整个小板放到了Golly中,它与我的配置有很大的不同.Golly是一款广泛使用的生命模拟器游戏.
我尝试了几种不同的方法来解决我的问题:
and/ orstatements.neighbors()通过将其插入到自己的程序中并设置一些网格配置来测试我的功能.neighbors()了一个位置.它工作得很好.看着我的代码,我看不出它为什么不起作用.我没有得到错误,它有效,它只是错误.模式的进展与它们的应用方式大不相同.这也是我编写的第一个> 100行程序,如果没有松散地遵循教程,请原谅我,如果答案是显而易见的.
相关代码如下:
#Function to find number of live neighbors
def neighbors(row, column):
adjacents = 0
#Horizontally adjacent
if row > 0:
if board[row-1][column]:
adjacents += 1
if column > 0:
if board[row][column-1]:
adjacents += 1
if row < thesize-1:
if board[row+1][column]:
adjacents += 1
if column < thesize-1:
if board[row][column+1]:
adjacents += 1
#Diagonally adjacent
if row > 0 and column > 0:
if board[row-1][column-1]:
adjacents += 1
if row < thesize-1 and column < thesize-1:
if board[row+1][column+1]:
adjacents += 1
if row > 0 and column < thesize-1:
if board[row-1][column+1]:
adjacents += 1
if row < thesize-1 and column > 0:
if board[row+1][column-1]:
adjacents += 1
#Return the final count (0-8)
return adjacents
Run Code Online (Sandbox Code Playgroud)
这似乎可以完美地返回任何给定细胞的8个邻居中有多少是活着的.下一位是逻辑部分,我认为问题在于.它根据游戏规则改变阵列.
#Main loop
while 1:
#Manage the rules of the game
for r in range(len(board)):
for c in range(len(board)):
neighborcount = neighbors(r, c)
if board[r][c]:
giveLife(r, c)
if neighborcount < 2 or neighborcount > 3:
board[r][c] = False
elif not board[r][c]:
killRuthlessly(r, c)
if neighborcount == 3:
board[r][c] = True
Run Code Online (Sandbox Code Playgroud)
最后,在pygame屏幕上可视化地打开和关闭正方形的部分.这是经过测试的,似乎效果很好,我只是觉得我会把它包括在内,以防出现问题.
for r in range(len(board)):
for c in range(len(board)):
if board[r][c]:
giveLife(r, c)
if not board[r][c]:
killRuthlessly(r, c)
Run Code Online (Sandbox Code Playgroud)
giveLife是一个在给定位置killRuthlessly绘制黑色矩形的函数,绘制一个白色矩形.这两者似乎都正常工作.
Isa*_*man 12
对于循环通过电路板并检查相邻单元的逻辑,它正在打开/关闭单元,同时继续检查其他单元.您可能正在阅读相邻的单元格,不是因为它们处于上一个时间步骤(这很重要),而是因为它们已经已经完成了已经循环的状态.尝试创建一个tmp_board复制当前电路板以及进行编辑的电路板.然后将它复制回到board你完成所有内容之后.
| 归档时间: |
|
| 查看次数: |
454 次 |
| 最近记录: |