3 Replies - 363 Views - Last Post: 18 April 2013 - 02:40 AM Rate Topic: -----

#1 little_fatty  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 22-March 13

Implementing an inventory in my text-based lab rat rpg

Posted 17 April 2013 - 11:01 PM

Hey yall,

I got a lot of help last time I was here, and I've found myself lost yet again. First off here is my code:

import textwrap

def show_description(d):
	print textwrap.fill(d)

def scene_opening(state):
	show_description("You are a rat, a rat that life dealt an interesting hand to. What you do with that hand is up to you. Unfortunately, you know nothing beyond your cold stainless steel cage. Fortunately, you were in the delightful position to be part of an experiment that taught rats how to read. Due to a careless mistake on the part of 'Hairless Ones' an adventure awaits. WILL YOU BE THE CHOSEN ONE?! The door to your cage has been left open.")
	select_path(state, [
		(scene_stay, "wait for the careless 'Hairless One' to return and right the wrong."),
		(scene_first_step, 'eagerly seize the opportunity, taking your first step into the world.')
		])

def scene_wait_more(state):
	show_description("You aren't much of a daring soul, you decide not to check things out. It  doesn't sound like whoever is out there is having that much fun anyway. You have everything you need right here, there is no need to leave the place that has taken such good care of you since you were young. You occupy your mind with your plans for tomorrow. Suddenly, the lights flicker and go out. Looks like the 'Hairless One' should be called the 'Careless One' right? It was a stupid joke, but you laugh at yourself anyway. It can't hurt to have a little peek outside can it? Plus the cage doesn't seem as safe with the door wide open.")
	select_path(state, [
		(scene_skeptical, 'cautiously take your first steps into the world.'), 
		(scene_call_out, 'you call out into the dark to find out if anyone can hear you.'), 
		(scene_close_cage, 'decide to try to close the door yourself.')
		])

def scene_first_step(state):
	show_description("You trip running out of your cage. You have been waiting for the day to get out of that awful cage your entire life.  Your ankle hurts, but you seem to be able to shrug it off. You hear a shrieking howl that you've often heard at night, but this time is differnt, you aren't behind the safety of your bars. A shiver runs down your spine.")
	show_description("You have sprained your ankle. You take damage!")
	doDamage(state, 2)
	if not isDone(state):
		select_path(state, [
			(scene_wait_more, 'quickly jump back into your cage.'),
			(scene_be_brave, 'face your fears.')
			])

def scene_stay(state):
	show_description("You've noticed some patterns in the time you've been here, it should be back one last time before the world goes dark. You hear a familiar howl, a creature in pain. You've heard it many times, it almost slips past you.")
	select_path(state, [
		(scene_wait_more, 'continue to wait.'), 
		(scene_slow_first_steps, 'finally decide to investigate the world.')
		])

def scene_be_brave(state):
	show_description("You puff out your chest as the lights begin to flicker and go out. You can't see anything quite yet, but there is no way in hell you are going back in that cage. This might be your only chance to see the world for what it is. As the great Abraham Lincoln said 'Bitch, I ain't scared a shit!' you read that somewhere.")
	select_path(state, [
                (scene_call_out, 'call out to find out if anyone can hear you.'),
                (scene_eyes_adjust, 'wait for your eyes to adjust to the dark.'),
                (scene_climb_blind, 'waste no more time, and start to climb down to the floor.')
                ])

def scene_slow_first_steps(state):
	show_description("You slowly step out of the cage, you are fascinated by the sound you keep hearing. What could it be? Could the animal be in trouble? Could it be evil? Your mind continues to race as you step out of the cage. The lights in the room begin to flicker, and finally turn of. 'Things aren't so scary out here afterall' you think as a stream of urine runs down your leg.")
	select_path(state, [
                (scene_call_out, 'call out into the darkness to find out if anyone can hear you.'),
                (scene_eyes_adjust, 'wait for your eyes to adjust to the dark.'),
                (scene_close_cage, 'run back into the cage, and try to close it by yourself.'),
                (scene_climb_blind, 'waste no more time, and start to climb down to the floor.')
                ])

def scene_call_out(state):
	show_description("Your voice echoes off the walls in the dark room... its quiet. You hear rustling coming from some cages across the room.  You call out once more, 'Is anyone there? Answer me!' Nothing. Your curiousity has peaked, there is really only one more thing to do. It is time for you to make the plunge to the world below... the ground!")
	select_path(state, [
                (scene_skeptical, 'decide to climb down.'),
                ])
	
def scene_eyes_adjust(state):
        show_description("As some time passes the world slowly starts to become more visible.  The black fades to grey, and your field of view has increased. Your patience has paid off, whoever it was that stated it was a virtue would be proud.")
        select_path(state, [
                (scene_call_out, 'call out into the room to find out if anyone can hear you.'),
                (scene_skeptical, 'decide to safely climb down to the floor below.')
                ])

