This is probably a trivial overlook, just starting out with python - python

I made a short text adventure for my human phys class about the liver.
link: http://pastebin.com/QYkn5VuU
#SUPER LIVER ADVENTURE 12!
from sys import exit
from random import randint
quips = ["Welcome!",
"have a wonderful day",
"Livers are cool!",
"this text was chosen at random",
"Writen in python",
"woo, splash text!",
"Notch loves ez!",
"Almost dragon free!"]
print quips [randint (0, len(quips) -1)]
def first_thing () :
print "You are a liver, congratulations! You should do some liver stuff now."
print "Here comes some blood, what should you do?"
filterblood = raw_input (">")
if filterblood == "filter" or "filter blood" or "filter the blood":
return 'second_thing'
elif filterblood == "who cares":
print "I care, be more considorate!"
return "first_thing"
else:
print "Sorry, no (Hint, it is your main purpose!)"
return "first_thing"
def second_thing () :
print "You are now filtering the blood, good for you!"
print "oh no! There is too much aldosterone! what would that do?"
fluidz = raw_input (">")
if fluidz == "fluid retension" or "Keeping fluids":
return 'third_thing'
else:
print "nope! (hint, what does aldosterone do?)"
return "second_thing"
def third_thing () :
print "Oh no!, that's bad!"
print "What should you do about that aldosterone?"
metabolize = raw_input (">")
if metabolize == "metabolize" :
return 'fourth_thing'
else:
print "BRZZZZ, wrong!"
return "third_thing"
def fourth_thing () :
print "super duper!"
print "the aldosterone has been taken care of, no problems at the current moment"
print "..."
print "..."
print "..."
print "After a couple of months a problem arises, you are inflamed, what could this be?"
hepatitis = raw_input (">")
if hepatitis == "hepatitis":
return 'fifth_thing'
else:
return "fourth_thing"
def fifth_thing () :
print "OH NO! Hepatitis!"
print "What could have caused this?"
idunno_somthing = raw_input (">")
if idunno_somthing == "infection" or "an infection" :
print "neat, thats no good."
print "thank you for coming"
exit (0)
elif idunno_somthing == "sex" or "drugs" or "rock n roll":
print "very funny, what specificly caused it?"
return "fifth_thing"
else:
return "fifth_thing"
ROOMS = {
'first_thing': first_thing,
'second_thing': second_thing,
'third_thing': third_thing,
'fourth_thing': fourth_thing,
'fifth_thing': fifth_thing
}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n--------"
next = room()
runner(ROOMS, 'first_thing')
#if you steal my stuff, credit me.
I had to type in hepatitis twice (lines 66 and 67)and none of the elif's worked.
edit: What am I missing?
This is probably a really stupid question, I'm just starting out. We were all beginners at once.

Your elif statement on line 82 reads:
elif idunno_something == "sex" or "drugs" or "rock n roll":
this should be
elif idunno_something in ("sex", "drugs", "rock n roll"):
The same sort of change should help on lines 22, 38 and 77.

