簡體   English   中英

exit() 與 Python 中的 while 循環沖突

[英]exit() is conflicting with a while loop in Python

我正在編寫一個(簡單的)二十一點游戲,我正在使用以下代碼讓用戶可以選擇再次玩游戲,直到他們決定不再玩為止。

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

問題是我在 game() 的嵌套函數中有幾個 exit() 旨在過早停止游戲(即從一開始就自然二十一點,或半身像)。 但是我發現 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() 仍然運行,即使我希望它停止。

是否有任何 function 或語句退出它所在的總體 function,而不殺死整個腳本?

謝謝!

試過返回和中斷,但他們沒有達到我想要的。

我嘗試將嵌套函數放在 game() 之外,但是當我想讓它停止時 game() 仍然運行。

您可以定義一個可以拋出的自定義異常,然后將您對game的調用包裝在 try-catch 中,然后提示檢查他們是否想再次玩游戲。

定義你的例外:

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

重寫你的game() function 以使用你的異常:

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

您甚至可以創建多個例外,以便您可以根據中斷 function 的原因調整行為:

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)

然后做出相應的回應:

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 function 中,這樣游戲的邏輯就完全獨立了。 然后,在 try-catch 塊的finally子句中,您可以選擇使用 return 來中斷回到外部循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM