gpt4 book ai didi

python - 如何访问具有特定 Class 属性值的 Class 实例?

转载 作者:行者123 更新时间:2023-12-01 06:25:23 24 4
gpt4 key购买 nike

我正在用 Python 制作一个基于文本的 RPG,并尝试设置 map 和玩家移动。然而,我还没有弄清楚如何“链接”房间,以便玩家可以使用北、南等命令从一个房间无缝移动到另一个房间。

我正在使用一个名为“Room”的类,它具有 x 坐标和 y 坐标属性。我已经在 map 中创建了每个“图 block ”的实例,并具有特定的 x-pos 和 y-pos 值。我想做的是根据当前的 x-pos 或 y-pos 转到“Room”类的当前实例。但是,我不知道如何根据属性值查找类实例。

下面是我的代码。任何帮助将不胜感激。

class Room:
def __init__(self,name,info,xpos,ypos,exits):
self.instances.append(self)
self.name = name
self.info = info
self.xpos = xpos
self.ypos = ypos
self.exits = exits

作为引用,room.exits 是您可以退出房间的哪些部分。这可能只是“s”和“n”,表示东边和西边都有墙。

为了进一步引用,在下面的代码中,cloc 代表当前位置。我目前将其设置为:

intro_room = Room("Living Room of House", "You are in a dusty living room, in a stranger's house. You don't know how you got here. It's hard to see and your hands are tied", 100, 100, ['s','n'])
cloc = intro_room

另一段代码:

def inp():
basic = input(">")
if basic == 'i':
print(" ")
print("This is what is in your current inventory", inventory)
elif basic == 'h':
print(" ")
### use this when programming actual game
print("Available commands:\n-move\n-take\n-look\n-talk\n-use\n-enter")
elif basic == 'm':
print(" ")
print(current_location)
elif basic == 'description':
print(cloc.name, cloc.info)
elif basic == 'n':
cloc = Room.get(ypos==ypos+1) ###try to access instance with certain instance attribute value???
#etc. for 's', 'e', 'w'

上面的代码不起作用,因为我不知道如何执行 map 移动。

最佳答案

您可以在 dict 中组织所有房间,其中键是 2 元组 (xpos, ypos)。然后,根据您的导出,您可以退出到不同的房间。

all_rooms = {
(0, 0): Room(..., xpos=0, ypos=0, ...),
(0, 1): Room(..., xpos=0, ypos=1, ...),
...
}

def inp():
...
elif basic == "move":
direction = input(f"Which direction? Your options are {cloc.exits}. \n>")
if direction in cloc.exits:
# determine new coordinate set based on direction
new_loc = {
'n': (cloc.xpos, cloc.ypos + 1),
's': (cloc.xpos, cloc.ypos - 1),
'e': (cloc.xpos + 1, cloc.ypos),
'w': (cloc.xpos - 1, cloc.ypos),
}[direction]
# change current location to the new room
cloc = all_rooms[new_loc]
else:
print("You can't move in that direction.")
elif ...

关于python - 如何访问具有特定 Class 属性值的 Class 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60174999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com