Python在循环结束后仍保持得分

2024-04-26 04:40:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我的代码有一个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 $0 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()

Tags: thetoyoumainhaverandomcardprint
3条回答

正如khelwood在评论中指出的,在这种情况下,实际循环比重复循环要好。如果在main内部调用main,则在不需要的情况下,会越来越深入地进行嵌套函数调用。通过while循环,您可以继续执行某些操作,直到某个条件不再为真。一个函数既可以接受参数,也可以返回一个值,这样每次游戏都可以从不同的平衡点开始

我做了一些其他的调整。我用链式<比较重写了你的赢/输支票,并将它们分成两行以便于阅读。在括号内,可以添加换行符,而不会影响代码执行。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 $0 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 $0 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()

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

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

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

相关问题 更多 >