Reputation: 27
tic tac toe problem.
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
so runx is checking to see where on the board you want to place the x. answer is the variable for where you want it. "a" is to see whether it is occupied and what its occupied with. 0=nothing,1=X,2=O. when i run this it says:
"(a) reference before assignment".
Upvotes: 0
Views: 102
Reputation: 304463
For small boards it's handy to keep the state in a 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
Because a dict
is mutable there's no problem updating it inside a function
Here is how divmod can be used to map a number from 0-8 onto a row/column
>>> 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)
Upvotes: 1
Reputation:
You're defining a
outside the function, so either use global a
inside the function to tell Python it's a global variable, or move the declaration inside the function.
Upvotes: 0
Reputation: 1475
You are trying to write to a global variable. then, you should place the word global a
in the function. like this:
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
I want to mention that as long as you not declare the local variable a, you can always read it from the function, but cannot write unless you put the global
keyword.
Upvotes: 2