【问题标题】:Incrementing a score system in Python在 Python 中增加分数系统
【发布时间】:2021-04-04 13:26:18
【问题描述】:

:D 我用 Python 制作了一个小石头剪刀布游戏,只是为了好玩和练习,我一直在尝试实现一个小评分系统,它似乎不想正常工作,我不确定如何解决问题。

import random
import messages

def gameOn():
  choice = ["rock", "paper", "scissors"]

  computer_choice = random.choice(choice)
  player_choice = input("Please chose Rock/Paper/Scissors: ")
  player_choice = player_choice.lower()
  total_score = 0

  while True:

    #Makes sure the user enters a valid option.
    if player_choice not in("rock", "paper", "scissors"):
      print("Choice is not correct!")

    #Prints in case both the computer and the player chose the same option.
    elif computer_choice == player_choice:
      print("You chose the same.")
    
    #Computer choses ROCK.
    elif computer_choice == "rock" and player_choice == "paper":
      print(messages.win[0])
      total_score += 1
      print(total_score)
    elif computer_choice == "rock" and player_choice == "scissors":
      print(messages.lose[0])

    #Computer choses PAPER.
    elif computer_choice == "paper" and player_choice == "rock":
      print(messages.lose[1])
    elif computer_choice == "paper" and player_choice == "scissors":
      print(messages.win[1])
      total_score += 1
      print(total_score)

    #Computer choses SCISSORS.
    elif computer_choice == "scissors" and player_choice == "rock":
      print(messages.win[2])
      total_score += 1
      print(total_score)
    elif computer_choice == "scissors" and player_choice == "paper":
      print(messages.lose[2])
      
    #Asks the user if he/she wants to play again and restarts the loop if so.
    answer = input("Would you like to play again or see your score? Yes/No/Score ")
    if answer in ("yes", "Yes", "y", "Y", "yup"):
      print("Game starting again!")
      gameOn()
    elif answer in ("Score", "score"):
      print("Your total score is " + str(total_score)) 
      answer = input("Would you like to play again or see your score? Yes/No/Score ")
      print("Game starting again!")
      gameOn()
    else:
      print("Goodbye!")
    break

gameOn()

增量本身有效,但我想做的是,如果玩家赢得多轮比赛并在最后写下“分数”,他应该能够看到他获得的所有分数。目前,每次新游戏开始时,得分变量都会重置,因此如果他赢得了回合,则使用的得分始终为 0 或 1。我怎样才能防止这种行为? 非常感谢:D,我希望这不是一个太愚蠢的问题。

【问题讨论】:

  • 请记住,存在递归限制,因此您只能在程序崩溃之前玩 1000 次左右的游戏,因为有很多嵌套函数调用。
  • 我对此一无所知 :D 谢谢你告诉我。

标签: python python-3.x increment


【解决方案1】:

我不建议为此使用递归。您也不应该需要使用全局变量。

我宁愿在你的 gameOn 函数中循环使用 while True 并在玩家想要退出时中断,这样你的分数就会保持在范围内。

还有你的“选择不正确!”由于缩进而无法正常工作。

import random
import messages

def gameOn():
        choice = ["rock", "paper", "scissors"]
        total_score = 0

    while True:    
        computer_choice = random.choice(choice)
        player_choice = input("Please chose Rock/Paper/Scissors: ")
        player_choice = player_choice.lower()

        while True:
            #Makes sure the user enters a valid option.
            if player_choice in("rock", "paper", "scissors"):
                break
            print("Choice is not correct!")

        #Prints in case both the computer and the player chose the same option.
        elif computer_choice == player_choice:
            print("You chose the same.")
    
        #Computer choses ROCK.
        elif<computer_choice == "rock" and player_choice == "paper":
            print(messages.win[0])
            total_score += 1
            print(total_score)
        elif computer_choice == "rock" and player_choice == "scissors":
            print(messages.lose[0])

        #Computer choses PAPER.
        elif computer_choice == "paper" and player_choice == "rock":
            print(messages.lose[1])
        elif computer_choice == "paper" and player_choice == "scissors":
            print(messages.win[1])
            total_score += 1
            print(total_score)

        #Computer choses SCISSORS.
        elif computer_choice == "scissors" and player_choice == "rock":
            print(messages.win[2])
            total_score += 1
            print(total_score)
        elif computer_choice == "scissors" and player_choice == "paper":
        print(messages.lose[2])
  
        #Asks the user if he/she wants to play again and restarts the loop if so.
        answer = input("Would you like to play again or see your score? Yes/No/Score ")

        if answer in ("Score", "score"):
            print("Your total score is " + str(total_score)) 
            answer = input("Would you like to play again or see your score? Yes/No/Score ")
            print("Game starting again!")
        elif answer in ("yes", "Yes", "y", "Y", "yup"):
            print("Game starting again!")
        else:
            print("Goodbye!")
            break #this makes your game stop

