python 3 - 一种将虚构物品存储在行李列表中的方法 - 用于文本基础游戏

时间:2014-04-12 18:47:34

标签: list python-3.x methods cmd command

我正在尝试编写一个简单的基于文本的游戏。

所以我需要一个可以用'bag'这​​样的命令调用的方法,它会显示'bag'的内容,列表。

我尝试了这个但无济于事:

import cmd

class Game(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)

        global bag
        bag = ['key1','key3']

    def bag(self,item):
        global bag

        print ("your bag contains: ")

        if self.bag.count(2):
            for i in bag:
                print(i)
                print("")
        else:
            print("your bag contains nothing")  

    def look_bag(self, args):
        self.bag('bag')

我使用list函数'count'(bag.count(2)来测试。理想情况下,如果有任意数量的项目,我需要一个返回True的函数。

非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

你会做

if bag:
    # there is something in the bag
else:
    # there is nothing in the bag

查看源代码并说:

            func = getattr(self, 'do_' + cmd)

所以你需要做

def do_bag(...):
    ...

答案 1 :(得分:1)

我终于明白了:

class Game(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)

        global bag
        bag = ['key1','key3']

        self.loc = get_room(1)
        self.look()

    def do_bag(self, line):
        global bag

        print ("your bag contains: ")

        if bag:
            for i in bag:
                print(i)
        else:
            print("your bag contains nothing")