为什么我得到一个全局名称错误

时间:2012-10-22 02:55:57

标签: python oop class

我目前遇到以下错误:

NameError: global name 'player1_unam' is not defined

如果有人可以请查看以下代码并给我一个问题的灵魂,我们将不胜感激。

我提前进行了alpologise,因为我知道它是非常混乱和低效的代码,但我只是python的初学者。

import os 
import random
from random import randint
game_won = False
p1_playing = True
p2_playing = True
class start_game(object):
    def __init__(self):
        suspect = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"] 
        weapon = ["Candlestick","Dagger","Lead Pipe","Revolver","Rope","Spanner"]
        room = ["Kitchen","Ballroom","Conservatory","Billiard Room","Library","Study","Hall","Lounge","Dining Room","Cellar"]
        rndsuspect = random.randrange(0, 5 ,1)
        rndweapon = random.randrange(0,5,1)
        rndroom = random.randrange(0,9,1)
        answers = []
        answers.append(suspect[rndsuspect])
        answers.append(weapon[rndweapon])
        answers.append(room [rndroom])      
        print answers[0]
        print answers[1]
        print answers[2]

class game_type:
    def __init__(self):
        select_game = raw_input("Do you want to start the game? ")
        lstchar = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"]
        if select_game.lower() == "yes":
            player1_unam = raw_input("What is Player 1's Name? ").lower().title()
            player1_cindex = int(input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] '))
            player1_char = lstchar[player1_cindex - 1]
            print ("%s has chosen to play as %s") %(player1_unam,player1_char)
            player2_unam = raw_input("What is Player 2's Name? ").lower().title()
            if player2_unam == player1_unam:
                while player2_unam == self.player1_unam:
                    player2_unam = player2_unam = raw_input("You can't use the same Name as Player 1, please choose again: ")
            player2_cindex = input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] ')
            player2_char = lstchar[player2_cindex - 1]
            if player2_cindex == player1_cindex:
                while player2_cindex == player1_cindex:
                    print "Choose A Character Other Than: %s" %  lstchar[player1_cindex - 1]
                    player2_cindex = int(input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] '))
                    player2_char = lstchar[player2_cindex - 1]
                    print ("%s has chosen to play as %s") %(player2_unam,player2_char)

