邻里生活游戏

2024-05-29 04:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python创建我的Game of life代码,但是当它检查相邻的邻居时,似乎有问题。我试着解决这个问题已经两天了,但我还是不知道我遗漏了什么。 这是代码分成几部分。在

from random import randrange
from tkinter import *
from time import sleep
root = Tk()
canv = Canvas(width = 800, height = 800)
canv.pack()

def value():
    if randrange(16) == 0:
        return 1
    else:
        return 0 

我在tkinter中设置画布,并创建一个函数来确定一个单元格的状态,因此每个单元格都有1/x的机会先生存。在

^{pr2}$

我在调试时创建了一个漂亮的打印函数。在

def nb(life,row,col):
    count = 0
    #print(x,y)
    #print(life[x][y])
    for r in [row-1, row, row+1]:
        for c in [col-1,col,col+1]:
            if life[r][c] == 1:
                count += 1
    if life[row][col] == 1:
        count -= 1
    #print(count,end=" ")
    return count

这个函数用来返回一个细胞有多少个邻居。(整个代码的调试都留下了注释)

def ud(life,life2,size,box):        
    #print(life)        
    while True:
        try:
            for row in range(1,size+1):
                for col in range(1,size+1):
                    #print(row,col)
                    a = nb(life,row,col)
                    print("[{0},{1}]".format(row,col), end =" ")
                    print(a, end=" ")

                    if ((1<a) and (a<4)):
                        life2[row][col] = 1
                        canv.itemconfig(box[row-1][col-1], fill ="black")

                    else:
                        life2[row][col] = 0
                        canv.itemconfig(box[row-1][col-1], fill ="white")
                print("")                         
            print("ok")
            #print(life2[19][19])
            root.update()
            pprint(life)
            #sleep(5)

            life = life2
            sleep(800/size**2)
            print("")
        except:
            break

这是主要的更新功能。它应该为life 2d数组中的每个单元格运行nb函数,并确定它在life2中的值。”box”是一个二维数组,它包含可视网格上每个单元格的矩形tkinter id。(是的,打印功能也用于调试。)

#######
size = 10
w = 10
box = [[canv.create_rectangle(y*w,x*w,y*w+10,x*w+10) for y in range(size)] for x in range(size)]
life = [[value() for y in range(size)] for x in range(size)]
life2 = [[0 for y in range(size+2)] for x in range(size+2)]
for i in range(1,size+1):
    life2[i] = [0] + life[i-1] + [0]
#life = life2

pprint(life)
root.update()
ud(life2,life2,size,box)

del box
del life
del life2

我创建box变量(w=单元格的宽度)并生成随机的活动单元格。然后我为“生命”创建了一个“0”帧(这样程序在拐角处时不会中断nb检查)。我知道我可以用try/except)。然后我用参数启动ud函数(size=一行中的单元格数量;两个life矩阵参数都是life2,因为理论上第二个参数将被完全重写)

那么这个程序有什么问题呢?在


Tags: 函数inboxforsizeifcountrange
1条回答
网友
1楼 · 发布于 2024-05-29 04:36:19

def ud(life,life2,size,box):内的这一行life = life2使得life和{}都指向相同的数据。您需要deep copylife2,并让life指向那个绝对独立的数据。在

Deep copy,因为您的life2包含其他列表,并且如果您只通过live = life2[:]进行浅拷贝,您仍然会遇到相同的问题-live将在其内部列出唯一的引用,但是内部列表的引用所指向的数据仍将是共享的。您使用^{} & ^{}进行深度复制。在


重命名

import copy
print()
a = [[1,3,5],[2,4,6]]
b = a  # second name, same data
a[0] = [0,8,15]    # replaces the ref on a[0] with a new one, b == a 
a[1][2] = 99       # modifies a value inside the 2nd list ref, b == a
print (a,"=>",b)   # b is just another name for a

输出

^{pr2}$

浅拷贝

a = [[1,3,5],[2,4,6]]
b = a[:]  # shallow copy
a[0] = [0,8,15]       # replaces one ref with a new one (only in a)
a[1][2] = 99          # modifies the value inside 2nd list, same ref in a&b
print (a,"=>",b)

输出

# b got "unique" refs to the inner lists, if we replace one in a 
# this does not reflect in b as its ref is unique. chaning values 
# inside a inner list, will be reflected, as they are not uniqe
([[0, 8, 15], [2, 4, 99]], '=>', [[1, 3, 5], [2, 4, 99]])

深度复制

a = [[1,3,5],[2,4,6]]
b = copy.deepcopy(a)  # deep copy
a[0] = [0,8,15]       # only a modified
a[1][2] = 99          # only in a modified
print (a,"=>",b)

输出

# completely independent - b shares no refs with former a, all got new'ed up
([[0, 8, 15], [2, 4, 99]], '=>', [[1, 3, 5], [2, 4, 6]])

如果将上面的print替换为

print(id(a), id(a[0]), id(a[1]), id(b), id(b[0]), id(b[1]))

您将得到a的唯一id及其内容的输出,以及b及其内容的输出:

重命名

`a`: 139873593089632, 139873593146976, 139873593072384 
`b`: 139873593089632, 139873593146976, 139873593072384

浅层:

`a`: 139873593229040, 139873593089632, 139873593146040
`b`: 139873593227168, 139873593088552, 139873593146040

深度:

`a`: 139873593253968, 139873593227168, 139873593072384
`b`: 139873593229040, 139873593089632, 139873593254112

相关问题 更多 >

    热门问题