Sylvain
Sylvain

Reputation: 563

python 3 - a method to store fictional items in a bag list - for text base game

I am trying to code a simple text based game.

So I need a method that can be called with a command such 'bag', and which will display the content of 'bag', a list.

I tried this but to no avail:

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')

I used the list function 'count' (bag.count(2) just to test. Ideally, I would need a function that would return True if there is any number of items.

Any help will be much appreciated, thanks!

Upvotes: 0

Views: 894

Answers (2)

Sylvain
Sylvain

Reputation: 563

I finally got it:

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")

Upvotes: 1

User
User

Reputation: 14873

You would do

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

looked at the source code and it says:

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

So you need to do

def do_bag(...):
    ...

Upvotes: 1

Related Questions