如何修改找色块游戏的代码?


from tkinter import *
import random

win=Tk()
win.geometry('270x270')
win.resizable(0,0)


num=1
inde=random.randint(0,99)
def col():
    arr=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    color1=''
    color2=''
    color3=''
    for i in range(4):
        color1+=arr[random.randint(0,15)]
    for i in range(2):
        color2+=arr[random.randint(0,15)]
    for i in range(2):
        color3+=arr[random.randint(0,15)]
    colorArr=[]
    colorArr.append('#' + color1 + color2)
    colorArr.append('#' + color1 + color3)
    return colorArr

def judge(event):
    global num
    num+=1
    level.config(text='第'+str(num)+'关')
    inde=random.randint(1,100)
    colorBox=col()
    for i in sqareBox:
        i.config(bg=colorBox[0])
        sqareBox[inde].config(bg=colorBox[2])
        sqareBox[inde].bind('<Button-1>',judge)

sqareBox=[]
colorBox=col()

for i in range(10):
    for j in range(10):
        label=Label(win,width=3,height=1,bg=colorBox[0],relief='groove')
        sqareBox.append(label)
        label.grid(row=i,column=j)

sqareBox[inde].config(bg=colorBox[1])
sqareBox[inde].bind('<Button-1>',judge)
level=Label(win,text='第1关',font=14)
level.grid(row=11,column=0,columnspan=10,pady=10)
win.mainloop()

如图,这是一个找不同色块游戏的代码。现在玩到第2关就会出错,第2关还会显示上一关不同的色块(图中紫色),且第2关不同色块的位置被固定在了第1行第1列(图中绿色)。请修改代码使游戏能正确运行

​​

img

 

原因是colorBox元素序号错了,只有两个元素。

 
from tkinter import *
import random
 
win=Tk()
win.geometry('270x270')
win.resizable(0,0)
 
 
num=1
inde=random.randint(0,99)
def col():
    arr=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    color1=''
    color2=''
    color3=''
    for i in range(4):
        color1+=arr[random.randint(0,15)]
    for i in range(2):
        color2+=arr[random.randint(0,15)]
    for i in range(2):
        color3+=arr[random.randint(0,15)]
    colorArr=[]
    colorArr.append('#' + color1 + color2)
    colorArr.append('#' + color1 + color3)
    return colorArr
 
def judge(event):
    global num
    num+=1
    level.config(text='第'+str(num)+'关')
    inde=random.randint(0,101)
    colorBox=col()
    for i in sqareBox:
        i.config(bg=colorBox[0])
        sqareBox[inde].config(bg=colorBox[1])
        sqareBox[inde].bind('<Button-1>',judge)
 
sqareBox=[]
colorBox=col()
 
for i in range(10):
    for j in range(10):
        label=Label(win,width=3,height=1,bg=colorBox[0],relief='groove')
        sqareBox.append(label)
        label.grid(row=i,column=j)
 
sqareBox[inde].config(bg=colorBox[1])
sqareBox[inde].bind('<Button-1>',judge)
level=Label(win,text='第1关',font=14)
level.grid(row=11,column=0,columnspan=10,pady=10)
win.mainloop()