如何使两个类实例相互引用?

2024-10-01 07:50:59 发布

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

所以我对我制作的基于文本的游戏有点意见。游戏通过引用一个函数的命令来运行,然后函数寻找玩家想要的任何东西。例如,“examineitem1”会让它打印位置字典中item1的描述

我遇到的问题是,我不能用我当前的布局设置播放器的位置。我想要的是玩家从洞穴开始,进入go to forest,角色的位置设置为forest。然而,它没有达到这一点,因为不管我以哪种方式声明这两个,我都遇到了一个NameError。我想在两者之间移动

cave = location(
    name = "CAVE NAME",
    desc = "It's a cave, there's a forest.",
    objects = {'item1' : item1, 'item2' : item2, 'item3' : item3},
    adjacentLocs = {'forest' : forest}
)
forest = location(
    name = "The Central Forest",
    desc = "It's very woody here. There's a cave.",
    objects = {},
    adjacentLocs = {'cave' : cave}
)

这是我的goTo()函数:

def goTo():
    target = None
    #Check inventory
    for key in pChar.inventory:
        if key.name.lower() in pChar.lastInput:
            print("\nThat's an object in your inventory. You won't fit in your backpack.")
            target = key
            break

    #Check scene objects
    if target == None:
        for key, loc in pChar.charLocation.objects.items():
            if key in pChar.lastInput:
                print("\nThat's a nearby object. You have essentially already gone to it.")
                target = key
                break

    #Check location list
    if target == None:
        for key, loc in pChar.charLocation.adjacentLocs.items():
            if key in pChar.lastInput:
                pChar.charLocation = loc
                print("\nYou amble on over to the {}.".format(pChar.charLocation.name))
                target = key
                break

    if target == None:
        print("That place doesn't exist.")

我怎样才能最好地把这两门课相互联系起来呢


Tags: tokey函数nameinnonetargetif
1条回答
网友
1楼 · 发布于 2024-10-01 07:50:59

除非对象已经存在,否则不能引用它。您可以在两个过程中创建位置:首先,在没有任何相邻位置的情况下初始化它们。然后,定义相邻位置。比如:

cave = location(
    name = "CAVE NAME",
    desc = "It's a cave, there's a forest.",
    objects = {'item1' : item1, 'item2' : item2, 'item3' : item3},
    adjacentLocs = {}
)
forest = location(
    name = "The Central Forest",
    desc = "It's very woody here. There's a cave.",
    objects = {},
    adjacentLocs = {}
)

cave.adjacentLocs["forest"] = forest
forest.adjacentLocs["cave"] = cave

(这是假设位置实例将其相邻位置分配给名为adjacentLocs的属性。你没有分享你的类实现,所以我不能确定这个细节。以任何合适的名称替换。)

相关问题 更多 >