提问人:emsiloader 提问时间:5/19/2023 更新时间:5/19/2023 访问量:56
如何在 Python 中中断 while 循环但不退出
how to break while loop but not exit in python
问:
以下是我的简单游戏的代码。当游戏在定义的条件下结束时,如果为 true,我想中断 while 循环,但不终止(退出)游戏。
import cv2
import datetime
#importing other files
#defitinions
# functions
def myfunction1():
try:
...
except:
...
while True: #I also put a gameflag to check ( while gameflag: ...)
#game codes here
if (conditions) :
gameOver = True
if gameOver:
#game is over codes here
#I put a gameflag here to set False to be checked in while loop above
else:
...
key = cv2.waitKey(1) #I put waiting key line both inside and outside of the while loop. But app skips this line and terminates.
if key == ord('r'): #I moved this Line out of the While loop but it doesn't
imgGameOver = cv2.imread("images/gameover.png")
gameflag = True
我计算球的位置并在 while 循环期间检查条件。正如您在代码中看到的,如果游戏结束,如果玩家想要重新启动游戏,我想保持窗口显示并等待密钥。 但是当我输入“break;”时,应用程序终止并退出。 当我放置一个布尔标志时,它不会在破坏 While 循环后进行检查。
我想停止 While 循环,直到玩家输入一个键来重新启动游戏(再次回到 While 循环,我的游戏代码所在) 我想要这个,因为某些服务在 while 循环中继续工作,例如文件附加文本、调用 Web 服务等。
谢谢
答:
0赞
Darkshadogt
5/19/2023
#1
您可以尝试添加嵌套的 while 循环。外部的 while 循环将表示正在运行的程序,而内部的 while 循环可以表示游戏正在运行。如果游戏完成,那么内部的 while 循环将中断,如果重新启动,它将再次循环。
评论
break
return
continue