我需要通过按空格键开始无限循环,然后再次按空格键结束循环
@win.event
def on_draw():
(some code of drawing)
@win.event
def on_key_press(symbol, modifiers):
global x,y,z,t
elif symbol == key.SPACE:
t += 0.05
x = ((1 - t) ** 3) * (-180) + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (0) + (t ** 3) * (200)
y = ((1 - t) ** 3) * 70 + 3 * t * ((1 - t) ** 2) * (140) + 3 * (t ** 2) * (1 - t) * (140) + (t ** 3) * (
70)
z = ((1 - t) ** 3) * 0 + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (100) + (t ** 3) * (
0)
(here should be a function of endless moving (drawing) while Space haven't pressed again)
答案 0 :(得分:1)
这不是正确的选择。您已经有了一个循环,即游戏循环。用它!
创建2个状态变量start_loop
和run_loop
:
start_loop = False
run_loop = False
如果按下 space ,则必须决定要做什么。
如果循环未运行(not run_loop
),请通过设置start_loop = True.
来启动循环
如果循环正在运行,请通过run_loop = False
停止循环。
def on_key_press(symbol, modifiers):
if symbol == key.SPACE:
if not run_loop:
start_loop = True
else:
run_loop = False
在主循环中,您必须区分3种情况。
start_loop
是True
。进行初始化并设置状态以在下一帧(start_loop = False
,run_loop = True
)中运行循环run_loop
是True
。在循环中执行代码def on_draw():
global x,y,z,t
if start_loop:
start_loop = False
run_loop = True
t += 0.05
x = ((1 - t) ** 3) * (-180) + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (0) + (t ** 3) * (200)
y = ((1 - t) ** 3) * 70 + 3 * t * ((1 - t) ** 2) * (140) + 3 * (t ** 2) * (1 - t) * (140) + (t ** 3) * (70)
z = ((1 - t) ** 3) * 0 + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (100) + (t ** 3) * (0)
elif run_loop:
# this is the loop
# [...] (here should be a function of endless moving (drawing) while Space haven't pressed again)
pass
else:
# this is default
# [...] (some code of drawing)
当然,您必须通过[schedule_interval
添加一个计划功能,该功能以指定的间隔运行循环。
def run_loop(dt):
on_draw()
pyglet.clock.schedule_interval(run_loop, 0.1) # run every tenth of a second
pyglet.app.run()