Почему счет не обновляется на моем табло? - PullRequest
0 голосов
/ 04 ноября 2019

Мне нужна помощь, почему мой счет не обновляется, когда черепаха 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 для полного кода.

1 Ответ

1 голос
/ 04 ноября 2019

И 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(). То, что мы действительно ожидаем, больше похоже на:

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 в целом.

...