-2

我对 python 有疑问。这是我的代码。

http://pastebin.com/yRu5WGKd

每当我选择项目或镐时,它打印得很好。下面的任何内容都不会打印..请帮忙!?!

注意:我也使用了 pastebin,因为我发现它最容易阅读。

4

1 回答 1

1

Your actual mistake is the 62nd line, if ItemType == 3 & ItemStr == 1: - it should start with elif, or it breaks your (really nasty) if-cascade.

Another potential problem: in all your comparisons, ie if ItemType == 1 & ItemStr == 1:, you are using bitwise and (&) when you should be using logical and (and).

Here is a rewritten version. It is less than half the length, data-driven, and makes it much easier to spot inconsistencies (did you mean 'Diamond' or 'Emerald' in your material types?):

class Item(object):
    types = [
        ('Item',    'Item'),
        ('Pickaxe', 'ItemPickaxe'),
        ('Shovel',  'ItemSpade'),
        ('Axe',     'ItemAxe'),
        ('Hoe',     'ItemHoe'),
        ('Sword',   'ItemSword')
    ]
    strengths = [
        ('Diamond', 'EnumToolMaterial.EMERALD'),    # ?? You might want to doublecheck this...
        ('Gold',    'EnumToolMaterial.GOLD'),
        ('Iron',    'EnumToolMaterial.IRON'),
        ('Stone',   'EnumToolMaterial.STONE'),
        ('Wood',    'EnumToolMaterial.WOOD'),
    ]

    javastring = 'public static final {type} {name} = new {type}({id}, {strength}).setItemName("{name}");'

    @classmethod
    def prompt_for_item(cls):
        s = "Please enter your item's name:\n"
        name = raw_input(s).strip()

        types = ["[{}] {}".format(i,n[0]) for i,n in enumerate(cls.types, 1)]
        s = "Please enter item type:\n{}\n".format('\n'.join(types))
        type_ = int(raw_input(s)) - 1

        s = "Please enter item id (unique int):\n"
        id = int(raw_input(s))

        strengths = ["[{}] {}".format(i,n[0]) for i,n in enumerate(cls.strengths, 1)]
        s = "Please enter item strength:\n{}\n".format('\n'.join(strengths))
        strength = int(raw_input(s)) - 1

        return cls(name, type_, id, strength)

    def __init__(self, name, type_, id, strength):
        self.name = name
        self.type = type_
        self.id = id
        self.strength = strength

    def write_to_file(self, fname=None):
        if fname is None:
            fname = '{}.java'.format(self.name)
        with open(fname, 'w') as outf:
            cls = type(self)
            outf.write(
                cls.javastring.format(
                    type = cls.types[self.type][1],
                    name = self.name,
                    id = self.id,
                    strength = cls.strengths[self.strength][1]
                )
            )

def main():
    it = Item.prompt_for_item()
    it.write_to_file()
    print 'File has been written'

if __name__=="__main__":
    main()
于 2012-07-13T17:13:58.720 回答