exit()与Python中的while循环冲突

46qrfjad  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(126)

我正在编写一个(简单的)21点游戏,我使用下面的代码为用户提供重新玩的选项,直到他们决定不再玩为止。

while True:
  game()
  if "n" in input("Do you want to play again? Y or N").lower():
    break

问题是我在game()的嵌套函数中有几个exit(),它们被设计为过早地停止游戏(例如,从一开始就自然的21点,或者突然停止),但是我发现exit()终止了整个脚本,并且完全跳过了上面的代码。
我不能在game()中的嵌套函数中使用return或break,因为我发现return/break只会退出嵌套函数,但game()仍然会继续,即使我希望game()停止。

def game():

  def first_check():
    player_sum = sum(player)
    dealer_sum = sum(dealer)
    if 21 in [player_sum,dealer_sum]:
      if 21 in [player_sum] and 21 in [dealer_sum]:
        print("Both you and the dealer have Blackjack, its a push!!")
      blackjack()
      exit()

如果我在上面的first_* check()中使用break而不是exit(),它会退出first *_check(),但是即使我想让它停止,game()仍然会运行。
是否有函数或语句退出它所在的支配性函数,而不杀死整个脚本?
谢谢大家!
尝试了返回和休息,但他们没有达到我想要的。
我试着把嵌套函数放在game()之外,但是当我想让game()停止时,它仍然运行。

vtwuwzda

vtwuwzda1#

您可以定义一个可以抛出的自定义异常,然后将对game的调用 Package 在try-catch中,并在其后提示检查用户是否愿意再次播放。
定义例外:

class StopGameIteration(Exception):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

重写game()函数以使用异常:

def game():

  def first_check():
    player_sum = sum(player)
    dealer_sum = sum(dealer)
    if 21 in [player_sum,dealer_sum]:
      if 21 in [player_sum] and 21 in [dealer_sum]:
        print("Both you and the dealer have Blackjack, its a push!!")
      blackjack()
      raise StopGameIteration("Had blackjack")

并将调用封装在try catch中:

while True:
  try: 
    game()
  except StopGameIteration:
    pass

  if "n" in input("Do you want to play again? Y or N").lower():
    break

您甚至可以创建几个异常,以便根据中断函数的原因调整行为:

class GameException(Exception):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class BlackjackAchieved(GameException):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class PlayerCheated(GameException):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

然后做出相应的React:

while True:
  try: 
    game()
  except BlackjackAchieved:
    print("Someone got a blackjack")
  except PlayerCheated:
    print("oh no, someone cheated")
  except GameException:
    print("Something related to the game happened to cause it to quit")

  if "n" in input("Do you want to play again? Y or N").lower():
    break

编辑:@pranav-hosangadi说得很对:try-catch应该在game函数内部,这样游戏的逻辑就完全独立了,然后,在try-catch块的finally子句中,可以选择使用return返回到外部循环。

相关问题