def scene_climb_blind(state):
	show_description("Unfortunately, being a caged rat, you never really learned the art of climbing. Add darkness to the equation, its a recipe for disaster. You finally realize this about a quarter of the way down your cage, as you begin to lose your footing. 'Well... I guess I'm dead.' You think as you begin to fall. Luckily for you, rats are a sturdy people. Embarrassed, you scan the area. Your cage is located in a small room, there is a large door at the far end of the room. The door appears to be open and there is a faint light flickering from the hallway. To the right of the door against the wall there lies a table with three more cages on it.")
	show_description("You have smashed your face. You take damage!")
	doDamage(state, 15)
	if not isDone(state):
		select_path(state, [
			(scene_first_hallway, 'go towards the light in the hallway.'),
			(scene_three_cages, 'get a closer look at the three cages.')
			])

def scene_close_cage(state):
	show_description("You swing the door to your cage shut. You push ever so gingerly on it, and it swings back open. Christ, It's literally like someone is making you go on an adventure. You examine the locking mechanism on the cage, it looks like you'll need a key if you want to close it. Do cages like this even exist? Seriously, a higher power must exist.")
	select_path(state, [
                (scene_call_out, 'call into the room to find out if anyone can hear you.'),
                (scene_skeptical, 'give into the powers at be, and start to climb to the damn floor already!')
                ])

def scene_skeptical(state):
	show_description("Your eyes are well adjusted to the dark. You steadily make your way down the floor below you. Your cage is located in a small room, there is a large door at the far end of the room. The door appears to be open and there is a faint light flickering from the hallway. To the right of the door against the wall there lies a table with three more cages on it.")
	select_path(state, [
                (scene_first_hallway, 'go towards the light in the hallway.'),
                (scene_three_cages, 'get a closer look at the three cages.')
                ])

def scene_first_hallway(state):
	show_description("this is a test")
        if add_screw == True:
                        select_path(state, [
                                (scene_test_one, 'test number one.'),
                                (scene_test_two, 'test number two.')
                                ])
        if add_screw != True:
                        select_path(state, [
                                (scene_test_one, 'test number one.')
                                ])
def scene_three_cages(state):
	show_description("The three cages are sloppily stacked on top of each other. As you approach a foul smell becomes more obvious. You are unsure how you never noticed it before you left your cage. You wonder how long the cages have been there.")
	select_path(state, [
                (scene_bottom_cage, 'investigate the bottom cage.'),
                (scene_your_room, 'step away from the cages.')
                ])

def scene_bottom_cage(state):
	show_description("The cage appears to have a large padlock on it. You peer between the bars of the cage. Your whiskers brush against the stainless steel. Your eyes focus as you begin to make out a lump of damp fur. The stench is almost unbearable, it must be dead. The body appears to be within paws reach.")
	select_path(state, [
                (scene_touch_body, 'decide to touch the body.'),
                (scene_your_room, 'step away from the cages.'),
                (scene_middle_cage, 'decide to climb to the middle cage.')
                ])
	
def scene_your_room(state):
	show_description("You are in your room, your cage is at the far end. There is an open door that leads to a hallway, next to the door are three sloppily stacked cages on a table. A whole room for one rat?")
	select_path(state, [
                (scene_first_hallway, 'go through the door towards the light in the hallway.'),
                (scene_three_cages, 'get a closer look at the three cages.')
                ])

def scene_touch_body(state):
	show_description("You slowly reach out, your paws are sweaty, knees weak, mom's spaghetti. Your fingers touch the fur, it's soaked in blood. Upon further inspection, a large whole in it's chest becomes more apparent. 'I think its dead.' You whisper aloud. 'What could have caused this?' If anything you learned from reading it was probably spiders, spiders are the worst.")
	select_path(state, [
                (scene_your_room, 'step away from the cages.'),
                (scene_middle_cage, 'decide to climb to the middle cage.')
                ])

def scene_middle_cage(state):
	show_description("You carefully climb the bars until you reach the second cage. The cage is bloody and covered in fur and stank. There is a noticeable body in the cage, but it is too far to reach.")
	select_path(state, [
                (scene_top_cage, 'decide to climb up to the top cage.'),
                (scene_your_room, 'climb to the floor.'),
                (scene_bottom_cage, 'decide to climb back to the bottom cage.')
                ])

def scene_top_cage(state):
	show_description("As you reach the top cage you notice the door is open...")
	select_path(state, [
                (scene_in_top_cage, 'walk into the cage.'),
                (scene_middle_cage, 'decide to climb down to the middle cage.'),
                (scene_your_room, 'get the hell off of the cages.')
                ])

def scene_in_top_cage(state):
	show_description("The cage is empy, you take a moment to look around. There is a rusty screw that looks lose. You can attempt to take it out to carry it with you, as it might be nice to use as protection. However, since you will have to use one hand to hold it it might be more trouble than it is worth concerning running and climbing.")
	select_path(state, [
                (scene_take_screw, 'take the screw.'),
                (scene_your_room, 'decide to leave and climb back down to the floor.')
                ])

def scene_take_screw(state):
	show_description("You grasp the screw with two hands and slowly start to turn. 'Righty tighty, lefty loosey' you think to yourself. It squeeks as you turn it, you pull it out and swing it through the air a few times. 'Sick!'")
        add_screw(state)
	select_path(state, [
                (scene_your_room, 'climb back down to the floor.')
                ])

