Python 即使在循环后仍保持得分

Python keep score even after loop

我有一个问题。我的代码有一个 def main():,我想即使在用户输入重启后也能保持分数。问题是循环后分数又变成了100。我该如何解决这个问题?

import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a [=11=] bet.")
print()
def main():
  bankbalance = 100
  print("These cards are open on the table:")
  print()
  print("First card:")
  firstcard = random.randint(1,13)  
  print(firstcard)
  print("Second card:")
  secondcard = random.randint(1,13)
  print(secondcard)
  playerinput = input("Enter your bet: ") 
  playerinput = int(playerinput)  
  dealercard = random.randint(1,13)
  dealercard = int(dealercard)
  print("The card you drew was", (dealercard), "!")
  if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
    print("You win!")
    bankbalance = bankbalance + playerinput
    print("You currently have $", (bankbalance))
    playagain = input("Would you like to play again yes/no: ")
    if playagain == ("yes"):
      main()
    else:
      exit
  else:
    print("You lost!")
    bankbalance = bankbalance - playerinput
    print("You currently have $", (bankbalance))
    playagain = input("Would you like to play again yes/no: ")
    if playagain == ("yes"):
      main()
    else:
      exit
main()

将分数定义为 main 之外的全局变量:

bankbalance = 100
def main():
  global bankbalance
  print("These cards are open on the table:")
  # .... 

编辑:我知道有更好的方法来实现 OP 的要求。不过,我的目标是帮助他改进自己的代码,首先向他解释代码的问题所在,以帮助 OP 从他的错误中吸取教训。

正如 khelwood 在评论中指出的那样,在这种情况下实际循环比重复出现更好。如果您在 main 内部调用 main,您将在不需要时越来越深入嵌套函数调用。 while 循环让您可以继续做某事,直到条件不再为真。一个函数可以接受参数和 return 一个值,这让游戏每次都从不同的平衡开始。

我还进行了其他一些调整。我用链式 < 比较重写了您的 win/loss 检查,并将它们分成两行以便于阅读。在括号内,您可以添加换行符而不影响代码执行。 Python 也会自动组合以这种方式分解的字符串,因此我为介绍文本所做的。我还更改了一些变量打印以使用 f-strings.

import random

def main():
    print("Welcome to Python Acey Ducey Card Game")
    print()
    print("Acey-ducey is played in the following manner: the dealer "
          "(computer) deals two cards faced up and you have an option "
          "to bet or not bet depending on whether or not you feel the "
          "card will have a value between the first two. If you do not "
          "want to bet, enter a [=10=] bet.")
    
    bankbalance = 100
    playagain = "yes"
    
    while playagain == "yes":
        bankbalance = play(bankbalance)
        playagain = input("Would you like to play again yes/no: ")
    
    print(f"You leave with ${bankbalance}")


def play(bankbalance):
    print()
    print(f"You currently have ${bankbalance}")
    print("These cards are open on the table:")
    print()
    print("First card:")
    firstcard = random.randint(1,13)    
    print(firstcard)
    print("Second card:")
    secondcard = random.randint(1,13)
    print(secondcard)
    playerinput = input("Enter your bet: ") 
    playerinput = int(playerinput)    
    dealercard = random.randint(1,13)
    print(f"The card you drew was {dealercard}!")
    if (firstcard < dealercard < secondcard or
        secondcard < dealercard < firstcard
    ):
        print("You win!")
        return bankbalance + playerinput
    else:
        print("You lost!")
        return bankbalance - playerinput

 
if __name__ == '__main__':
    main()

另外,请注意,您的代码目前允许您下注超过您的下注,并在您出现负数时继续下注。如果这不是故意的,请考虑如何避免这种情况。

我刚刚完成了与上述类似的解决方案。玩2轮或更多轮后,递归调用会很明显。

import random

def welcome():
    print("Welcome to Python Acey Ducey Card Game\n")
    print("Acey-ducey is played in the following manner: ")
    print("\tthe dealer (computer) deals two cards faced up")
    print("\tyou have an option to bet or not bet depending on")
    print("\twhether or not you feel the card will have a value")
    print("\tbetween the first two.")
    print("\tIf you do not want to bet, enter a [=10=] bet.\n")


def get_bet(balance):
    while True:
        bet = input("Enter your bet: ")
        try:
            bet = int(bet)
            if bet <= balance and bet >= 0:
                return bet
            elif bet < 0:
                print("You can't bet negative amounts!")
            else:
                print("You don't have enough cash to bet that!")
        except:
            print("You must enter a number bet!")
        
    

def game_round(bankbalance):
    print("\nThese cards are open on the table:")
    firstcard = random.randint(1,13)
    print("\nFirst card:", firstcard)
    secondcard = random.randint(1,13)
    print("Second card:", secondcard)
    playerinput = get_bet(bankbalance) 
    dealercard = random.randint(1,13)
    dealercard = int(dealercard)
    print("The card you drew was", (dealercard), "!")
    if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
        print("You win!")
        return playerinput
    else:
        print("You lost")
        return -playerinput


def main():
    welcome()
    bankbalance = 100
    print("You currently have $", (bankbalance))
    while True:
        playagain = input("Enter [Y] to play a game, any other key to exit: ")
        if playagain.lower() == ("y"):
            bankbalance = game_round(bankbalance)
            print("\nYou currently have $", (bankbalance))
        else:
            break
    print("Thanks for playing- Goodbye!")

main()