当Python乌龟与食物碰撞时,为什么我的分数没有更新,我需要帮助。我还在下面发布了带有完整代码的链接:
if turtle.distance(food) < 20:
food.goto(randint(-280, 280), randint(-280, 280))
# Adding sections
new_section = Turtle()# Turtle() is the same as turtle.Turtle()
new_section.shape('square')
new_section.speed(0)
new_section.color('orange', 'grey')
new_section.penup()
new_section.goto(old_position)
sections.append(new_section)# Adds new section of body at the end of body
# Score
score = 0
high_score = 0
# Increase the score
score = + 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center",font=("Courier", 24, "normal"))
***Need help on updating score have also posted link below***
screen.update()
screen.ontimer(move, DELAY)
pastebin.com查看完整代码。
答案 0 :(得分:1)
score
和highscore
都是move()
的本地变量,每次运行时都重新设置为零。它们必须是全局的,并声明为global
。
如果我们从得分的角度来看move()
,则它看起来像:
def move():
score = 0
high_score = 0
# Increase the score
score = + 10
if score > high_score:
high_score = score
pen.write("Score: {} High Score: {}".format(score, high_score), ...))
score
和highscore
在move()
中是 local 的地方。我们真正期望的是:
score = 0
high_score = 0
def move():
global score, high_score
# Increase the score
score += 10
if score > high_score:
high_score = score
pen.write("Score: {} High Score: {}".format(score, high_score), ...))
阅读有关Python global
关键字和一般Python全局变量的信息。