问题描述
我一直很难解决这个问题。我想做的是使while循环不断运行,除非我发出“停止”命令。
我正在用更大的游戏制作一个钓鱼迷你游戏,我希望能够根据命令开始钓鱼(我已经能够做到),并且希望钓鱼继续发生,直到最终输入“停止”。
我做事的方式是先要求输入命令,然后根据命令进行操作。但是,在这种情况下,我不想这样做,因为要求输入会暂停while循环。
我愿意接受有关如何使用特定命令退出while循环的其他建议,但是游戏是基于文本的,因此理想情况下,我希望退出文本命令。
if command == 'fish':
print('You start fishing')
while True:
# fishing happens,you may or may not catch something
# if you enter a command ('exit'),you stop fishing
# I dont,however,want the code to pause to ask for a command.
# I want it to be uninterrupted fishing,until I choose to exit
解决方法
您需要2个loops
和flags
,当用户pauses
的{{1}}成为pauseFlag
且您的代码将从{{1} },当他True
进入inner loop
时,unpause
切换到pauseFlag
,游戏将重新开始。
类似以下内容:
False
也许您想知道:inner loop
是什么?如您所见,这是第一个循环的条件。每当while(quitFlag):
while(!pauseFlag):
#your code
if(somthing):
pauseFlag = True
if(somthing):
pauseFlag = False # and it make the code goes to the second loop again and resume the game
切换到quitFlag
时,游戏就会关闭,并且用户无法继续游戏,必须重新开始游戏。