我听说全球化变量不是一种非常习惯的做法,所以我尝试通过不全球化任何变量来最小化数量,并且只全球化错误消息告诉我的那些。但是这样做很烦人,而且浪费时间。
有人能告诉我什么时候应该在函数中全局变量的经验法则吗?什么时候不需要?
这是我的意思的示例(功能):import turtle
from random import randint as rd
from time import sleep
delay = 0.1
wn = turtle.Screen()
wn.setup(400,400)
wn.tracer(0)
player = turtle.Turtle('square')
player.penup()
player.goto(0,-170)
rock = turtle.Turtle('circle')
rock.shapesize(0.5,0.5)
rock.penup()
rock.goto(rd(-190,190),200)
rocks = [rock]
pen = turtle.Turtle(visible=False)
pen.penup()
pen.goto(0,150)
def go_left(): # No globalizing here
if player.xcor() >= -170:
player.setx(player.xcor()-10)
def go_right(): # No globalizing here
if player.xcor() <= 170:
player.setx(player.xcor()+10)
def move_rocks(): # No globalizing here
for rock in rocks:
rock.sety(rock.ycor()-rd(0,2))
def loop_rocks():
global count # rocks not globalized here
for rock in rocks:
if rock.ycor() < -200:
count += 1
rock.goto(rd(-190,190),200)
def add_rocks():
global count # rocks not globalized here
if count == len(rocks) and len(rocks) <= 15:
rock = turtle.Turtle('circle')
rock.shapesize(0.5,0.5)
rock.penup()
rock.goto(rd(-190,190),200)
rocks.append(rock)
count = 0
def write_score():
global time,score,high_score # pen not globalized here
time += 1
if time == 500:
score += 1
time = 0
if score > high_score:
high_score = score
pen.clear()
pen.write(f'Score: {score} High Score: {high_score}',align='center',font=('Arial',10,'bold'))
def hit(): # No globalizing here
for rock in rocks:
if player.distance(rock) < 15:
return True
def die():
global score,rocks # player not globalized here
sleep(1)
for rock in rocks:
rock.goto(300,300)
rocks = rocks[:1]
rocks[0].goto(rd(-190,190),200)
player.goto(0,-170)
score = 0
wn.listen()
wn.onkeypress(go_left,'Left')
wn.onkeypress(go_right,'Right')
score = 0
high_score = 0
count = 0
time = 0
while True:
if hit():
die()
move_rocks()
loop_rocks()
add_rocks()
write_score()
wn.update()