康威的生命游戏没有正确计算邻居
Conway's Game of Life not counting neighbors correctly
我正在使用 Python 执行标准的 Conway 生命游戏程序。我在遍历数组时尝试计算邻居时遇到问题。我创建了 print 语句来打印 if 语句的连续性,以及每个语句的 count 值。
这是我的代码:(我在整个代码中的 # 中都有问题)
import random
numrows = 10
numcols = 10
def rnd():
rn = random.randint(0,1)
return rn
def initial():
grid = []
count = 0
for x in range(numrows):
grid.append([])
for y in range(numcols):
rand=random.randrange(1,3)
if(rand == 1):
grid[x].append('O')
else:
grid[x].append('-')
for x in grid:
print(*x, sep=' ',end="\n") #this prints the random 2d array
print("")
print("")
answer = 'y'
newgrid = []
count = 0
while(answer == 'y'): # I believe I am going through, checking neighbors
# and moving onto the next index inside these for
#loops below
for r in range(0,numrows):
grid.append([])
for c in range(0,numcols):
if(r-1 > -1 and c-1 > -1): #I use this to check out of bound
if(newgrid[r-1][c-1] == 'O'):#if top left location is O
count = count + 1 #should get count += 1
else:
count = count
print("top left check complete")
print(count)
if(r-1 > -1):
if(newgrid[r-1][c] == 'O'):
count = count + 1
else:
count = count
print("top mid check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r-1][c+1] == 'O'):
count = count + 1
else:
count = count
print("top right check complete")
print(count)
if(c-1 > -1 and r-1 > -1):
if(newgrid[r][c-1] == 'O'):
count = count + 1
else:
count = count
print("mid left check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r][c+1] == 'O'):
count = count + 1
else:
count = count
print("mid right check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c-1] == 'O'):
count = count + 1
else:
count = count
print("bot left check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c] == 'O'):
count = count + 1
else:
count = count
print("bot mid check complete")
print(count)
if(r+1 < numrows and c+1 < numcols):
if(newgrid[r+1][c+1] == 'O'):
count = count + 1
else:
count = count
print("bot right check complete")
print(count)
# I am not sure about the formatting of the code below, how do I know that
# the newgrid[r][c] location is changing? should it be according to the for-
# loop above? Or should it get it's own? If so, how could I construct it as
# to not interfere with the other loops and items of them?
if(newgrid[r][c] == '-' and count == 3):
newgrid[r][c] ='O'
elif(newgrid[r][c] == 'O' and count < 2):
newgrid[r][c] = '-'
elif(newgrid[r][c] == 'O' and (count == 2 or count == 3)):
newgrid[r][c] = 'O'
elif(newgrid[r][c] == 'O' and count > 3):
newgrid[r][c] = '-'
# I'm also confused how to go about printing out the 'new' grid after each
# element has been evaluated and changed. I do however know that after the
# new grid prints, that I need to assign it to the old grid, so that it can
# be the 'new' default grid. How do I do this?
for z in newgrid:
print(*z, sep=' ',end="\n")
answer = input("Continue? y or n( lower case only): ")
newgrid = grid
if(answer != 'y'):
print(" Hope you had a great life! Goodbye!")
initial()
这是当前的输出和错误消息:
>>> initial()
- O - - O - - O - -
- O - - O - - - O O
- O - - O - O O - O
O - - O - - O O O O
O - O O - - - O O -
O - O - O - O - O -
O - O O O O - - O -
- - - - O O O - - O
O O - O - - O - - -
- - O O O - O - - -
top left check complete
0
top mid check complete
0
top right check complete
0
mid left check complete
0
mid right check complete
0
bot left check complete
0
bot mid check complete
0
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
initial()
File "C:\Users\Ted\Desktop\combined.py", line 86, in initial
if(newgrid[r+1][c+1] == 'O'):
IndexError: list index out of range
当我遍历随机数组以查看邻居是什么时,它似乎很好,直到它在检查机器人右邻居时移动到 [0][1]。
此外,中间右侧的邻居应该 + 1 才能算作还活着。但是,即使 if 语句连续,count 仍然是 0?
问题 1:我怎么可能知道我的 if 条件是否满足数组所有边的每个 [r][c] 实例?
问题 2:我当前检查出界的方法是否最适合我的情况?有没有办法在我检查值之前制作 "check all for out of bounds"?
此时我已经束手无策了。提前感谢您抽出时间帮助回答我的问题
您收到索引错误是因为您的 newgrid
只包含一个空行。以及您在 newgrid
而不是 grid
中对邻居的测试(正如 Blckknght 在评论中提到的那样)。我进行了一些修复,但还有很多工作可以改进此代码。看起来它现在可以工作了,但是很难说什么时候你在处理随机的生命形式。 :) 我建议为您的程序提供一些使用已知生活模式(例如信号灯和滑翔机)的方法,以查看它们的行为是否正确。
确保 newgrid
有效的最简单方法是从 grid
复制它。如果我们只是做 newgrid = grid
,那只会使 newgrid
成为 grid
对象的另一个名称。要正确复制列表列表,我们需要复制每个内部列表。我的新代码使用 copy_grid
函数来做到这一点。
我已经修复了您在计算邻居部分的 if
测试中遇到的几个小错误,并且简化了根据邻居计数更新单元格的逻辑。我还压缩了生成随机网格的代码,并添加了一个简单的函数,可以从字符串中读取生命模式并从中构建网格。这让我们可以使用 Glider 测试代码。我还添加了一个生成空网格的函数。尽管我在测试期间使用了该功能,但该程序目前并未使用该功能,我想这是一个有用的示例。 :)
import random
# Set a seed so that we get the same random numbers each time we run the program
# This makes it easier to test the program during development
random.seed(42)
numrows = 10
numcols = 10
glider = '''\
----------
--O-------
---O------
-OOO------
----------
----------
----------
----------
----------
----------
'''
# Make an empty grid
def empty_grid():
return [['-' for y in range(numcols)]
for x in range(numrows)]
# Make a random grid
def random_grid():
return [[random.choice('O-') for y in range(numcols)]
for x in range(numrows)]
# Make a grid from a pattern string
def pattern_grid(pattern):
return [list(row) for row in pattern.splitlines()]
# Copy a grid, properly!
def copy_grid(grid):
return [row[:] for row in grid]
# Print a grid
def show_grid(grid):
for row in grid:
print(*row)
print()
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
count = 0
# Above this row
if(r-1 > -1 and c-1 > -1):
if(grid[r-1][c-1] == 'O'):
count += 1
if(r-1 > -1):
if(grid[r-1][c] == 'O'):
count += 1
if(r-1 > -1 and c+1 < numcols):
if(grid[r-1][c+1] == 'O'):
count += 1
# On this row
if(c-1 > -1):
if(grid[r][c-1] == 'O'):
count += 1
if(c+1 < numcols):
if(grid[r][c+1] == 'O'):
count += 1
# Below this row
if(r+1 < numrows and c-1 > -1):
if(grid[r+1][c-1] == 'O'):
count += 1
if(r+1 < numrows):
if(grid[r+1][c] == 'O'):
count += 1
if(r+1 < numrows and c+1 < numcols):
if(grid[r+1][c+1] == 'O'):
count += 1
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
if count < 2 or count> 3:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
#grid = random_grid()
grid = pattern_grid(glider)
run(grid)
此代码确实可以正常工作,但仍有 很多 改进的余地。例如,这是 run()
的改进版本,它通过使用几个循环来压缩邻居计数部分。
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
# This includes the cell itself in the count
count = 0
for y in range(max(0, r - 1), min(r + 2, numrows)):
for x in range(max(0, c - 1), min(c + 2, numcols)):
count += grid[y][x] == 'O'
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
# Remember, this count includes the cell itself
if count < 3 or count > 4:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
要计算邻居,只需遵循这个简单的规则。您将拥有当前单元格的行和列。使用它形成两个数组,一个用于行,另一个用于列。以下是您的逻辑。
您可以通过演示视频找到详细的实现方式 here。
this.neibhours = function() {
var rows = [row-1, row, row+1];
var cols = [col-1, col, col+1];
neibhourCells = [];
for(var i=0; i < rows.length; i++) {
for(var j=0; j < cols.length; j++) {
if(!(col === cols[j] && row === rows[i])) {
var cell = new Cell(rows[i], cols[j])
if(cell.isOnGrid()) {
neibhourCells.push(cell);
}
}
}
}
return neibhourCells;
}
我正在使用 Python 执行标准的 Conway 生命游戏程序。我在遍历数组时尝试计算邻居时遇到问题。我创建了 print 语句来打印 if 语句的连续性,以及每个语句的 count 值。
这是我的代码:(我在整个代码中的 # 中都有问题)
import random
numrows = 10
numcols = 10
def rnd():
rn = random.randint(0,1)
return rn
def initial():
grid = []
count = 0
for x in range(numrows):
grid.append([])
for y in range(numcols):
rand=random.randrange(1,3)
if(rand == 1):
grid[x].append('O')
else:
grid[x].append('-')
for x in grid:
print(*x, sep=' ',end="\n") #this prints the random 2d array
print("")
print("")
answer = 'y'
newgrid = []
count = 0
while(answer == 'y'): # I believe I am going through, checking neighbors
# and moving onto the next index inside these for
#loops below
for r in range(0,numrows):
grid.append([])
for c in range(0,numcols):
if(r-1 > -1 and c-1 > -1): #I use this to check out of bound
if(newgrid[r-1][c-1] == 'O'):#if top left location is O
count = count + 1 #should get count += 1
else:
count = count
print("top left check complete")
print(count)
if(r-1 > -1):
if(newgrid[r-1][c] == 'O'):
count = count + 1
else:
count = count
print("top mid check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r-1][c+1] == 'O'):
count = count + 1
else:
count = count
print("top right check complete")
print(count)
if(c-1 > -1 and r-1 > -1):
if(newgrid[r][c-1] == 'O'):
count = count + 1
else:
count = count
print("mid left check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r][c+1] == 'O'):
count = count + 1
else:
count = count
print("mid right check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c-1] == 'O'):
count = count + 1
else:
count = count
print("bot left check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c] == 'O'):
count = count + 1
else:
count = count
print("bot mid check complete")
print(count)
if(r+1 < numrows and c+1 < numcols):
if(newgrid[r+1][c+1] == 'O'):
count = count + 1
else:
count = count
print("bot right check complete")
print(count)
# I am not sure about the formatting of the code below, how do I know that
# the newgrid[r][c] location is changing? should it be according to the for-
# loop above? Or should it get it's own? If so, how could I construct it as
# to not interfere with the other loops and items of them?
if(newgrid[r][c] == '-' and count == 3):
newgrid[r][c] ='O'
elif(newgrid[r][c] == 'O' and count < 2):
newgrid[r][c] = '-'
elif(newgrid[r][c] == 'O' and (count == 2 or count == 3)):
newgrid[r][c] = 'O'
elif(newgrid[r][c] == 'O' and count > 3):
newgrid[r][c] = '-'
# I'm also confused how to go about printing out the 'new' grid after each
# element has been evaluated and changed. I do however know that after the
# new grid prints, that I need to assign it to the old grid, so that it can
# be the 'new' default grid. How do I do this?
for z in newgrid:
print(*z, sep=' ',end="\n")
answer = input("Continue? y or n( lower case only): ")
newgrid = grid
if(answer != 'y'):
print(" Hope you had a great life! Goodbye!")
initial()
这是当前的输出和错误消息:
>>> initial() - O - - O - - O - - - O - - O - - - O O - O - - O - O O - O O - - O - - O O O O O - O O - - - O O - O - O - O - O - O - O - O O O O - - O - - - - - O O O - - O O O - O - - O - - - - - O O O - O - - - top left check complete 0 top mid check complete 0 top right check complete 0 mid left check complete 0 mid right check complete 0 bot left check complete 0 bot mid check complete 0 Traceback (most recent call last): File "<pyshell#68>", line 1, in <module> initial() File "C:\Users\Ted\Desktop\combined.py", line 86, in initial if(newgrid[r+1][c+1] == 'O'): IndexError: list index out of range
当我遍历随机数组以查看邻居是什么时,它似乎很好,直到它在检查机器人右邻居时移动到 [0][1]。
此外,中间右侧的邻居应该 + 1 才能算作还活着。但是,即使 if 语句连续,count 仍然是 0?
问题 1:我怎么可能知道我的 if 条件是否满足数组所有边的每个 [r][c] 实例?
问题 2:我当前检查出界的方法是否最适合我的情况?有没有办法在我检查值之前制作 "check all for out of bounds"?
此时我已经束手无策了。提前感谢您抽出时间帮助回答我的问题
您收到索引错误是因为您的 newgrid
只包含一个空行。以及您在 newgrid
而不是 grid
中对邻居的测试(正如 Blckknght 在评论中提到的那样)。我进行了一些修复,但还有很多工作可以改进此代码。看起来它现在可以工作了,但是很难说什么时候你在处理随机的生命形式。 :) 我建议为您的程序提供一些使用已知生活模式(例如信号灯和滑翔机)的方法,以查看它们的行为是否正确。
确保 newgrid
有效的最简单方法是从 grid
复制它。如果我们只是做 newgrid = grid
,那只会使 newgrid
成为 grid
对象的另一个名称。要正确复制列表列表,我们需要复制每个内部列表。我的新代码使用 copy_grid
函数来做到这一点。
我已经修复了您在计算邻居部分的 if
测试中遇到的几个小错误,并且简化了根据邻居计数更新单元格的逻辑。我还压缩了生成随机网格的代码,并添加了一个简单的函数,可以从字符串中读取生命模式并从中构建网格。这让我们可以使用 Glider 测试代码。我还添加了一个生成空网格的函数。尽管我在测试期间使用了该功能,但该程序目前并未使用该功能,我想这是一个有用的示例。 :)
import random
# Set a seed so that we get the same random numbers each time we run the program
# This makes it easier to test the program during development
random.seed(42)
numrows = 10
numcols = 10
glider = '''\
----------
--O-------
---O------
-OOO------
----------
----------
----------
----------
----------
----------
'''
# Make an empty grid
def empty_grid():
return [['-' for y in range(numcols)]
for x in range(numrows)]
# Make a random grid
def random_grid():
return [[random.choice('O-') for y in range(numcols)]
for x in range(numrows)]
# Make a grid from a pattern string
def pattern_grid(pattern):
return [list(row) for row in pattern.splitlines()]
# Copy a grid, properly!
def copy_grid(grid):
return [row[:] for row in grid]
# Print a grid
def show_grid(grid):
for row in grid:
print(*row)
print()
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
count = 0
# Above this row
if(r-1 > -1 and c-1 > -1):
if(grid[r-1][c-1] == 'O'):
count += 1
if(r-1 > -1):
if(grid[r-1][c] == 'O'):
count += 1
if(r-1 > -1 and c+1 < numcols):
if(grid[r-1][c+1] == 'O'):
count += 1
# On this row
if(c-1 > -1):
if(grid[r][c-1] == 'O'):
count += 1
if(c+1 < numcols):
if(grid[r][c+1] == 'O'):
count += 1
# Below this row
if(r+1 < numrows and c-1 > -1):
if(grid[r+1][c-1] == 'O'):
count += 1
if(r+1 < numrows):
if(grid[r+1][c] == 'O'):
count += 1
if(r+1 < numrows and c+1 < numcols):
if(grid[r+1][c+1] == 'O'):
count += 1
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
if count < 2 or count> 3:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
#grid = random_grid()
grid = pattern_grid(glider)
run(grid)
此代码确实可以正常工作,但仍有 很多 改进的余地。例如,这是 run()
的改进版本,它通过使用几个循环来压缩邻居计数部分。
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
# This includes the cell itself in the count
count = 0
for y in range(max(0, r - 1), min(r + 2, numrows)):
for x in range(max(0, c - 1), min(c + 2, numcols)):
count += grid[y][x] == 'O'
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
# Remember, this count includes the cell itself
if count < 3 or count > 4:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
要计算邻居,只需遵循这个简单的规则。您将拥有当前单元格的行和列。使用它形成两个数组,一个用于行,另一个用于列。以下是您的逻辑。
您可以通过演示视频找到详细的实现方式 here。
this.neibhours = function() {
var rows = [row-1, row, row+1];
var cols = [col-1, col, col+1];
neibhourCells = [];
for(var i=0; i < rows.length; i++) {
for(var j=0; j < cols.length; j++) {
if(!(col === cols[j] && row === rows[i])) {
var cell = new Cell(rows[i], cols[j])
if(cell.isOnGrid()) {
neibhourCells.push(cell);
}
}
}
}
return neibhourCells;
}