conway的生命游戏
import random, time, copyWIDTH = 60
HEIGHT = 20
nextCells = []
for i in range(WIDTH):
column = []
for y in range(HEIGHT):
if random.randint(0, 1):
column.append('#')
else:
column.append(' ')
nextCells.append(column)
while True:
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells, end='')
print()
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x-1) % WIDTH
rightCoord = (x+1) % WIDTH
aboveCoord = (y-1) % HEIGHT
belowCoord = (y+1) % HEIGHT
numNeighbors = 0
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells = '#'
elif currentCells == ' ' and numNeighbors == 3:
nextCells = '#'
else:
nextCells = ''
time.sleep(1)
这是一个小游戏。它在《python编程快速上手-让繁琐工作自动化(第2版)》中的第四章。
我按照书原样输入,结果却是错误的。我尝试了把while循环后的第二个嵌套for循环减少缩进,但是结果还是只输入了一副图。
什么原因呢?哪位前辈帮忙解决一下啊?谢谢 你看看你要的是不是这个意思:
import random, time, copy
WIDTH = 60
HEIGHT = 20
while True:
nextCells = []
for i in range(WIDTH):
column = []
for y in range(HEIGHT):
if random.randint(0, 1):
column.append('#')
else:
column.append(' ')
nextCells.append(column)
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells, end='')
print()
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x-1) % WIDTH
rightCoord = (x+1) % WIDTH
aboveCoord = (y-1) % HEIGHT
belowCoord = (y+1) % HEIGHT
numNeighbors = 0
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#':
numNeighbors += 1
if currentCells == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells = '#'
elif currentCells == ' ' and numNeighbors == 3:
nextCells = '#'
else:
nextCells = ''
nahongyan1997 发表于 2021-6-25 14:23
你看看你要的是不是这个意思:
对的,谢谢啊。
页:
[1]