For fun, I completely fixed up your program.
#!/usr/bin/python
# SUPER LIVER ADVENTURE 12!
# If you steal my stuff, credit me.
# Owen Sanders on StackOverflow
#
# Updated December 5, 2011
# OregonTrail on StackOverflow
from sys import exit
from random import randint
quips = [
"Welcome!",
"have a wonderful day",
"Livers are cool!",
"this text was chosen at random",
"Writen in python",
"woo, splash text!",
"Notch loves ez!",
"Almost dragon free!"
]
print quips[randint(0, len(quips)-1)]
def first_thing():
print ("You are a liver, congratulations! "
"You should do some liver stuff now.")
print "Here comes some blood, what should you do?"
filterblood = raw_input ("> ")
if filterblood in ("filter", "filter blood", "filter the blood"):
return 'second_thing'
elif filterblood == "who cares":
print "I care, be more considorate!"
return "first_thing"
else:
print "Sorry, no (Hint, it is your main purpose!)"
return "first_thing"
def second_thing():
print "You are now filtering the blood, good for you!"
print "oh no! There is too much aldosterone! what would that do?"
fluidz = raw_input ("> ")
if fluidz in ("retain fluid", "fluid retention", "keep fluids",
"keep fluid"):
return 'third_thing'
else:
print "nope! (hint, what does aldosterone do?)"
return "second_thing"
def third_thing():
print "Oh no!, that's bad!"
print "What should you do about that aldosterone?"
metabolize = raw_input ("> ")
if metabolize == "metabolize":
return 'fourth_thing'
else:
print "BRZZZZ, wrong!"
return "third_thing"
def fourth_thing():
print "super duper!"
print ("the aldosterone has been taken care of, no problems at the "
"current moment")
print "..."
print "..."
print "..."
print ("After a couple of months a problem arises, you are inflamed, "
"what could this be?")
hepatitis = raw_input ("> ")
if hepatitis == "hepatitis":
return 'fifth_thing'
else:
return "fourth_thing"
def fifth_thing():
print "OH NO! Hepatitis!"
print "What could have caused this?"
idunno_somthing = raw_input ("> ")
if idunno_somthing in ("infection", "an infection"):
print "neat, thats no good."
print "thank you for coming"
exit (0)
elif idunno_somthing in ("sex", "drugs", "rock n roll"):
print "very funny, what specificly caused it?"
return "fifth_thing"
else:
return "fifth_thing"
ROOMS = {
'first_thing': first_thing,
'second_thing': second_thing,
'third_thing': third_thing,
'fourth_thing': fourth_thing,
'fifth_thing': fifth_thing
}
def runner(rooms, start):
nextRoom = start
while True:
room = rooms[nextRoom]
print "--------"
nextRoom = room()
runner(ROOMS, 'first_thing')

Since you are a beginner, I will start with some suggestions on asking for help. Ideally, you want to provide the smallest amount of code as possible that shows the problem that you are having. Explain what you expect to happen, and what does actually happen when you execute the code that you have presented.
When you want to check if a string is multiple values, you put the possible values in a list or tuple.
if filterblood in ["filter", "filter blood", "filter the blood"]:
In the case of the example above you may want to accept all answers that start with "filter":
if filterblood.startswith("filter"):

Related

Simple Text-based game using classes. Trying to create a basic loop for if has a particular item in the inventory. Then open the door

