Python libtcod:对象描述功能错误

时间:2014-07-16 12:57:55

标签: python roguelike libtcod

我正在通过libtcod python教程工作,我决定搞砸一些代码,使它今天变得更加独特,并决定从一个功能开始,让玩家将鼠标悬停在某个对象上并按“' d”对于该对象的描述。

我目前遇到属性错误:' str'对象没有属性'描述'第657行。我尝试了很多不同的东西,但是看起来没有用,不幸的是我的理解水平现在非常有限,所以我无法弄清楚出了什么问题。

以下是相关的类和功能:

class Object:
    #this is a generic object: the player, a monster, an item, the stairs...
    #it's always represented by a character on screen.
    def __init__(self, x, y, char, name, color, blocks=False, fighter=None, ai=None, item=None, description=None):
        self.x = x
        self.y = y
        self.char = char
        self.name = name
        self.color = color
        self.blocks = blocks
        self.fighter = fighter
        if self.fighter: #let the fighter component know who owns it
            self.fighter.owner = self
        self.ai = ai
        if self.ai: #let the ai component know who owns it
            self.ai.owner = self
        self.item = item
        if self.item: #let the item component know who owns it, like a bitch
            self.item.owner = self
        self.description = self
        if self.description: #let the description component know who owns it
            self.description.owner = self

    def describe(self):
        #describe this object
        message(self.description, libtcod.white)

def handle_keys():
    global keys;

            if key_char == 'd':
                #show the description menu, if an item is selected, describe it.
                chosen_object = description_menu('Press the key next to an object to see its description.\n')
                if chosen_object is not None:
                    chosen_object.describe()

            return 'didnt-take-turn'

def description_menu(header):

    global mouse

    #return a string with the names of all objects under the mouse
    (x, y) = (mouse.cx, mouse.cy)

    #create a list with the names of all objects at the mouse's coordinates and in FOV
    names = [obj.name for obj in objects if obj.x == x and obj.y == y and libtcod.map_is_in_fov(fov_map, obj.x, obj.y)]

    names = ', '.join(names) #join the names, seperated by commas
    return names.capitalize()

    #show a menu with each object under the mouse as an option
    if len(names) == 0:
        options = ['There is nothing here.']
    else:
        options = [item.name for item in names]

    index = menu(header, options, INVENTORY_WIDTH)

    #if an item was chosen, return it
    if index is None or len(names) == 0: return None
    return names[index].description

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

函数description_menu()具有以下return

names[index].description

这是一个属于Object的字符串成员 当你说

chosen_object.describe()

您正在调用describe()方法,但该方法属于Object类,而不是字符串(因此为attribute error: 'str' object has no attribute 'describe')。您必须description_menu()返回Object而不仅仅是其名称。

相关问题