问题描述
我正在尝试用 Python 制作 Conway's Game of Life(我只是将它放在我的 discord 机器人中,因为为什么不呢)。我的问题是,当我运行它时,没有任何反应,消息没有被编辑。没有错误消息。我想代码认为上一代没有任何变化,所以它停止了,尽管有些东西已经发生了。
这是我的代码,我相信问题出在环境函数或 for y,row in enumerate(grid):
循环中。
@commands.command()
async def gameoflife(self,ctx):
grid = [[0 for i in range(15)] for i in range(13)]
grid[5][5],grid[5][6],grid[5][7] = (1,1,1) #just a simple blinker for Now
def emojify(i):
convert = {0 : '⬛',1 : '⬜'}
return convert[i]
gridmap = '\n'.join([''.join(list(map(emojify,i))) for i in grid])
embed = discord.Embed(colour = 0xf1c40f)
embed.set_author(name = 'CONWAY\'S GAME OF LIFE')
embed.add_field(name = '_ _',value = gridmap,inline = False)
embed.set_footer(text = 'Generation 1')
m = await ctx.send(embed = embed)
def surroundings(y,x):
count = 0
surrtiles = ((-1,0),(-1,1),(0,(1,-1),-1))
for i in surrtiles:
row = y
column = x
if row > 11 and i[0] == 1:
row = 0
if column > 13 and i[1] == 1:
column = 0
if grid[row + i[0]][column + i[1]] == 1:
count += 1
return count
gen = 1
while True:
gen += 1
await asyncio.sleep(2.0)
nextgrid = grid[:]
for y,row in enumerate(grid):
for x,column in enumerate(row):
if surroundings(y,x) == 3:
nextgrid[y][x] = 1
if surroundings(y,x) > 3:
nextgrid[y][x] = 0
if surroundings(y,x) < 2:
nextgrid[y][x] = 0
if nextgrid == grid:
break
else:
grid = nextgrid[:]
gridmap = '\n'.join([''.join(list(map(emojify,i))) for i in grid])
embed = discord.Embed(colour = 0xf1c40f)
embed.set_author(name = 'CONWAY\'S GAME OF LIFE')
embed.add_field(name = '_ _',inline = False)
embed.set_footer(text = f'Generation {gen}')
await m.edit(embed = embed)
解决方法
解决了问题。尽管 nextgrid
是 grid
的单独副本,但它存储的列表不是。我刚刚用 nextgrid = grid[:]
替换了 nextgrid = [i[:] for i in grid]
,效果很好!