python - 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 循环期间更新。
解决方案
您绘制的(及时)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
推荐阅读
- javascript - ExtJS Modern - 向网格单元添加多个按钮
- javascript - 如何构建 tensorflow.js 模型来预测数字的平方?
- terraform - 如何解决创建服务时出错:googleapi:错误 403:服务帐户上的权限“iam.serviceaccounts.actAs”被拒绝
- rust - 使用 serde 反序列化带有 Enum 键的 HashMap
- angular - WINDOWS 上的 WebSerial API - “DOMException:无法打开串行端口。”
- python - 从字典中获取键的最有效方法
- node.js - 回滚后的 Mikroorm id 漏洞
- docker - 添加第二个 EF 核心数据库后 Blazor 服务器端 docker 容器分段错误
- asp.net-core - 在 asp.net core 中模拟用户
- javascript - 如何使用Angular8检测输入变化