ATBS Python康威生命游戏代码运行仅显示空格问题排查
错误排查结果
核心问题是缩进错误,这是抄写Python代码时最高发的问题:Python不使用大括号区分代码块,完全靠缩进层级判断代码归属,你的代码里while True主循环的循环体只包含2行代码:
- 打印5个换行分隔步
- 深拷贝上一步的细胞状态到
currentCells
原本应该放在循环内部的「打印当前细胞网格」「计算下一代细胞状态」「1秒暂停防闪烁」逻辑全部顶格写在了循环外部,属于永远不会被执行的死代码。程序启动后会陷入无限空转,持续输出空行,你看到的“仅显示空格”实际是不断刷屏的空白行,活细胞渲染、演化逻辑完全没有运行。
修正后可运行代码
只需要把从# Print currentCells on the screen:开始,到time.sleep(1)结束的所有代码,统一缩进4个空格,放到while True的循环体内部即可,其他逻辑无需修改:
# 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
内容的提问来源于stack exchange,提问作者Gecko0
相关产品推荐
相关产品推荐

