SchrodingersStat
SchrodingersStat

Reputation: 291

Difficulty with Inventory and Room system in a text based game

I'm a fairly new programmer, been struggling for a few years on and off with brief exposure to a few languages. I'm trying to finally get a firm grasp with Python, and to do so my current project is to design a simple text based game like "Zork".

I've successfully made an EXTREMELY simple version of this using functions for each room, however this isn't generalizable at all. Before I explain what I'm currently working on poorly, I'll link the code. Now as you can see, this is a very inefficient way of building rooms as it requires tons of code and I can't use it for anything except this exact game.

To start I created a list to be used as the player inventory

    inventory = []


def addToInventory(item):
    inventory.append(item)

This is the class I am using to construct weapons, and is where my trouble starts. The class works fine, and I can even add instances of it to my inventory list successfully.

class Weapon:

    def __init__(self, name, damage, speed, weight):
        self.name = name
        self.damage = damage 
        self.speed = speed
        self.weight = weight

sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)

This is the class I am attempting to design to create rooms. It has not been implemented yet. Right now the issue that I'm facing is that unable to add instances of the Weapon class to the argument for Roominv. So for example, I could not use the sword instance of my weapon class as an argument for the contents of a Room, it tells me that sword is undefined.

Entrance = Room("You are at an entrance", "N", "Search the ground", sword)

Now my goal with this project really is to learn, so I don't want any code, but am I going down the right path with this? How can I tie certain instances of the weapons class to certain rooms? Should I be using dictionaries to build the rooms instead? If I SHOULD be using dictionaries, do I have to create an individual dictionary for each room or are nested dictionaries a thing?

I've searched a lot for the answers to these as I'm sure similar questions have been asked, but I can't seem to find a straight answer.

class Room:

def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
    self.description = description
    self.exits = exits
    self.actions = actions
    self.Roominv = Roominv


def GAMEOVER():
    print("Oh no, it appears you have died. Press 1 to restart")

    choice = input(">>> ")

    if choice == "1":
        intro()

def introstrt(): 
    print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
    print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
    print("THEN LOOK NO FURTHER!")
    print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
    print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
    print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
    print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
    print("  A     A     A      A     ooo")
    print(" vvv   vvv   vvv    vvv   ooooo")
    print("vvvvv vvvvv vvvvv  vvvvv   ooo")
    print("  H     H     H      H")
    print("  A     A     A      A")
    print(" vvv   vvv   vvv    vvv    | O  __")
    print("vvvvv vvvvv vvvvv  vvvvv   +-|-(__) ")
    print("  H     H     H      H      / \ ")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("PRESS 1 TO BEGIN")

    choice = input(">>> ")


    if choice == "1":
        intro()
    else:
        print("I can't understand that command")
        intro()

def intro():
    global inventory
    print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2. Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")
    print("5.View Intro")

    choice = input(">>> ")

if choice == "1":
    print("You don't find any sticks. This is a poorly designed forest.")
    intro()
elif choice == "2":
    print("Sweet backflip, what now?")
    intro()
elif choice == "3":
    print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
    print("GAME OVER.")
    GAMEOVER()
elif choice == "4":
    print("You move towards the clearing.")
    clearing()
elif choice == "Pick up sword":
    addToInventory(sword)
    print("Your bag contains", inventory)
    intro()
elif choice == "5":
    introstrt()
else:
    print("I can't understand that command")
    intro()
def clearing():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Curse the sun whilst masturbating vigorously")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
        clearingnofl()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearing()
    elif choice == "3":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        clearingdrk()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intro()
    else:
        print("I can't understand that command")
    clearing()

def clearingnofl():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Curse the sun whilst masturbating vigorously")
    print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofl()
    elif choice == "2":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        print("You notice the flower glowing brightly in your bag.")
        clearingnofldrk()
    elif choice == "3":
         print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intronofl()
    else:
        print("I can't understand that command")
        clearingnofl()
def clearingdrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
        clearingnofldrk()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearingdrk()
    elif choice == "3":
        print("The sun reluctantly forgives you, it is sunny again.")
        clearing()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        introdrk()
    else:
        print("I can't understand that command")
        clearingdrk()
def clearingnofldrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
   print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofldrk()
    elif choice == "2":
        print("The sun reluctantly forgives you, it is sunny again.")
    clearingnofl()
    elif choice == "3":
        print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
        intronofldrk()
    else:
        print("I can't understand that command")
        clearingnofldrk()
def intronofldrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        intronofldrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofldrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofldrk()
    else:
        print("I can't understand that command")
        intronofldrk()
def introdrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        introdrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        introdrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingdrk()
    else:
        print("I can't understand that command")
    introdrk()
def intronofl():
    print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest.")
        intronofl()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofl()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofl()
    else:
        print("I can't understand that command")
        intronofl()
introstrt()

Upvotes: 0

Views: 1502

Answers (1)

ryachza
ryachza

Reputation: 4540

I would start by adding more structure, separating the definition of the rooms from the IO/action evaluation.

In terms of maintining state, one possibility (using introSword as an example) is to modify the containing Room within the action, changing the available future actions.

You'd have to change the input and output definitions for Python 3. Hopefully those are the only changes needed.

import traceback as tb

try:
  input = raw_input

  def output(*args):
    print ''.join(map(str,args))

  inventory = []

  class Weapon:
    def __init__(self, name, damage, speed, weight):
      self.name = name
      self.damage = damage 
      self.speed = speed
      self.weight = weight

    def __repr__(self):
      return self.name

  sword = Weapon("Sword", 7, 5, 5)
  knife = Weapon("Knife", 5, 7, 3)
  stick = Weapon("Stick", 2, 3, 3)

  class Room:
    def __init__(self,description,exits,actions,others=[]):
      self.description = description
      self.exits = exits
      self.actions = actions
      self.others = others

    def render(self):
      output(self.description)

      if self.actions:
        output('You can:')
        for id,name,_ in self.actions:
          output(id,'. ',name)

      choice = input('>>> ').upper()

      for id,_,action in self.actions:
        if choice == id.upper():
          action(self)
          break
      else:
        for id,action in self.others:
          if choice == id.upper():
            action(self)
            break
        else:
          output('I can\'t understand that command')
          self.render()

  quit = False

  while not quit:
    def introstrtBegin(room):
      intro.render()

    introstrt = Room(
      '''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
  A     A     A      A     ooo
 vvv   vvv   vvv    vvv   ooooo
vvvvv vvvvv vvvvv  vvvvv   ooo
  H     H     H      H
  A     A     A      A
 vvv   vvv   vvv    vvv    | O  __
vvvvv vvvvv vvvvv  vvvvv   +-|-(__)
  H     H     H      H      / \ 
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
      ''',
      [],
      [],
      [('1',introstrtBegin)]
    )

    def gameoverRestart(_):
      global quit
      quit = False

    def gameoverQuit(_):
      global quit
      quit = True

    gameover = Room(
      'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
      [],
      [],
      [('1',gameoverRestart)
      ,('2',gameoverQuit)
      ]
    )

    def introSticks(room):
      output('You don\'t find any sticks. This is a poorly designed forest.')
      room.render()

    def introBackflip(room):
      output('Sweet backflip, what now?')
      room.render()

    def introWildlife(room):
      output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
      output('GAME OVER.')
      gameover.render()

    def introClearing(room):
      output('You move towards the clearing.')
      clearing.render()

    def introNoSword(room):
      output('You already picked up the sword')
      room.render()

    def introSword(room):
      global inventory
      inventory.append(sword)
      output('Your bag contains: ',inventory)

      room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
      room.others = [
        ('pick up sword',introNoSword)
      ]

      room.render()

    intro = Room(
      '''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
      ''',
      [],
      [('1','Look for sticks',introSticks)
      ,('2','Do a backflip',introBackflip)
      ,('3','Attempt to befriend wildlife',introWildlife)
      ,('4','Go to Clearing',introClearing)
      ,('5','View Intro',lambda _: introstrt.render())
      ],
      [('pick up sword',introSword)]
    )

    def clearingFlower(room):
      output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
      room.render()

    def clearingHarp(room):
      output('You can\'t tell which direction the music is coming from!.')
      room.render()

    def clearingCurse(room):
      output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
      output('The sun is deeply offended and goes away. It is dark now.')
      room.render()

    def clearingBack(room):
      output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
      intro.render()

    clearing = Room(
      '''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
      ''',
      [],
      [('1','Pick the flower',clearingFlower)
      ,('2','Go towards the harp',clearingHarp)
      ,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
      ,('4','Go back',clearingBack)
      ]
    )

    introstrt.render()
except:
  tb.print_exc()
finally:
  input('#')

Upvotes: 1

Related Questions