将全局变量设置为对象 Python 3.3



我一直在尝试进行开放式文本冒险。我试图设置九个房间,你可以在里面移动,但我认为我这样做的方式在 python 中是不可能的。有没有类似的方法可以做到这一点?解决方法?这是代码:(顺便说一下,我知道用户还没有办法交互)

class Room:
    def __init__(self, north, east, south, west, desc):
        self.north = north
        self.east = east
        self.south = south
        self.west = west
        self.desc = desc
loc1 = Room(False, loc2, loc4, False, "You can go east and south")
loc2 = Room(False, loc3, loc5, loc1, "You can go east, south, and west")
loc3 = Room(False, False, loc6, loc2, "You can go west and south")
loc4 = Room(loc1, loc5, loc7, False, "You can go north, east, and south")
loc5 = Room(loc2, loc6, loc8, loc4, "You are in the center room, with paths in all directions")
loc6 = Room(loc3, False, loc9, loc5, "You can go north, west, and south")
loc7 = Room(loc4, loc8, False, False, "You can go north and east")
loc8 = Room(loc5, loc9, False, loc7, "You can go north, east, and west")
loc9 = Room(loc6, False, False, loc8, "You can go north and west")
location = loc5
def Interpret(b):
    global location
    if b == 'help':
        print('To move around, type north, south, east and west. Make sure it's all in lowercase, so that the game can understand.')
    elif b == 'north':
        if location.north == False:
            print("You can't go that way.")
        else:
            location = location.north
    elif b == 'east':
        if location.east == False:
            print("You can't go that way.")
        else:
            location = location.eastth
    elif b == 'south':
        if location.south == False:
            print("You can't go that way")
        else:
            location = location.south
    elif b == 'west':
        if location.west == False:
            print("You can't go that way")
        else:
            location = location.west

您看到的问题是,在声明变量之前,您不能在方法调用中使用变量。撇开使用每个房间变量的样式问题不谈,解决该问题的一种方法是将设置移动到创建所有房间后可以调用的方法;

class Room:
    def setup(self, north, east, south, west, desc):
        self.north = north
        self.east = east
        self.south = south
        self.west = west
        self.desc = desc
loc1 = Room()
loc2 = Room()
loc3 = Room()
loc4 = Room()
...
loc9 = Room()
loc1.setup(False, loc2, loc4, False, "You can go east and south")
loc2.setup(False, loc3, loc5, loc1, "You can go east, south, and west")
loc3.setup(False, False, loc6, loc2, "You can go west and south")
loc4.setup(loc1, loc5, loc7, False, "You can go north, east, and south")
...
loc9.setup(loc6, False, False, loc8, "You can go north and west")

相关内容

  • 没有找到相关文章

最新更新