python - 尝试用 Python 制作康威的生命游戏
问题描述
我正在尝试用 Python 制作 Conway 的生命游戏(我只是把它放在我的 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),
(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 = '_ _', value = gridmap, inline = False)
embed.set_footer(text = f'Generation {gen}')
await m.edit(embed = embed)
解决方案
解决了这个问题。虽然nextgrid
是 的单独副本grid
,但它存储的列表不是。我刚刚替换nextgrid = grid[:]
为nextgrid = [i[:] for i in grid]
,它工作正常!
推荐阅读
- haskell - 如何检查 Text.XML.Cursor 中节点的内容?
- assertj - 如何在 AssertJ 中链接多个 assertThat 语句
- node.js - 如何在环回 3 中需要时自动迁移?
- ios - Face ID userFallback在iOS swift中不起作用
- mysql - mysql 0000-00-00 00:00:00 转换为空
- javascript - 三.js子忽略父变换
- spring-mvc - 如何在spring mvc中了解当前登录用户的详细信息
- android - 如何创建位置对象
- amazon-web-services - 如何在 AWS SNS API 触发器中添加自定义标头?
- javascript - 如何更新我的 NodeJS 安装的 v8 (Javascript) 版本?