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

时间:2013-08-16 19:50:10

标签: python nameerror

我有两个文件。 myclasses.py包含我游戏的所有类,game.py创建所有对象并运行游戏。我想我收到了错误,因为我的GameEngine对象无法看到secondRoom对象。我在全局范围内创建了secondRoom。我不明白为什么GameEngine无法看到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)

3 个答案:

答案 0 :(得分:0)

将secondRoom传递给StartGame:

mygame.StartGame(player, firstRoom, secondRoom)

此外,应使用

初始化StartGame方法中的变量
this.player = player
this.firstRoom = firstRoom
this.secondRoom = secondRoom
this.gameIsRunning = False

稍后将其与this.first/secondRoom一起使用。

答案 1 :(得分:0)

简短回答:全球意味着模块全球化。

答案很长:实际上你的引擎不需要看第二个房间,因为connects_to

中引用了它

尝试更换:

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.'

答案 2 :(得分:-1)

您为 secondRoom 提供了一个空项目列表。

secondRoom = Room("ROOOM 2", ['south', 'east'], [])

也许您应该为 init 方法参数添加值:

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

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