[英]Stuck with ATBS with python Conway's Game of Life
在 ATBS with python 一书的第 4 章列表中有一个简短的程序:康威的生命游戏。 据我所见,我完全复制了代码。 当我运行代码时,它没有给出错误消息。 但我只看到出现空格。 我正在使用书中指出的 Mu 编辑器软件。
有人可以复制并粘贴我的代码,看看他们是否比空格更重要?
下面是代码:
# Conway's Game of Life
import random, time, copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
column = [] # Create a new column
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('#') # add a living cell
else:
column.append(' ') # add a dead cell
nextCells.append(column) # NextCells is a list of a column lists.
while True: # Main program loop
print('\n\n\n\n\n') # Seperate each step with newlines
currentCells = copy.deepcopy(nextCells)
# Print currentCells on the screen:
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') # Print the # or space
print() # Print a newline at the end of the row
# Calculate the next step's cells based on current steps cells:
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neighboring coordinates:
# '% WIDTH' ensures leftCoord is always between 0 and WIDTH -1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# Count number of living neighbors
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-left neighbor is alive
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1 # Top neighbor is alive
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-right neighbor is alive
if currentCells[leftCoord][y] == '#':
numNeighbors += 1 # Left neighbor is alive
if currentCells[rightCoord][y] == '#':
numNeighbors += 1 # Right neighbor is alive
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1 # below-left is alive
if currentCells[x][belowCoord] == '#':
numNeighbors += 1 # below is alive
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1 # below-right is alive
# Set cell based on Conway's Game of Life rules:
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
# Living cells with 2 or 3 neighbors stay alive:
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
# Dead cells with 3 neighbors become alive:
nextCells[x][y] = '#'
else:
# Everything else dies or stays dead
nextCells[x][y] = ' '
time.sleep(1) # add a 1 second pause to reduce flickering
我的代码有什么问题?
您的问题是第一个while True:
语句之后的所有内容都应该在循环内,但是,代码中的缩进(在 Python 中定义范围)导致循环范围仅跨越 2 行,而不是整个其余部分文件。
解决方案是在每行代码的开头添加一个[TAB]
while True: # Main program loop
print('\n\n\n\n\n') # Seperate each step with newlines
currentCells = copy.deepcopy(nextCells)
以便
for x in range(WIDTH):
for y in range(HEIGHT):
等等转向
for x in range(WIDTH):
for y in range(HEIGHT):
等等。 如果您使用适当的代码编辑器或 IDE,您应该能够选择所有这些行并按键盘上的[TAB]
来解决问题。
我也可以看到你提到的那本书的源代码完好无损,所以作者肯定已经解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.