为什么我的记分牌上的分数没有更新?

Why isn't the score updating on my scoreboard?

我需要帮助,了解为什么当 Python 乌龟与食物碰撞时我的分数没有更新。我还在下面发布了一个包含完整代码的 link:

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 完整代码。

scorehighscore 都是 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), ...))

其中 scorehighscorelocalmove()。我们真正期望的更像是:

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 全局变量的一般信息。