python怎么退出游戏_python

在设计游戏时,与传统的“后端” Python编码相比,我们发现需要这种模式:从内部函数到“跳转”再到外部函数。

因此,在游戏中,通常会发生以下情况:从mainloop调用的函数中,您会希望退出mainloop并转到代码设置下一个游戏阶段或显示游戏结束画面的地方,并且提供开始新游戏的机会。

Python具有“ sys.exit”调用,该调用将完全停止程序,因此,尽管您可以从检查游戏结束条件的代码中调用它,但它会完全退出您的程序,而不会为用户提供选择开始新的比赛。 (如果您的游戏是在图形UI上,而不是在控制台的“打印和输入”游戏上,那么本来就很糟糕的体验会变成灾难性的,因为游戏本身会突然关闭而没有任何痕迹)。

因此,尽管可以使用可由这些函数设置的“状态变量”进行管理,并由mainloop(在您的情况下为mainGame函数中的while语句)进行管理,但这种设计既乏味又容易出错-会是这样的:

def mainGame(...):

...

game_over = False

while not game_over:

if search_area not in search_area_options:

game_over = True

...

if search_area == "4":

game_over = True

因此,请注意,使用此设计,如果将“ game_over”标志更改为True,则无论在何处,在下一次迭代中,“ while”条件都会失败,并且程序自然会结束mainGame函数的执行-和是否没有外部功能处理“再次播放”? 屏幕上,程序结束。

没关系,也许对于像这样的简单游戏来说,正确的做法是。

但是在更复杂的设计中,您在主循环中的选择会变得更加复杂-您可以调用可以自行实现迷你游戏的函数,否则检查可能并不容易-而且,最重要的是,而不是退出该主要功能的“结束游戏”条件,例如,将导致游戏进入下一阶段的“获胜”条件。

在这些情况下,您可能不想使用Python的Exception机制来将游戏状态记录在变量中。 异常是一种在程序错误时自然发生的语言构造,它使程序可以停止或继续在发生异常的地方“上方”的函数中运行-如果程序员仅包括正确的“ try” -except”子句以捕获异常。

因此,可以发生一个复杂的游戏,该游戏可以处理任意comples游戏,并且仍然可以通过创建命名良好的异常并适当放置try-except子句,很容易始终知道执行将导致的结果-使用此策略的更复杂的游戏可能伴随着一些事情:

# start

class BaseGameException(BaseException): pass

class ProgramExit(BaseGameException): pass

class GameOver(BaseGameException): pass

class MiniGameOver(BaseGameException): pass

class NextStage(BaseGameException): pass

def minigame():

while True:

# code for game-within-game mini game

...

if some_condition_for_winning_main_game_stage:

raise NextStage

...

def main_game(stage):

# get data, scenarios, and variables as appropriate for the current stage

while True:

...

if some_condition_for_minigame:

minigame()

...

if condition_for_death:

raise GameOver

...

def query_play_again():

# print and get messag reponse on whether to play again

...

if player_decided_to_quit:

# This takes execution to outsude the "main_game_menu" function;

raise ProgramExit

def main_game_menu():

"""Handle game start/play again/leatherboard screens"""

stage = 1

while True:

# print welcome message, and prompt for game start

try:

main_game(stage)

except NextStage:

# print congratulations message, and prepare for next stage

stage += 1

except GameOver:

# player died - print proper messages, leatherboard

query_play_again()

stage = 1

# if the program returns here, just let the "while" restart the game

if __name__ == "__main__":

try:

main_game_menu()

except ProgramExit:

print("Goodbye!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值