def scene_test_one(state):
	scene_coming_soom(state)

def scene_test_two(state):
	scene_coming_soom(state)

def scene_coming_soom(state):
	show_description("Coming soon")
	state['scene'] = scene_quit

def scene_quit(state):
	state['done'] = True
	print "Good bye!"


def get_int(prompt):
	n = None
	while n==None:
		try:
			choice = raw_input(prompt)
			n = int(choice)
		except:
			print choice, "is not a valid selection!"
	return n

def select_path(state, paths):
	for i, (jump, phrase) in enumerate(paths):
		print "\t", (i+1), phrase
	print "\t(0 Quit)"
	menu_selection = get_int("Make a selection (0 - %i): " % len(paths))
	if menu_selection==0:
		state['scene'] = scene_quit
	elif menu_selection>0 and menu_selection<=len(paths):
		(jump, phrase) = paths[menu_selection-1]
		print "You ", phrase
		state['scene'] = jump
	else:
		print menu_selection, "is not a valid selection!"


def doDamage(state, hp):
	state['health'] -= hp
	if isAlive(state):
		showHealth(state)
		return True
	else:
		print "You have died."
		state['done'] = True
		return False

def isAlive(state):
	return state['health'] > 0
	
def isDone(state):
	return state['done']

def showHealth(state):
	print "HP ", state['health'], "/100"

def add_screw(state):
        return True 

def play(state):
	while not isDone(state):
		showHealth(state)
		state['scene'](state)

play({'health': 100, 'scene': scene_opening, 'done': False })


So if you try running it, you will get an indention error. I can't figure out for the life of me why this keeps happening.

So here is what I am trying to implement into the game. in scene_in_top_cage (lines 148-153) you get the option to move on to scene_take_screw (lines 155 - 160) In this scene I want to add the players first possible inventory item, a screw. In lines 221-222 I attempt to tell python that add_screw should be True when scene_take_screw is chosen.

I'm using scene_first_hallway (lines 92 - 102) as a testing field for the screw. If the player takes the screw I want the game to respond with two possible choices. If it is not taken, I want the game to respond with only one option. However, I keep getting an indention error so I am not sure if I am even close.

So can you guys tell me, am I even close?

Is This A Good Question/Topic? 0
  • +

Replies To: Implementing an inventory in my text-based lab rat rpg

#2 Mekire  Icon User is offline

  • D.I.C Head

Reputation: 116
  • View blog
  • Posts: 212
  • Joined: 11-January 13

Re: Implementing an inventory in my text-based lab rat rpg

Posted 17 April 2013 - 11:23 PM

Well it is very good to see that you are using functions and don't have global variables. The answer to this question though is (as it almost always is with people making games of this type) that it is time to learn classes. Classes will let you create an object with its own namespace, attributes, and methods so that you can keep track of these things in a much easier (and more maintainable way).

Here is a (very trivial) example:
class Rat:
    def __init__(self,health,inventory=None):
        self.health = health
        if not inventory:
            self.inventory = []
        else:
            self.inventory = inventory
    def get_item(self,item):
        self.inventory.append(item)

if __name__ == "__main__":
    MyRat = Rat(100,["cheese"])
    print(MyRat.health)
    print(MyRat.inventory)
    MyRat.get_item("screw")
    print(MyRat.inventory)

Of course, fully converting your entire program to an object oriented paradigm would take a bit of work, but if you are comfortable with writing functions, this is the next step on your journey.

-Mek

Note:
Your indentation error makes me think you are using IDLE as most IDEs will still let you run in this case. The problem is that you have mixed tabs and spaces. If you are using IDLE you can detabify everything. Press ctrl+a to select all; then go to format and select detabify region. After doing this you will have to fix a bit of spacing, but after that everything should be fine.

Or just cut/paste this:
Spoiler

This post has been edited by Mekire: 17 April 2013 - 11:36 PM

Was This Post Helpful? 1
  • +
  • -

#3 Mekire  Icon User is offline

  • D.I.C Head

Reputation: 116
  • View blog
  • Posts: 212
  • Joined: 11-January 13

Re: Implementing an inventory in my text-based lab rat rpg

Posted 18 April 2013 - 12:00 AM

As for the way you are trying to implement the inventory. You almost have the right idea, but not quite.

The function add_screw doesn't do anything the way you call it. If you are not quite ready to take the plunge into classes just yet, the next best thing would be to give your state dictionary an inventory key.
play({'health': 100, 'scene': scene_opening,'inventory': [], 'done': False })
Then when you get an item append it to that list:
state['inventory'].append("screw")


Now when you want to check your inventory:
if "screw" in state["inventory"]:
    #do something
else:
    #do something else

-Mek
Was This Post Helpful? 0
  • +
  • -

#4 little_fatty  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 22-March 13

Re: Implementing an inventory in my text-based lab rat rpg

Posted 18 April 2013 - 02:40 AM

Not quite ready to plunge into classes, maybe on my second game. So I fit the code from your second post in, and it works well. Thanks a bunch!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1