Text adventure help

Hello all. I am trying to learn some python by creating a text adventure game. I am using the book - Make Your Own Python Text Adventure by Phillip Johnson as a reference but I am stuck on getting my inventory to display.

So far I have a folder with 3 document? Modules? I am not sure the correct word.

player.py and items.py come back as good but when i try and pull up my inventory on game.py file it comes back with this error. AttributeError: ‘Player’ object has no attribute ‘inventory’ player.py, line 13

This is my game.py file

from player import Player
        

def play():  
    print("Welcome to Gateway!")
    player = Player()
    while True:
        action_input = get_player_command()
        if action_input in ['n', 'N', '8']:
            print("Go North")
        elif action_input in ['s', 'S', '2']:
            print("Go South")
        elif action_input in ['e', 'E', '6']:
            print("Go East")
        elif action_input in ['w', 'W', '4']:
            print("Go West")
        elif action_input in ['i', 'I']:
            player.print_inventory()
        else:
            print("Invalid Action")
    
    
def get_player_command():
    return input('Action: ')


play()

This is my player.py file

import items


class Player:
    def _init_(self):
        self.inventory = [items.Rock(),
                          items.Dagger(),
                          'Gold(5)',
                          'Crusty Bread']
        
    def print_inventory(self):
        print("Inventory:")
        for item in self.inventory:
            print('* ' + str(item))
        best_weapon = self.most_powerful_weapon()
        print("Your best weapon is your {}".format(best_weapon))
        
    def most_powerful_weapon(self):
        max_damage = 0
        best_weapon = none
        for item in self.inventory:
            try:
                if item.damage > max_damage:
                    best_weapon = item
                    max_damage = item.damage
            except AttributeError:
                pass
            
        return best_weapon

This is my items.py file

class Weapon:
    def _init_(self):
        raise NotImplementedError("Do not create raw Weapon objects.")
    
    def _str_(self):
        return self.name           
   

class Rock(Weapon):
    def _init_(self):
        self.name = "Rock"
        self.description = "A fist-sized rock, suitable for bludgeoning."
        self.damage = 5
 
 
class Dagger(Weapon):
    def _init_(self):
        self.name = "Dagger"
        self.description = "A small dagger with some rust. " \
                           "Somewhat more dangerous than a rock."
        self.damage = 10
        

class RustySword(Weapon):
    def _init_(self):
        self.name = "Rusty Sword"
        self.description = "This sword is showing its age, " \
                            "but still has some fight in it."
        self.damage = 20

All of the other commands in the game.py file work, the only one that returns with an error is inventory. I have been stuck on this for two days and I do not want to move on until this is resolved.

Thank you

You have some other problems (like “none” should be “None”), but the main one here is that most of the class special methods like init and str are often called “dunder” methods because they are surrounded by “Double UNDERscores” on both sides of the name. It may be hard to tell in some fonts.

Your methods have a single underscore on each side, so they don’t match and aren’t being called.

By Myron StCyr via Discussions on Python.org at 01Apr2022 02:56:

Hello all. I am trying to learn some python by creating a text
adventure game. I am using the book - Make Your Own Python Text
Adventure by Phillip Johnson as a reference but I am stuck on getting
my inventory to display.

So far I have a folder with 3 document? Modules? I am not sure the correct word.

You could just say 'files". But each is a “module”< which can be
imported as you are doing.

player.py and items.py come back as good

If you mean you can go:

python3 player.py

and get no errors, that just means that the syntax is good and that they
execute to the end of the file without error. Python, being dynamic, has
to execute a module in order to run the code which defines functions and
classes. You can think of them as big complex assignment statements, so
that this:

def f(a,b):
  return a+b

defines a function which does addition, and assigns it to the name “f”.
The same with classes. The point here is that these are things which are
executed in order to define these things: an “import” actually runs the
file which gets imports, though only the first time.

but when i try and pull up my inventory on game.py file it comes back
with this error. AttributeError: ‘Player’ object has no attribute
‘inventory’ player.py, line 13

At first glance your code looked good to me, which I suppose only
underscores that it “runs without error”. It does not mean it is
correct. On a closer read, look at this:

This is my player.py file

import items


class Player:
   def _init_(self):
       self.inventory = [items.Rock(),
                         items.Dagger(),
                         'Gold(5)',
                         'Crusty Bread']

This is your problem. When you create a new instance of a class, the
class’ intialisation function is run with the new instance, if it has
one. That’s what your method above is supposed to do. However, the
method which is called has its name spelled __init__, not _init_.

It is legal to not have an __init__ method, so nothing complains about
your class definition.

Technically, Player inherits (implicitly) from the class object,
which has an __init__ which does nothing.

Cheers,
Cameron Simpson cs@cskk.id.au

Thank you both! Not using a double underscore was indeed the problem. That is a fine detail that I cannot recall ever seeing specified in a beginner learning book. I might never have thought of checking for that on my own.

If the book (or whatever you consulted to learn how to create a class) didn’t include or specify double underscores when it mentioned special methods, then it presumably contains an error that should be reported to the author/publisher…that’s a pretty significant omission.

1 Like

The book shows examples but as a beginner, it was not easily discernible that it was supposed to be double underscores. I am thankful for all of your quick responses. It is these finer details that are easily missed by someone inexperienced.