import turtle
ben = turtle.Turtle()
W = 1
ben.speed(10.5)
ben.width(5)
#X = 0
O = 0
if GRIDDONE == True: #inside lines
ben.speed(10.5)
ben.forward(100)
ben.right(90)
ben.forward(300)
ben.left(90)
ben.forward(100)
ben.left(90)
ben.forward(300)
ben.right(90)
ben.forward(100)
ben.right(90)
ben.forward(100)
ben.right(90)
ben.forward(300)
ben.left(90)
ben.forward(100)
ben.left(90)
ben.forward(300)
ben.pu()
ben.forward(500)
X = turtle.Turtle()
O = turtle.Turtle()
X.pu()
O.pu()
X.forward(300)
X.right(90)
O.forward(300)
O.right(90)
X.color("Blue")
X.color()
O.color("Red")
O.color()
X.width(2)
O.width(2)
#X.speed(100)
#O.speed(100)
SQ1 = False
StartX = '300'
StaryY = '0'
def playX():
P1 = input('Can player X please choose their square')
if (P1) == ('1'):
if (SQ1) == False:
X.right(90)
X.forward(300) #change this
X.left(90)
X.left(45)
X.pd()
X.forward(140)
X.pu()
X.left(135)
X.forward(100)
X.left(135)
X.pd()
X.forward(140)
X.pu()
X.setx(300)
X.sety(0)
X.left(45)
SQ1 = True
def playO():
P1 = input('Can player O please choose their square')
if P1 == ('1'):
if SQ1 == False:
O.right(90)
O.forward(300) #change this
O.left(90)
O.forward(50)
O.left(90)
O.forward(10)
O.left(90)
O.pd()
O.circle(-40)
O.pu()
O.setx(300)
O.sety(0)
O.left(180)
SQ1 = True
playO()
#playX()
这是我的代码,我需要创建一个不允许乌龟在相同的情况下绘制的功能,如果'功能两次,但我得到标题中的错误。错误如下:
追踪(最近一次通话): 文件" C:\ Users \ benna \ Downloads \ 2.py",第314行,in playO() 文件" C:\ Users \ benna \ Downloads \ 2.py",第297行,在playO中 如果SQ1 == False: UnboundLocalError:局部变量' SQ1'在分配前引用
我认为这是因为在函数中使用变量时无法对其进行编辑。
答案 0 :(得分:0)
错误是由于SQ1
在全局空间中声明,然后在play0()
函数内被访问。
您可以使用关键字global
来修复此错误。在play0()
函数中添加一行,指定SQ1
是全局的,如下所示(参见第2行):
def playO():
global SQ1
P1 = input('Can player O please choose their square')
if P1 == ('1'):
if SQ1 == False:
进一步改进:
我建议您关注变量名Python Style Guide并提高代码的可读性。