为什么要获取(名称错误:未定义全局名称“secondRoom”)?

2024-09-30 08:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两份文件。我的类.py为我的比赛准备了所有的课程游戏.py创建所有对象并运行游戏。我想我得到了错误,因为我的GameEngine对象看不到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)

在我的class.py公司名称:

^{pr2}$

Tags: the对象keypygame游戏roomplayer
3条回答

把第二个房间传给StartGame:

mygame.StartGame(player, firstRoom, secondRoom)

另外,StartGame方法中的变量应该用

^{pr2}$

{cd1>以后使用。在

简而言之:全局是指模块全局。在

长回答:实际上,您的引擎不需要看到第二个房间,因为它在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']

南方也一样。在

或者更广泛地说:

^{pr2}$

甚至:

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

你给了你的二房一张空的物品清单。在

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

也许您应该添加一个None值您的init方法参数:

^{pr2}$

相关问题 更多 >

    热门问题