在 Python 中增加分数系统

Incrementing a score system in Python

: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()

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

我建议为您的 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)

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

根据«每次新游戏开始»的含义,有两种不同的回答方式。

多次调用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)

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

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

我宁愿在你的 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()