gpt4 book ai didi

python - 康威生命游戏的问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:21 29 4
gpt4 key购买 nike

我遇到了一个问题,我没有成功地通过其他人的帖子找到解决方案。我们遵循康威生命游戏的标准规则。

到目前为止,我已经能够创建二维数组,并使用随机字符“-”(表示死亡)和“O”(表示活着)填充数组(字母 O 不是数字零)。我相信我正在正确地检查和检查所有邻居。 * 我使用 try/catch 的原因是因为这是我能够弄清楚如何避免收到越界错误消息的唯一方法。

我的主要问题是,我不确定在检查/更改值时是否正确地遍历数组。另外,我不确定在将活/死规则应用于整个数组后如何打印“更新的”二维数组。

截至目前,输出打印一次随机数组,然后再次打印完全相同的数组,然后询问我是否要继续(再次执行 while 循环)。如果我选择“y”,我会收到错误消息

TypeError: list indices must be integers, not list

我已经迷失了方向,任何想法都会有所帮助,因为我已经进入 python 大约 3 周了。

这是我的代码:

import random

numrows = 25
numcols = 25


def rnd():
rn = random.randint(0,1)
return rn


def initial():

grid = []
count = 0

for x in range(numrows):
grid.append([])
for y in range(numcols):
rand=random.randrange(1,3)
if(rand == 1):
grid[x].append('O')
else:
grid[x].append('-')

for x in grid:
print(*x, sep=' ',end="\n") #prints initial grid with random values

print("")# space for clarity sake
print("")# " "

answer = 'y'
count = 0

while(answer == 'y'):

#This is where I am checking each neighbor. Adding 1 to count for each
#live neighbor.

for r in range(0,numrows):
for c in range(0,numcols):


try:
if(grid[r-1][c-1] == 'O'):
count += 1

except:
pass

try:
if(grid[r-1][c] == 'O'):
count += 1

except:
pass

try:
if(grid[r-1][c+1] == 'O'):
count += 1

except:
pass

try:
if(grid[r][c-1] == 'O'):
count += 1

except:
pass

try:

if(grid[r][c+1] == 'O'):
count += 1

except:
pass

try:
if(grid[r+1][c-1] == 'O'):
count += 1

except:
pass

try:
if(grid[r+1][c] == 'O'):
count += 1

except:
pass

try:
if(grid[r+1][c+1] == 'O'):
count += 1

except:
pass


#this is where I am applying the rules of living or dying
#based on how many neighbors there are.

if(grid[r][c] == '-'):
if(count == 3):
grid[r][c].append('O')

if(grid[r][c] == 'O'):
if(count < 2):
grid[r][c].append('-')

if(grid[r][c] == 'O'):
if(count == 2 or count == 3):
grid[r][c].append('O')

if(grid[r][c] == 'O'):
if(count > 3):
grid[r][c].append('-')

for r in grid: #This is a problem area as i dont
print(*r, sep=' ',end="\n")#know how to print the grid

answer = input("Continue? y or n( lower case only): ")

if(answer != 'y'):
print(" Hope you had a great life! Goodbye!")

最佳答案

问题是这样的:崩溃发生在 if 行:

                if(grid[r][c] == '-'):  # <=== here on this line
if(count == 3):
grid[r][c].append('O')

在那一行,r不再是一个整数,而是一个列表。但为什么?答案出现在几行之后:

            for r in grid:                 #This is a problem area as i dont
print(*r, sep=' ',end="\n")#know how to print the grid

在这个 block 中,r 是一个 int,但现在你把它变成了一个列表。我承认你的评论,关于不知道如何打印网格,所以我可以建议一个快速:

print('\n'.join(' '.join(str(cell) for cell in row) for row in grid))

这样,您就不会覆盖变量r

关于python - 康威生命游戏的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371283/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com