我正在尝试创建一个在按 P 时暂停游戏的功能。我还希望它在游戏运行时显示在屏幕上。但是,我不知道如何继续我的功能。另外,是否可以在不使用import time
?
使用我的代码,在开始游戏之后, P 只会暂停其中一个块,而且它永远不会再移动。
def play():
onkey(None,"space")
clear()
hanoi(6, t1, t2, t3)
write("press STOP button to exit",
align="center", font=("Courier", 16, "bold"))
def pause():
onkey(None,"p")
clear()
hanoi(6, t1, t2 ,t3)
write("Press P to Pause",
align="center", font=("Courier", 16, "bold"))
if onkeypress("p"):
Pause = True
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
t1 = Tower(-250)
t2 = Tower(0)
t3 = Tower(250)
# make tower of 6 discs
for i in range(6,0,-1):
t1.push(Disc(i))
# prepare spartanic user interface ;-)
write("Aleksandar Stefanov's ToH. Press spacebar to start game",
align="center", font=("Courier", 16, "bold"))
onkey(play, "space")
onkey(pause, "p")
listen()
return "EVENTLOOP"
if __name__=="__main__":
msg = main()
print(msg)
mainloop()
答案 0 :(得分:0)
当您按 p
时,您应该跟踪游戏状态以切换它类似的东西:
def pause():
if (GameStatus == 'play'):
GameStatus = 'pause'
#GAME IS ON PAUSE
elif (GameStatus == 'pause'):
GameStatus = 'play'
#GAME IS ON PLAY
def main():
global GameStatus
GameStatus = 'play'
onkey(pause, "p")
如果您想暂停onpress
并暂停onrelease
,可以使用onkeypress
和onkeyrelease
来注册您的活动
类似的东西:
def pause():
if (GameStatus == 'play'):
GameStatus = 'pause'
#GAME IS ON PAUSE
def unpause():
if (GameStatus == 'pause'):
GameStatus = 'play'
#GAME IS ON PLAY
def main():
global GameStatus
GameStatus = 'play'
onkeypress(pause, "p")
onkeyrelease(unpause, "p")
答案 1 :(得分:0)
我刚刚解决了这个问题,在得到一些工作后,我将其简化为这个。它通过将内容包装在 if 语句中来暂停 while 循环。
#screen.tracer is set to 0
#variable for if statement
PAUSED = False
#function to change variable
def pause_game():
global PAUSED
if PAUSED:
PAUSED = False
elif not PAUSED:
PAUSED = True
#function tied to key press
screen.onkeypress(pause_game, "space")
#if statement I wrapped all content of while game_is_on loop
if not PAUSED:
#(perform all function of game)
elif PAUSED:
time.sleep(.01)
screen.update()
C/P 将此代码添加到我的蛇游戏中,效果相同。