基于文本的游戏中的UnboundLocalError

时间:2016-04-04 22:14:35

标签: python python-2.7

当我尝试在此游戏中移动时,它为变量提供了一个UnboundLocalError。我不明白为什么会这样,有人可以向我解释并告诉我如何解决它吗?

pro = '> '
import random
chamber = random.randint(1, 6)
def initialMenu():
    print "Welcome to Russian Roulette!"
    print 'Type "R" for the rules or "P" to play.'
    play_or_rules = raw_input(pro)
    if play_or_rules == 'r' or play_or_rules == 'R':
        rules()
    elif play_or_rules == "P" or play_or_rules == 'p':
        turn()
    else:
        print 'ERROR: Must type in "R" or "P" at the beginning. Restarting program.\n'
        initialMenu()

def rules():
    print "You have a revolver. You and 1 friend play this game. You load 1 bullet into one of the six chambers."
    print "On your turn, you can pull the trigger on yourself, on your opponent and then yourself, or spin the chamber."
    print "You may spin the chamber as much as you like before firing."
    print "Once you fire at yourself, your turn ends, and your friend's begins."
    print "Keep in mind that the game isn't completely random; there can be some strategy to it.\n"
    initialMenu()
def turn():
    print 'Type "Q" to shoot yourself, "W" to shoot your opponent and then yourself, or "E" to spin the chamber.'
    move = raw_input(pro)
    if move == 'q' or move == 'Q':
        if chamber == 1:
            print "BANG! Your brain splatters on the wall. YOU LOSE"
        else:
            print "CLICK! You live another round."
            chamber += 1
            if chamber == 7:
                chamber = 1
                turn()
            else:
                turn()
    elif move == 'W' or move == "w":
        if chamber == 6:
            print "CLICK! Your opponent lives."
            print "BANG! You don't."
            print "YOU LOSE"
            #first shot would be blank, second wouldn't
        elif chamber == 1:
            print "BANG! Your opponent's head has a hole in it."
            print "YOU WIN"
        else:
            print "CLICK! Your opponent lives."
            print "CLICK So do you."
            chamber += 2
            if chamber == 7:
                chamber = 1
                turn()
            elif chamber == 8:
                chamber = 2
                turn()
            else:
                turn()
    elif move == 'e' or move == 'E':
        chamber = random.randint(1, 6)
        print "You spun the chamber, but it is still your turn."
        turn()
initialMenu()

感谢您的帮助! 这是错误:

Traceback (most recent call last):
  File "C:/Python27/russianroulette.py", line 62, in <module>
    initialMenu()
  File "C:/Python27/russianroulette.py", line 11, in initialMenu
    turn()
  File "C:/Python27/russianroulette.py", line 61, in turn
    turn()
  File "C:/Python27/russianroulette.py", line 27, in turn
    if chamber == 1:
UnboundLocalError: local variable 'chamber' referenced before assignment

1 个答案:

答案 0 :(得分:4)

chamber是一个全局变量,当python试图找出变量的范围时,函数内的chamber被视为 local 变量UnboundLocalError