Python 为什么我会得到(NameError:未定义全局名称'secondRoom')?

Python 为什么我会得到(NameError:未定义全局名称'secondRoom')?,python,nameerror,Python,Nameerror,我有两个文件。myclasses.py拥有我游戏的所有类,game.py创建所有对象并运行游戏。我想我会出错,因为我的GameEngine对象看不到secondRoom对象。我在全局范围内创建了secondRoom。我不明白为什么游戏引擎看不到第二个房间 ## game.py from myclasses import * ## Creating objects smallKey = Key("Small Key") bossKey = Key("Boss Key") firstRoom = R

我有两个文件。myclasses.py拥有我游戏的所有类,game.py创建所有对象并运行游戏。我想我会出错,因为我的GameEngine对象看不到secondRoom对象。我在全局范围内创建了secondRoom。我不明白为什么游戏引擎看不到第二个房间

## game.py
from myclasses import *
## Creating objects
smallKey = Key("Small Key")
bossKey = Key("Boss Key")
firstRoom = Room("Room", ['north', 'south'], [smallKey, bossKey])
secondRoom = Room("ROOOM 2", ['south', 'east'], [])
player = Person(raw_input("Please enter your name: "), firstRoom)
## Setting class variables
firstRoom.description = "This is the first room"
secondRoom.description = "This is the second room..." 
firstRoom.connects_to = {"north": secondRoom}
secondRoom.connects_to = {"south": firstRoom}
list_of_rooms = [firstRoom, secondRoom]  
## Running the game
mygame = GameEngine()
mygame.StartGame(player, firstRoom)
myclass.py:

from sys import exit

class Person(object):
    ## Class Variables
    inventory = []

    ## Class Functions
    def __init__(self, name, room):
        ## Instance Variables
        self.name = name
        self.current_room = room
    def Move(self, room):
        self.current_room = room
    def pickup(item):
        pass

class Item(object):
    def __init__(self, name):
        self.name = name

class Key(Item):
    def __init__(self, name):
        self.name = name


class Room(object):
    ## Class Variables
    description = ''
    connects_to = {}

    ## Class Functions
    def __init__(self, name, directions, items):
        self.name = name 
        self.list_of_directions = directions
        self.items = items
    def print_description(self):
        print self.description

    def print_items_in_room(self):
        for item in self.items:
            print item.name

class GameEngine(object):
    list_of_commands = ['move <direction>',
                        'pickup <item>',
                        'room description',
                        'show inventory',
                        'quit\n']      
    def GetCommand(self):
        return raw_input('> ')

    def StartGame(self, player, room):
        player = player
        room = room
        gameIsRunning = False
        print "The game has officially started... Good Luck!\n\n"

        while(not gameIsRunning):
            print "List of Directions:"
            print "------------------"
            for direction in room.list_of_directions:
                print direction

            print "\nList of Items in Room:"
            print "----------------------"
            for item in room.items:
                print item.name

            print "\nList of Commands:"
            print "-----------------"
            for action in self.list_of_commands:
                print action

            command = self.GetCommand()
            if command == 'quit':
                exit(0)
            if command == 'move north':
                if 'north' in room.list_of_directions and room.connects_to['north'] == secondRoom:
                    player.Move(secondRoom)
                    room = secondRoom
            if command == 'move south':
                if 'south' in room.list_of_directions and room.connects_to['south'] == firstRoom:
                    player.Move(firstRoom)
                    room = firstRoom
                else:
                    print "You can't go that direction."
            if command == 'move east':
                if 'east' in room.list_of_directions:
                    print 'You just died >:}'
                    exit(0)
            if command == 'pickup small key':
                for item in room.items:
                    print item.name
                    if item.name == 'Small Key':
                        player.inventory.append(item)
                        room.items.remove(item)
你给了第二个房间一张空物品清单

secondRoom = Room("ROOOM 2", ['south', 'east'], [])
也许您应该在init方法参数中添加一个None值:

class Room(object):
    # Class Variables
    description = ''
    connects_to = {}

    ## Class Functions
    def __init__(self, name, directions, items=None):
        pass

将第二个房间传给StartName:

mygame.StartGame(player, firstRoom, secondRoom)
另外,StartGame方法中的变量应该用

this.player = player
this.firstRoom = firstRoom
this.secondRoom = secondRoom
this.gameIsRunning = False

稍后再使用。第一个/第二个房间。

简短回答:全局意味着模块全局

详细回答:实际上,您的引擎不需要看到第二个房间,因为它在“连接到”中被引用

尝试替换:

if command == 'move north':
    if 'north' in room.list_of_directions and 'north' in room.connects_to:
        player.Move(room.connects_to['north'] )
        room = room.connects_to['north']
南方也是一样

或者更一般地说:

if command.startswith ('move '):
    direction = command [4:].strip ()
    if direction in room.list_of_directions and direction in room.connects_to:
        player.Move(room.connects_to[direction] )
        room = room.connects_to[direction]
甚至:

if command.startswith ('move '):
    direction = command [4:].strip ()
    if direction in room.list_of_directions:
        if direction in room.connects_to:
            player.Move(room.connects_to[direction] )
            room = room.connects_to[direction]
        else:
            print 'You fell off the world' #(valid direction but no room behind)
    else:
        print 'Thou shalst not move this way.'

修正你的代码格式。只需将代码粘贴进去,高亮显示,然后按CTRL-K键。这些文件在不同的文件中吗?全局变量仅对定义它们的模块是全局的。不要使用或标记,而且绝对不要像现在这样以错误的顺序关闭它们。有一个格式为代码的按钮,看起来像一对大括号,或者您可以使用Ctrl-K,或者如果您想手动执行,您可以缩进代码4的空格。