My problem actually occurs in LockedRoom():
The error python throws is:
Traceback (most recent call last):
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 479, in <module>
a_game.play()
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 33, in play
next_scene_name = current_scene.enter()
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 147, in enter
has_key = "key" in Person.items
AttributeError: class Person has no attribute 'items'
So, I believe the problem is to do with checking for, or putting "Key" in the
person's items. I then want to check this list to see if the warrior is carrying it. If he is, then he should be able to open the door. If not, then the door should remain closed. I need to repeat this again at the end for TowerRoom. In that case, I need to check for up to 3 different items. I have attached the code. Hopefully, the error is a very simple one.
from sys import exit
from random import randint
key = False
brick = False
candle = False
Cup = False
class Scene(object):
def enter(self):
print "This scene is not yet configured."
exit(1)
class Person:
def __init__(self, name):
self.name = name
self.items = []
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
current_scene.enter()
class Death(Scene):
quips =[
"You really suck at this.",
"Why don't you try a little harder next time.",
"Well... that was a very stupid thing to do.",
"I have a small puppy that's better at this than you.",
"why don't you just give up now.",
"Please, stop killing me!",
"Your mom would be proud of you... if she were smarter."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(0)
class MainGate(Scene):
def enter(self):
print "Welcome to Luke's first Text based game."
print "It currently has no name, nor will it ever have one."
print "Because it kind of sucks a little bit."
print"----------------------------------------"
print "Evil Dr. Onion has stollen the Mushroom Kingdoms princess"
print "You have chased him down for months through rain, snow"
print "and desserts. You have finally tracked him down."
print "In front of you is a huge castle. You go through the giant"
print "entrance to begin your search for the princess. Nobody"
print "know what may await you ahead."
print "Do you want to enter the Castle?"
print "1. Yes"
print "2. No"
action = raw_input(">")
if action == '1':
return 'central_corridor'
elif action == '2':
print "What? You are leaving and giving up on the princess"
print "already? God will certainly smite you for this!!!"
return 'death'
else:
print "Please choose an action numerically using the numpad"
print "on your computer."
return 'MainGate'
class CentralCorridor(Scene):
def enter(self):
print "You enter the castle. In fron of you stands a giant onion"
print "monster. It looks at you with its big, bulging eye. Your"
print "own eyes begin to weep as you look at this... thing."
print "The giant onion monster begins to charge at you, waving its"
print "sword over what I suppose would be its head."
print "what do you do?"
print "1. Try and fight the giant onion with your sword."
print "2. Try and dodge out of the way of the onion and run past it."
print "3. Throw something at the onion."
print "4. Stand there and scream at the onion."
action = raw_input(">")
if action == '1':
print "You take your sword out of its sheath. Waiting for the onion"
print "to reach you so that you can stab it in its giant eye."
print "however as it gets closer its stench gets worse and worse."
print "It gets so bad that you can hardly see!"
print "You try and swing at the onion, and miss!"
print "You feel a stabbing pain in your right shoulder"
print "and then everything goes black."
return 'death'
elif action == '2':
print "As the onion charges you, you jump out of the way."
print "However, the giant onion is much quicker than you expected."
print "You look down to see a sword protruding from your stomach."
print "You scream in pain and die."
return 'death'
elif action == '3':
print "You look in your pockets to find something to throw at"
print "the onion."
print "You find a rubber duck and throw it at the onion. Unfortunately, it"
print "does nothing but distracts the onion from you for a few"
print "short seconds. After it focuses its attention back on you,"
print "it eats your face off."
return 'death'
elif action == '4':
print "You choose to stand and scream at the onion at the highest"
print "pitch your girly little voice will allow."
print "The onion, hearing your scream, is terrified. It turns"
print "around and rolls away as quickly as its little legs and can"
print "carry it. You quickly catch up with it and cut its little"
print "legs right off, before hurrying to the next room."
return 'locked_room'
else:
print "please choose an appropriate action dear sir. Otherwise,"
print "you will never be able to rescue the princess."
return 'central_corridor'
class LockedRoom(Scene):
def enter(self):
print "You are standing in a room with just a door in front of you."
print "What do you do?"
print "1. Try and open the door."
has_key = "key" in Person.items
if not has_key: print "2. pick up the key"
action = raw_input(">")
if (action == '1' and has_key):
print "You unlock and open the door."
return 'monty_hall_room'
elif (action == '1' and not has_key):
print "the door will not budge"
return 'locked_room'
elif (action == '2' and not has_key):
print "you picked up the key."
Person.items.append("key")
return 'locked_room'
else:
print "Please enter a numeric value as something to do."
print "Otherwise we might be here all day."
return 'locked_room'
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'main_gate': MainGate(),
'central_corridor': CentralCorridor(),
'locked_room': LockedRoom(),
'monty_hall_room': MontyHallRoom(),
'pickel_room': PickleRoom(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
warrior = Person("Soldat")
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
I just need a way to use a class 'list' and put things in and out of it in the other classes. Then, use whatever is contained in that list to open a door or slay a monster.
Any help anyone could provide would be greatly appreciatd.
You need create a "person" instance (you already did this), instead of using the class:
warrior = Person.new("penne12")
Or use the one you created
Then you can use your "warrior":
warrior.name #=> "penne12"
warrior.items #=> []
This is because the class itself doesn't store the name or items, the instance of the class (created when you do Person.new) contains the item array and the name. Trying to get the attributes of the class won't work.
Further reading

Why does this one chunk of code come up with error but the other one doesn't?

I have two sections of Python code - one works and the other one comes up with an error. What rule makes this the case?
Here is the chunk of code that got the error, along with the error:
Code:
elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
print "Now what will you do with the jello?"
print "1. Eat it."
print "2. Take it out and load it in a gun."
print "3 Nothing."
jello = raw_input("> ")
if jello == "1" or jello == "2":
print "Your mind is powered by it remember? Now you are dead!"
elif jello == "3":
print "Smart move. You will survive."
else:
print "Do something!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
I got this error message in prompt:
File "ex31.py", line 29
print "Now what will you do with the jello?"
^
IndentationError: unindent does not match any outer indentation level
BUT when my code is like this:
elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
print "Now what will you do with the jello?"
print "1. Eat it."
print "2. Take it out and load it in a gun."
print "3 Nothing."
jello = raw_input("> ")
if jello == "1" or jello == "2":
print "Your mind is powered by it remember? Now you are dead!"
elif jello == "3":
print "Smart move. You will survive."
else:
print "Do something!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
I get no error message.
Basically my question is - why do I not get an error message if I indent the line
print "Now what will you do with the jello?"
...and the rest of the block of code below it.
But I get an error code if I leave it with the same indentation as the line above it?
Does this mean that the print line after an if statement can only be one line in total, with no other print lines allowed to be linked to the output of the if statement above the first print line of that block?
Thanks.
I suspect you're mixing spaces and tabs. It's best to use only spaces so that your visual indentation matches the logical indentation.
Examining your source code, there's a tab character in the second line here:
if insanity == "1" or insanity == "2":
\t print "Your body survives powered by a mind of jello. Good job!"
print "Now what will you do with the jello?"
I've marked it with \t, which makes the mixed up indentation stick out.
Have you checked that your indentation is consistent? Are you using 4 spaces everywhere (not tabs)? I cut and paste your code from your first example(starting from the insanity raw input) and it ran fine on my machine.
You're not indenting after the elif at the top of this code:
elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
Have you tried:
elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
and see what happens?
Off on a tangent:
As you are already finding out, trying to do a story of any size with cascading if-else clauses very quickly becomes unwieldy.
Here is a quick state-machine implementation that makes it easy to write a story room-by-room:
# assumes Python 3.x:
def get_int(prompt, lo=None, hi=None):
"""
Prompt user to enter an integer and return the value.
If lo is specified, value must be >= lo
If hi is specified, value must be <= hi
"""
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
pass
class State:
def __init__(self, name, description, choices=None, results=None):
self.name = name
self.description = description
self.choices = choices or tuple()
self.results = results or tuple()
def run(self):
# print room description
print(self.description)
if self.choices:
# display options
for i,choice in enumerate(self.choices):
print("{}. {}".format(i+1, choice))
# get user's response
i = get_int("> ", 1, len(self.choices)) - 1
# return the corresponding result
return self.results[i] # next state name
class StateMachine:
def __init__(self):
self.states = {}
def add(self, *args):
state = State(*args)
self.states[state.name] = state
def run(self, entry_state_name):
name = entry_state_name
while name:
name = self.states[name].run()
and your story rewritten to use it
story = StateMachine()
story.add(
"doors",
"You are standing in a stuffy room with 3 doors.",
("door 1", "door 2", "door 3" ),
("wolves", "cthulhu", "treasury")
)
story.add(
"cthulhu",
"You stare into the endless abyss at Cthulhu's retina.",
("blueberries", "yellow jacket clothespins", "understanding revolvers yelling melodies"),
("jello", "jello", "muck")
)
story.add(
"muck",
"The insanity rots your eyes into a pool of muck. Good job!"
)
story.add(
"jello",
"Your body survives, powered by a mind of jello. Good job!\nNow, what will you do with the jello?",
("eat it", "load it into your gun", "nothing"),
("no_brain", "no_brain", "survive")
)
story.add(
"no_brain",
"With no brain, your body shuts down; you stop breathing and are soon dead."
)
story.add(
"survive",
"Smart move, droolio!"
)
if __name__ == "__main__":
story.run("doors")
For debugging, I added a method to StateMachine which uses pydot to print a nicely formatted state graph,
# belongs to class StateMachine
def _state_graph(self, png_name):
# requires pydot and Graphviz
from pydot import Dot, Edge, Node
from collections import defaultdict
# create graph
graph = Dot()
graph.set_node_defaults(
fixedsize = "shape",
width = 0.8,
height = 0.8,
shape = "circle",
style = "solid"
)
# create nodes for known States
for name in sorted(self.states):
graph.add_node(Node(name))
# add unique edges;
ins = defaultdict(int)
outs = defaultdict(int)
for name,state in self.states.items():
# get unique transitions
for res_name in set(state.results):
# add each unique edge
graph.add_edge(Edge(name, res_name))
# keep count of in and out edges
ins[res_name] += 1
outs[name] += 1
# adjust formatting on nodes having no in or out edges
for name in self.states:
node = graph.get_node(name)[0]
i = ins[name]
o = outs.get(name, 0)
if not (i or o):
# stranded node, no connections
node.set_shape("octagon")
node.set_color("crimson")
elif not i:
# starting node
node.set_shape("invtriangle")
node.set_color("forestgreen")
elif not o:
# ending node
node.set_shape("square")
node.set_color("goldenrod4")
# adjust formatting of undefined States
graph.get_node("node")[0].set_style("dashed")
for name in self.states:
graph.get_node(name)[0].set_style("solid")
graph.write_png(png_name)
and calling it like story._state_graph("test.png") results in
I hope you find it interesting and useful.
Things to think about next:
room inventory: things you can pick up
player inventory: things you can use or drop
optional choices: you can only unlock the red door if you have the red key in inventory
modifiable rooms: if you enter the secluded grove and set it on fire, it should be a charred grove when you return later

Making an RPG in Python

The code gets stuck within the yes_or_no function right after the user input. No error message, please help! As you can see all I am trying to do is effectuate a simple purchase, I haven't been able to test the buy_something function, and I'm aware that it may have issues.
#!/usr/bin/env python
import time
# Intro
print "Input Name:"
time.sleep(1)
name = raw_input()
print "Welcome to Tittyland brave %s'" %(name)
time.sleep(2)
print "You are given nothing but 500 gold to start you journey..."
time.sleep(2)
print "Good luck..."
time.sleep(3)
print "Shopkeeper: 'Eh there stranger! Looks like you'll need some gear before going into the wild! Check out my store!'"
time.sleep(4)
print ""
#Inventory and first shop
inventory = {
'pocket' : [],
'backpack' : [],
'gold' : 500,
}
shop = {
'dagger' : 50,
'leather armor' : 150,
'broadsword' : 200,
'health potion' : 75,
}
#Buying items
for key in shop:
print key
print "price: %s" % shop[key]
print ""
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input()
def buying_something(x):
for i in shop:
if shop[i] == x:
inventory[gold] -= shop[i]
inventory[backpack].append(shop[i])
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"
yes_or_no(answer1)
I fixed both your functions. You had your raw_inputs at the wrong place:
def yes_or_no(purchase_q):
if purchase_q == "yes":
while True:
things = raw_input("Great. What is your hearts desire(type no more to exit shop): ")
if things != "no more":
buying_something(things)
else:
print "Good luck on your journey then"
break
def buying_something(item):
if item in shop.keys():
print "You have %s gold available" %(inventory.get('gold'))
print "Item Added {0}: ".format(item)
backpack_items = inventory.get('backpack')
backpack_items.append(item)
item_cost = shop.get(item)
print "Cost of Item is %s gold coins " %(item_cost)
inventory['gold'] = shop.get(item) - item_cost
What happens is that after this line:
print "Shopkeeper: So, you interested in anything?"
you wait for raw input with this answer1 = raw_input()
Then immediately after you type yes or no, you wait for input again item = raw_input()
Tt's not getting stuck or anything, it's just doing as it's told.
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input() // <-- This is in the wrong place
yes_or_no(answer1)
What you've written requires the user to type in the item they want after the yes or no answer, and regardless of a yes or no. I suggest you move the item = raw_input() into your yes_or_no function.
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
item = raw_input()
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"

Use of lists for collecting items

I'm currently going through the book "Learning Python The Hard Way", and I'm trying to make a simple game. In this game, I want to be able to pick up at item "Flashlight" in one room, to be able to get into another room. I can, however, not make it work :-(
So the question is, how do I carry the same list through several functions, and how do I put things in it? I want to be able to put multiple things in it.
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
Hope you can help me out, thanks :-)
Code:
def start(bag):
print "You have entered a dark room"
print "You can only see one door"
print "Do you want to enter?"
answer = raw_input(">")
if answer == "yes":
light_room(bag)
elif answer == "no":
print "You descidede to go home and cry!"
exit()
else:
dead("That is not how we play!")
def light_room(bag):
print "WOW, this room is amazing! You see magazines, cans of ass and a flashlight"
print "What do you pick up?"
print "1. Magazine"
print "2. Cans of ass"
print "3. Flashlight"
pick(bag)
def pick(bag):
pick = raw_input(">")
if int(pick) == 1:
bag.append("Magazine")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 2:
bag.append("Can of ass")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 3:
bag.append("Flashlight")
print "Your bag now contains: \n %r \n" % bag
else:
print "You are dead!"
exit()
def start_bag(bag):
if "flashlight" in bag:
print "You have entered a dark room"
print "But your flashlight allows you to see a secret door"
print "Do you want to enter the 'secret' door og the 'same' door as before?"
answer = raw_input(">")
if answer == "secret":
secret_room()
elif answer == "same":
dead("A rock hit your face!")
else:
print "Just doing your own thing! You got lost and died!"
exit()
else:
start(bag)
def secret_room():
print "Exciting!"
exit()
def dead(why):
print why, "You suck!"
exit()
bag = []
start(bag)
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
The problem here is that in this line:
def pick(bag):
pick = raw_input(">")
you bind pick to a new value (a str) so it doesn't reference a function anymore. Change that to something like:
def pick(bag):
picked = raw_input(">")

Getting two class game to interact

So I know this site gets far too many questions about Zed Shaw's Learn Python the Hard Way, but I'm going through ex42., extra credit #3, has got me hung up.
I am having trouble getting the class Engine to effectively start and transition into the class Map where the game can begin going through the different functions that I have defined
the code is as follows:
from sys import exit
from random import randint
class Map(object):
def death():
print quips[randint (0, len(quips)-1)]
exit(1)
def princess_lives_here():
print "You see a beautiful Princess with a shiny crown."
print "She offers you some cake."
eat_it = raw_input(">")
if eat_it == "eat it":
print "You explode like a pinata full of frogs."
print "The Princess cackles and eats the frogs. Yum!"
return 'death'
elif eat_it == "do not eat it":
print "She throws the cake at you and it cuts off your head."
print "The last thing you see is her munching on your face. Yum!"
return 'death'
elif eat_it == "make her eat it":
print "The Princess screams as you cram the cake in her mouth."
print "Then she smiles and cries and thank you for saving her."
print "She points to a tiny door and says, 'The Koi needs cake too.'"
print "She gives you the very last bit of cake and shoves you in."
return 'gold_koi_pond'
else:
print "The Princess looks at you confused and just points at the cake."
return 'princess_lives_here'
class Engine(Map):
def _init_(self, start):
self.quips = [
"You died. You suck at this.",
"Your mom would be proud, if she were smarter",
"Such a luser.",
"I have a small puppy that's better at this."
]
self.start = start
def play(self):
next = self.start
while True:
print "\n-----"
room = getattr(self, next)
next = room()
e = "princess_lives_here".Map.Engine
e.play()
Now the issue is not with the other functions within Map class but making the transition from the class Engine to class Map so the game can continue. It is either not defining 'Map' within the class Engine or in the variable i am setting up at the end and trying to run with the play() command.
Any other links you can point me to in regards to class interaction would be great. thnx again
There's a lot wrong here.
Your code as shown is illegally indented; it looks like __init__() and play() should be indented to be members of class Engine, and death() and princess_lives_here() indented into Map.
The __init__ of a class needs double underscores, not single, on each end.
The line:
e = "princess_lives_here".Map.Engine
is nonsensical python; it starts by trying to find a "Map" attribute in a string. If you want to instance a new object of a class, you'd say
e = Engine( "princess_lives_here" ) # or Map( "...")?
It's unclear to me what you need both Map and Engine for, but I'm guessing you either want Map to be a subclass of Engine (Engine is generic to all games and Map is specific to this game) or you want them to be separate objects, where an Engine and a Map refer back to each other.
As it stands you have Engine as a subclass of Map. If they're supposed to be separate, declare Engine as an object, have its __init__ take both a starting point and a map instance, and do
m = Map()
e = Engine( m, "princess_lives_here" )
from sys import exit
from random import randint
class Map(object):
def __init__(self):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def death(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
def princess_lives_here(self):
print "You see a beautiful Princess with a shiny crown."
print "She offers you some cake."
eat_it = raw_input("> ")
if eat_it == "eat it":
print "You explode like a pinata full of frogs."
print "The Princess cackles and eats the frogs. Yum!"
return 'death'
elif eat_it == "do not eat it":
print "She throws the cake at you and it cuts off your head."
print "The last thing you see is her munching on your torso. Yum!"
return 'death'
elif eat_it == "make her eat it":
print "The Princess screams as you cram the cake in her mouth."
print "Then she smiles and cries and thanks you for saving her."
print "She points to a tiny door and says, 'The Koi needs cake too.'"
print "She gives you the very last bit of cake and shoves you in."
return 'gold_koi_pond'
else:
print "The princess looks at you confused and just points at the cake."
return 'princess_lives_here'
def gold_koi_pond(self):
print "There is a garden with a koi pond in the center."
print "You walk close and see a massive fin poke out."
print "You peek in and a creepy looking huge Koi stares at you."
print "It opens its mouth waiting for food."
feed_it = raw_input("> ")
if feed_it == "feed it":
print "The Koi jumps up, and rather than eating the cake, eats your arm."
print "You fall in and the Koi shrugs than eats you."
print "You are then pooped out sometime later."
return 'death'
elif feed_it == "do not feed it":
print "The Koi grimaces, then thrashes around for a second."
print "It rushes to the other end of the pond, braces against the wall..."
print "then it *lunges* out of the water, up in the air and over your"
print "entire body, cake and all."
print "You are then pooped out a week later."
return 'death'
elif feed_it == "throw it in":
print "The Koi wiggles, then leaps into the air to eat the cake."
print "You can see it's happy, it then grunts, thrashes..."
print "and finally rolls over and poops a magic diamond into the air"
print "at your feet."
return 'bear_with_sword'
else:
print "The Koi gets annoyed and wiggles a bit."
return 'gold_koi_pond'
def bear_with_sword(self):
print "Puzzled, you are about to pick up the fish poop diamond when"
print "a bear bearing a load bearing sword walks in."
print '"Hey! That\' my diamond! Where\'d you get that!?"'
print "It holds its paw out and looks at you."
give_it = raw_input("> ")
if give_it == "give it":
print "The bear swipes at your hand to grab the diamond and"
print "rips your hand off in the process. It then looks at"
print 'your bloody stump and says, "Oh crap, sorry about that."'
print "It tries to put your hand back on, but you collapse."
print "The last thing you see is the bear shrug and eat you."
return 'death'
elif give_it == "say no":
print "The bear looks shocked. Nobody ever told a bear"
print "with a broadsword 'no'. It asks, "
print '"Is it because it\'s not a katana? I could go get one!"'
print "It then runs off and now you notice a big iron gate."
print '"Where the hell did that come from?" You say.'
return 'big_iron_gate'
def big_iron_gate(self):
print "You walk up to the big iron gate and see there's a handle."
open_it = raw_input("> ")
if open_it == 'open it':
print "You open it and you are free!"
print "There are mountains. And berries! And..."
print "Oh, but then the bear comes with his katana and stabs you."
print '"Who\'s laughing now!? Love this katana."'
return 'death'
else:
print "That doesn't seem sensible. I mean, the door's right there."
return 'big_iron_gate'
class Engine(object):
def __init__(self, o, map):
self.map = map
self.obj = o
def play(self):
nextmap = self.map
while True:
print "\n--------"
room = getattr(self.obj, nextmap)
nextmap = room()
a_map = Map()
a_eng = Engine(a_map, "princess_lives_here")
a_eng.play()

Categories

Resources