class dice_roll(game_type):
    def __init__(self, game_type):
        final_suggestion = False
        suggested_suspect = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"] 
        suggested_weapon = ["Candlestick","Dagger","Lead Pipe","Revolver","Rope","Spanner"]
        rolled_room = ["Kitchen","Ballroom","Conservatory","Billiard Room","Library","Study","Hall","Lounge","Dining Room","Cellar", "Corridor"]
        current_player = [player1_unam,player2_unam]
        chosen_room = []
        player1_room = []
        player2_room = []
        suggestion = []
        correct_elements = []
        introom = random.randrange(0,10,1)
        super(dice_roll,self). __init__(self)
        current_turn = 0
        while game_won == False and p1_playing == True and p2_playing == True: 
            if raw_input("Type 'Roll' to start your turn  %s" %current_player[current_turn]).lower() == "roll":
                dice = random.randrange(1,6,1)
                pass
                print "You have rolled a %d" % dice
                if dice == 1:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = rolled_room[introom]
                elif dice == 2:
                    introom = random.randrange(0,10,1)
                    print "You are now in the %s"  % rolled_room[introom]                   
                    if current_turn == 0:
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = rolled_room[introom]                  
                elif dice == 3:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[10]
                    else:
                        player2_room = rolled_room[10]
                elif dice == 4:
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d] "  % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    if current_turn == 0:
                        introom = int(input("Which Room Do You Choose? "))
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = int(input("Which Room Do You Choose? "))
                        player2_room = rolled_room[introom]
                elif dice == 5:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[10]
                    else:
                        player2_room = rolled_room[10]
                elif dice == 6:
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d] "  % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    if current_turn == 0:
                        player1_room = int(input("Which Room Do You Choose? "))
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = int(input("Which Room Do You Choose? "))
                        player2_room = rolled_room[introom]                   
                if player1_room == "Cellar" or player2_room == "Cellar":
                        if raw_input("Do you want to make a final suggestion? ").lower == "yes":
                            final_suggestion = True
                elif player1_room != "Corridor" and player1_room != "Cellar" or player2_room != "Corridor" and player2_room != "Cellar":
                    suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                    suggestion.append(suggested_suspect[suggestion_index - 1])
                    suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                    suggestion.append(suggested_weapon[suggestion_index - 1])
                    if current_turn == 0:
                        suggestion.append(player1_room)
                    else:
                        suggestion.append(player2_room)
                        if suggestion [0] == start_game.answers [0]:
                            correct_elements.append(suggestion[0])
                        elif suggestion [1] == start_game.answers [1]:
                            correct_elements.append(suggestion[1])
                        elif suggestion [2] == start_game.answers [2]:
                            correct_elements.append(suggestion[2])
                        intcorrect = len(correct_elements)            
                    if final_suggestion == True:
                            suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                            suggestion.append(suggested_suspect[suggestion_index - 1])
                            suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                            suggestion.append(suggested_weapon[suggestion_index - 1])
                            suggestion_index = int(input("Where do you think the crime was committed? Kitchen [1],Ballroom [2],Conservatory [3], Billiard Room [4], Library [5], Study [6], Hall [7], Lounge [8], Dining Room [9], Cellar [10]"))
                            suggestion.append(rolled_room[suggestion_index - 1])
                            if suggestion[0] == start_game.answers[0] and suggestion [1] == start_game.answers [1] and suggestion [2] == start_game.answers [2]:
                                game_won = True
                                print "%s Has won the game :D" %current_player[current_turn]
                                print "%s committed the murder with the %s in the %s" %(start_game.answers[0],start_game.answers[1],start_game.answers[2])
                                print "Thankyou for playing CLUEDO"
                                if raw_input("Would you like to play again? ").lower == "yes":
                                    run_game = game_type(__init__)          
                elif player1_room != "Corridor" and player1_room != "Cellar" or player2_room != "Corridor" and player2_room != "Cellar":
                        suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                        suggestion.append(suggested_suspect[suggestion_index - 1])
                        suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                        suggestion.append(suggested_weapon[suggestion_index - 1])
                        if current_turn == 0:
                            suggestion.append(player1_room)
                        else:
                            suggestion.append(player2_room)
                        if suggestion [0] == start_game.answers [0]:
                           correct_elements.append(suggestion[0])
                        elif suggestion [1] == start_game.answers [1]:
                            correct_elements.append(suggestion[1])
                        elif suggestion [2] == start_game.answers [2]:
                            correct_elements.append(suggestion[2])
                        intcorrect = len(correct_elements)
                if intcorrect == 0:
                    print "None of those facts are correct"
                    del correct_elements[0:len(correct_elements)]
                    del suggestion[0:len(suggestion)]
                    else:
                        shown_card = random.choice(correct_elements)
                        print "You got %s correct" %shown_card
                        del correct_elements[0:len(correct_elements)]
                        del suggestion[0:len(suggestion)]
            current_turn += 1                
            if current_turn == 2:
                current_turn = 0

run_game = game_type()
suspectinfo = start_game()           
roll = dice_roll(game_type)

run_game()#.__init__()
suspectinfo()#.__init__()
roll()

谢谢你的帮助

3 个答案:

答案 0 :(得分:0)

您需要使用

self.player1_unam

而不是

player1_unam

否则,当您进行初始赋值时,会创建一个局部变量,当您尝试取消引用(访问)它时,Python首先会查找一个局部变量,然后查找一个全局变量,并且两次都失败它会给你那个错误。

答案 1 :(得分:0)

您需要使用self.player1_unam因为python正在查找global命名空间而不是本地命名空间(在定义它的类的内部)。

例如,以下可以是全局命名空间中的值,而self.player1_unam在类中定义:

def player1_unam():
    print "I am in the global namespace!"

或变量:

player1_unam="I am in the global namespace!"

或班级:

class player1_unam(object):
    pass

值得注意的是,您必须更改 每次 使用player1_unamself.player1_unam才能解决此问题。

答案 2 :(得分:0)

为什么不从一开始就让玩家一个名字变成一个变量? 我觉得会更好。

 class game_type:
    def __init__(self):
        global  player1_unam
        ...
        player1_unam = raw_input("What is Player 1's Name? ").lower().title()