tic tac toe问题。
a=0
def runx():
answer = int(input("answer:"))
if answer == 1:
if a==1 or a==2:
print("nope")
if a==0:
mlabel=Label(mGui,text="x").grid(row=1,column=1)
a=1
所以runx正在检查你想要放置x的板子在哪里。答案是您想要的变量。 “a”是看它是否被占用以及它占据了什么。 0 =无,1 = X 2 = O。当我跑这个时它说:
“(a)转让前的参考”。
答案 0 :(得分:2)
您正在尝试写入全局变量。那么,你应该在函数中放置global a
这个词。像这样:
a=0
def runx():
global a
answer = int(input("answer:"))
if answer == 1:
if a==1 or a==2:
print("nope")
if a==0:
mlabel=Label(mGui,text="x").grid(row=1,column=1)
a=1
我想提一下,只要您不声明局部变量a,就可以随时从函数中读取它,但除非您放置global
关键字,否则无法写入。
答案 1 :(得分:1)
对于小型电路板,将状态保持在dict
a = {}
def runx():
answer = int(input("answer:"))
row, column = divmod(answer, 3)
if (row, column) in a:
print("nope")
else:
mlabel=Label(mGui, text="x").grid(row=row, column=column)
a[row, column] = 1
因为dict
是可变的,所以在函数
以下是如何使用divmod将0-8中的数字映射到行/列
>>> for answer in range(0, 9):
... print divmod(answer, 3)
...
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
答案 2 :(得分:0)
你在函数外面定义a
,所以要么在函数内部使用global a
告诉Python它是一个全局变量,要么在函数内移动声明。