首页 > 解决方案 > Python onkey 不停止循环

问题描述

def startgame():
    start.state = False
    print start.state


def restart():
    end.state = False
    start.state = True
    print game.state, end.state


s.listen()

s.onkey(startgame, "Return")

s.onkey(restart, 'r')

# This Loop stops when you hit Enter

while start.state:
    start.enter()
s.reset()

# I tried repeating it here but it doesn't work
while end.state:
    end.enter()
s.reset()
game.state = 'playing'

两个循环都嵌套在一个主while循环中,但第二个循环嵌套在另一个while循环中(如果有帮助的话)所以它看起来像这样

while True:
    while start.state:
        start.flash()
    s.reset()
    while True:

        # main game code here

        while end.state:
            end.flash()
        s.reset()
        game.state = 'playing'
        break

我只是希望它显示结束屏幕并让“按 r 再次播放”在屏幕上闪烁,直到玩家点击 r,然后它应该重新启动游戏并返回开始屏幕。该end.state变量不会在 while 循环期间更新,但start.state会在其 while 循环期间更新。

标签: pythonwhile-loopnestedturtle-graphics

解决方案


您绘制的(及时)while循环在乌龟之类的事件驱动环境中没有位置。一般来说,我们需要用事件来控制一切,特别是定时器事件。让我们将您的代码重写为状态机。(因为我没有你的对象类,所以像我的示例代码中的实体会start.state变成全局变量。)start_state

from turtle import Screen, Turtle

start_state = True
end_state = False

def start_game():
    global start_state

    start_state = False

def end_game():
    global end_state

    if not start_state:
        end_state = True

def restart_game():
    global end_state, start_state

    end_state = False
    start_state = True

def flash(text):
    turtle.clear()
    turtle.write(text, align="center", font=('Arial', 24, 'bold'))

    color = turtle.pencolor()
    turtle.pencolor(turtle.fillcolor())
    turtle.fillcolor(color)

def game_states():

    if start_state:
        flash("Start")
    elif end_state:
        flash("End")
    else:
        flash("Playing")

    screen.ontimer(game_states, 500)

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.fillcolor(screen.bgcolor())

screen.onkey(start_game, 'Return')
screen.onkey(restart_game, 'r')
screen.onkey(end_game, 'e')
screen.listen()

game_states()

screen.mainloop()

状态机规则是:

Start via <Return> -> Playing
Playing via <e> -> End and via <r> -> Start
End via <r> -> Start

推荐阅读