gameOn()

【讨论】:

    【解决方案2】:

    我建议为你的 gameOn 函数定义一个参数,所以它看起来像这样:

    def gameOn(total_score=0):
      # REMOVE this following line:
      total_score = 0
      # because we already defined it on parameter
    
      # when user wins, and you call the function again,
      # give current total_score to it
      gameOn(total_score)
    

    由于在每个函数调用中您都给出了当前分数,现在您的应用应该能够跟踪实际总分

    【讨论】:

    • 这感觉像是一个比使用全局变量更好的选择,尽管如果你想更进一步,创建一个类可能会更好......
    • 最大递归限制仍有问题。因此,使用 while 循环留在该函数范围内会更好。
    【解决方案3】:

    根据“每次新游戏开始”的含义,有 2 种不同的方法来回答这个问题。

    如果多次调用gameOn 函数,是否要保留分数?
    或者如果您再次运行程序,您是否也想保留分数?

    gameOn 调用之间保持分数

    问题是您的 total_score 变量的范围,它是本地的。因此,在每次执行 gameOn 后都会对其进行清理。解决此问题的最简单方法是将其设置为全局:

    import random
    import messages
    
    # Total score is initialized outside of any game
    total_score = 0
    
    def gameOn():
      choice = ["rock", "paper", "scissors"]
    
      computer_choice = random.choice(choice)
      player_choice = input("Please chose Rock/Paper/Scissors: ")
      player_choice = player_choice.lower()
      global total_score
      # Then the rest of your existing function
      # ...
    

    建议:随着时间的推移,您会在 Python 中变得更好,并且您会意识到这种全局变量通常被认为是不好的,因为它缺乏隔离性。对于较大的项目,依赖全局定义的东西会使代码更难发展,增加开发人员的认知负担,更难测试……但对于这么小的脚本来说,这完全没问题。 我的观点是:它很方便,但请记住还有其他方法可以做到这一点。在这种情况下,它们更复杂,并且设计过度,但关键不应该被认为是“只要我想保持一个状态,就需要使用全局变量”;)

    在运行之间保持分数。

    如果您的目标是在每次运行脚本之间保持分数,那么您需要将其保存在当前 Python 会话内存的“外部”。
    一种非常简单的方法是将其保存到文件中。 Python 的内置 pickle 库就是为此而设计的(还有许多其他选项,取决于您是否希望它可以被其他程序或人类使用。当它仅用于 Python 时,pickle 超级简单和快速可靠)

    在这种情况下,您需要:

    • 游戏开始时加载现有分数,如果现有分数存在
    • 在游戏结束时保存
    import random
    import messages
    import pickle
    import os
    
    
    def gameOn():
      choice = ["rock", "paper", "scissors"]
    
      computer_choice = random.choice(choice)
      player_choice = input("Please chose Rock/Paper/Scissors: ")
      player_choice = player_choice.lower()
     
      score_file = "score.dat"
      # Check if an existing score existed
      if os.path.isfile(score_file):
          with open(score_file, "rb") as f:
            total_score = pickle.load(f)
      else:
          total_score = 0
    
      # Then the rest of your existing function
      # ...
      # and at the end of the function, we save the score to the file
      with open(score_file, "wb") as f:
          pickle.dump(total_score, f)
    

    这应该可以为您指明您真正想要实现的目标。

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2016-01-05
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多