尝试在 T 或 F 游戏中使用全局变量

Trying to use global variables in a T or F game

我不知道如何解决这个错误,以便我可以为每场获胜的比赛加分并带走回合。

你选择你想玩多少轮,当你玩每一轮时,1 会从 'round' 变量中减去,直到你有 0,这将不再让你玩并直接带你到评分函数。

积分是为了跟踪 you/the 机器人赢了哪些游戏,以便查看最后谁赢了(在所有回合完成后)

我收到以下错误:

Traceback (most recent call last):
  File "python", line 99, in <module>
  File "python", line 13, in login
  File "python", line 30, in start
  File "python", line 33, in rcheck
UnboundLocalError: local variable 'round' referenced before assignment

这是我的代码:

from time import sleep
import random

print("Rock, Paper, Scissors. By Leona Bryant")
print("")

def login():
  username=input("Username: ")
  password=input("Password: ")
  if (username == "shinleona" ) and (password == "hacker101"):
    print ("")
    print ("Welcome back Leona!")
    start()
  else:
    print("")
    print ("Invalid credidentals, try again.")
    login()


def start():
  print("")
  round=int(input("How many rounds would you like to play? Please pick from 3-10"))
  if (round <3 ):
    print("Invalid number, try again.")
    start()
  else:
    print("")
    print("Loading..")
    sleep(3)
    rcheck()

def rcheck():
  if (round <=0 ):
    print("End of game!")
    print("Calculating scores...")
    score()
  else:
    round-=1
    game()


def game():
  print("")
  rps=("rock" , "paper" , "scissors")
  bot = random.choice(rps)
  user=input("Rock..Paper..Scissors..SHOOT!").lower()
  print("The bot chose" , bot )

  if (bot == user):
    print ("This round was a draw, you both gain 1 point!")
    point+=1 
    bpoint+=1
    rcheck()

  elif ( (bot == "paper") and (user == "rock") ) or ( (bot == "scissors") and (user == "paper") ) or ( (bot == "rock") and (user == "scissors") ):
    print ("You Lose this round, Bot gains 1 point!")
    bpoint+=1 
    rcheck()

  else:
    print("You won this round, User gains 1 point!")
    point+=1
    rcheck()




def score():
  if (point > bpoint):
    print("Congratulations, you won the game with" , point , "points")
    again()

  else:
    print("Sorry, you lost the game. The bot won with" , bpoint , "points")
    again()


def again():
  play=input("Play again?").lower
  if (play[0] == "y"):
    start()

  elif (play[0] == "n"):
    print("Thanks for playing!")
    exit()

  else:
    print ("Invalid answer, try again.")
    again()

round = 0 
point = 0 
bpoint = 0 

global round
global bpoint
global point 

login()

global 在函数中使用,表示它正在修改的值来自外部(模块)作用域。它在模块级代码中没有用。你应该删除行

global round
global bpoint
global point

在 MATLAB 中,他们将使名称全局可用。在 Python 中,它们什么都不做,因为变量已经在模块范围内定义。

将行 global round 添加到 rcheck(以及使用全局变量的函数的相应行)。这告诉 python 函数中的名称 round 实际上是一个全局变量,即定义在模块中。如果没有 global 语句,该函数将尝试执行 round = round + 1,但右侧的 round 未在函数范围内定义。

当然,如果可以避免,请不要使用全局变量。编写一个具有所有必要状态和功能的 class,或者至少将值传递给您的函数并通过 return 值接受更新。

您没有将全局变量引入方法中,将以下内容添加到 rcheck() 方法的顶部:

global round

这应该允许您使用这个全局变量。