岩石,纸,剪刀 - Python

时间:2016-03-24 01:58:28

标签: python

我正在尝试为课堂完成摇滚,纸张,剪刀任务。

我收到"UnboundLocalError: local variable 'tied' referenced before assignment"错误。

有人可以告诉我为什么我收到此错误?

import random

user_score = 0
computer_score = 0
tied = 0

def main():
print ("Let's play the game of Rock, Paper, Scissors. ")

while True:
    print ("Your current record is", user_score, "wins,", computer_score,     "losses and", tied, "ties")

    computer_choice = random.randint(1,3)
    if computer_choice == 1:
        computer_rock()
    elif computer_choice == 2:
        computer_paper()
    else:
        computer_scissors()    

def computer_rock():
     user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
     if user_choice == "1":
        print ("Draw! You both chose Rock.")
        tied += 1            
        try_again()
     elif user_choice == "2":
        print ("You Win! The computer chose Rock, while you picked Paper.")
        user_score += 1            
        try_again()
    elif user_choice == "3":
        print ("You Lose! You chose scissors, while the computer picked Rock.")
        computer_score += 1            
        try_again()
else:
    print ("ERROR: Invalid entry, please re-enter your choice. ")
    computer_rock()

def computer_paper():
    user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
    if user_choice == "1":
        print ("You Lose! You chose rock, while the computer picked Paper.")
        computer_score += 1        
        try_again()
    elif user_choice == "2":
        print ("Draw! You both picked Paper.")
        tied += 1            
        try_again()
    elif user_choice == "3":
        print ("You Win! The computer chose Paper, while you picked Scissors.")
        user_score += 1                    
        try_again()
    else:
        print ("ERROR: Invalid entry, please re-enter your choice. ")
        computer_paper()

def computer_scissors():
    user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
    if user_choice == "1":
        print ("You Win! You chose rock, while the computer picked Scissors.")
        user_score += 1  
        try_again()                  
    elif user_choice == "2":
        print ("You Lose! The computer chose Scissors, while you picked Paper.")
        computer_score += 1                    
        try_again()
    elif user_choice == "3":
        print ("Draw! You both picked Scissors.")
        tied += 1            
        try_again()
    else:
        print ("ERROR: Invalid entry, please re-enter your choice. ")
        computer_scissors()

def try_again():
    choice = input("Play again? Yes or no. ")
    if choice == "y" or choice == "Y" or choice == "yes" or choice == "Yes":
        main()
    elif choice == "n" or choice == "N" or choice == "no" or choice == "No":
        print ("Thanks for playing. ") 
    else:
        print ("Try again")
        try_again()

main()

3 个答案:

答案 0 :(得分:2)

将以下代码添加为三个computer_()函数中的每一个的第一行应该可以解决您的问题。

global tied, user_score, computer_score

有更好的方法来完成你正在做的事情,但这应该让你超越驼峰:)

答案 1 :(得分:1)

虽然Triptych的答案完全可以接受(并且也被广泛使用),但对于相对新手级的程序员来说,通常更好的做法是将参数传递给函数而不是使用global关键字。

可以在Python文档中找到更多信息:https://docs.python.org/3/tutorial/controlflow.html#defining-functions

本质上,重点是程序员将所谓的参数(或参数)传递给函数,包含那些参数的函数可以处理这个数据和返回值返回到调用它的位置,类似于print()函数的工作方式。您将字符串(例如"Hi")传递到print()函数(例如print("Hi")),此内置函数中的代码将字符"Hi"显示在屏幕上

在这种情况下,您的代码看起来像这样:

# In your main function:

def main():
print ("Let's play the game of Rock, Paper, Scissors. ")

while True:
    print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")
        computer_choice = random.randint(1,3)
    if computer_choice == 1:
        result = computer_rock(user_score, computer_score, tied)  ## Notice the difference here
    elif computer_choice == 2:
        result = computer_paper(user_score, computer_score, tied)  ## Those variables you put in the function call are arguments
    else:
        result = computer_scissors(user_score, computer_score, tied)


# ...

# In the computer_rock() function:
# Even though I only modified this function, you should probably modify all three to suit your needs.

def computer_rock(user_score, computer_score, tied): ## <-- See the parameters?
    user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
    if user_choice == "1":
        print ("Draw! You both chose Rock.")
        tied += 1            
        try_again()
    elif user_choice == "2":
        print ("You Win! The computer chose Rock, while you picked Paper.")
        user_score += 1            
        try_again()
    elif user_choice == "3":
        print ("You Lose! You chose scissors, while the computer picked Rock.")
        computer_score += 1            
        try_again()
    return [user_score, computer_score, tied] # Returning a list so it is easier to sort variables

另外需要注意的是,即使您正在调用try_again()来重新启动游戏,在main()调用的函数内调用main()也不是一个好主意。 }。最好在main函数中使用while循环来调节和控制程序的流程。

希望这有帮助!

答案 2 :(得分:0)

它是由Python中的一个功能引起的。 以下示例发出相同的异常。请注意您无法在 Local-Scope 中分配全局变量

>>> variable = 1
>>> def function():
...     variable += 1
...
>>> function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in function
UnboundLocalError: local variable 'variable' referenced before assignment

因此,如果您按以下方式编写, Globale-Variable 的值未更改。 function()中的此变量不是全局变量,但本地变量。正确?

>>> variable = 1
>>> def function():
...  variable = 2
...
>>> function()
>>> variable
1

顺便说一下,这个功能对我们很有用,因为我们想要使用尽可能小的功能,如果大声说话,只是因为我们人类不了解长功能。 < / p>

也许您现在想在这里使用全局变量,但是当您编写许多代码并且可以使用全局变量时,您会感到恐慌as&#34;这个变量在哪里变化?&#34;因为有很多地方你改变了。

如果我们有代码,我们无法知道我们在哪里更改,这些代码将是神秘的代码。真是太恶心了。

@priptych的答案也是对的。如果你采纳他的答案,这个代码将起作用。但是,我建议您不要使用全球

P.S。您可以在 JavaScript 中执行此操作。