python NameError, but I think the name is defined - python

Ok I going through LPTHW and writing a game. We are supposed to section the game up into different scripts to see how importing them works. I have 4 scripts: ex45.py executes the main code, Engine45.py is the engine, Locations45.py is the list of locations, and Maps45.py is what holds the map values and moves through locations.
The error I get when running is:
Traceback (most recent call last):
File "ex45.py", line 2, in
import Maps45
File "C:\Users\Raistlin\Python\Maps45.py", line 1, in
import Locations45
File "C:\Users\Raistlin\Python\Locations45.py", line 4, in
class Map(object):
File "C:\Users\Raistlin\Python\Locations45.py", line 6, in Map
'Gold_gym' : Gold_gym(),
NameError: name 'Gold_gym' is not defined
I don't understand why I am getting a Gold_gym is not defined when it is defined in Locations45.py.
Code blocks below:
ex45.py
import Engine45
import Maps45
import Locations45
a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()
Engine45.py
class Engine(object):
def __init__(self, location_map):
print "Engine __init__ has location_map", location_map
self.location_map = location_map
def run(self):
current_location = self.location_map.opening_location()
print "Play's first scene", current_location
while True:
print "\n"('-' * 20)
next_location_name = current_location.use()
print "next location", next_location_name
current_location = self.location_map.next_location(next_location_name)
print "map returns new location", current_location
Locations45.py
from random import randint
from sys import exit
class Location(object):
def use(self):
print "This is not configured."
exit(1)
class Loser_gym(Location):
quips = [
'You are worthless, goodbye.'
'Thanks for trying noob.'
'Sex and candy, not today.'
]
def use(self):
print Loser_gym.quips[randint(0, len(self.quips)-1)]
exit(1)
class Gold_gym(Location):
def use(self):
print "Welcome to the Gold Gym. This gym will test your physical prowess."
print "Before you there is a large pool of water with a center platform."
print "On your person is a satchel, a whip, a hat, and a gun."
print "Your goal is to find the way out of the gym."
print "Acceptable inputs are satchel, whip, hat, or gun."
print "Good Luck."
action = raw_input("What do you do:> ")
if action == 'satchel':
print "You throw your satchel towards the center platform."
print "It does absolutely nothing. Try again."
return 'Gold_gym'
elif action == 'whip':
print "You use your whip somewhat akin to Indiana Jones."
print "You swing from a pipe and land squarely on the center platform."
print "You have survived this turmoil."
return 'Sapphire_gym'
elif action == 'hat':
print "You valiantly toss your hat toward the center platform."
print "Your hat is caught by a gust of wind and blows away."
print "You cannot survive without your hat."
return 'Loser_gym'
elif action == 'gun':
print "You shoot your about wildly in the air."
print "A ricochet hits you in the head and you die."
return 'Loser_gym'
else:
print "DOES NOT COMPUTE, TRY AGAIN."
return 'Gold_gym'
class Sapphire_gym(Location):
def use(self):
print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
print "Just kidding there is no way to figure this out consistently."
print "Before you stands a door, the door has a small keypad on it."
print "Below the keypad is what appears to be a smart card reader."
print "On your way to the location you picked up two smartcards off the ground."
print "One is red and one is green."
print "Clearly you will need to use a smartcard and guess a code(3-digits)."
card = raw_input('Which card do you choose:> ')
if card == 'red':
print "A laser beam comes out of the door and cauterizes your brain."
return 'Loser_gym'
elif card == 'green':
code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
guess = raw_input('What code do you enter:> ')
guesses = 0
while guess != code and guesses < 20 and guess != '123':
print "INCORRECT!"
guesses += 1
guess = raw_input('What code do you enter:> ')
if guess == code or guess == '123':
print "Nice guess noob! You may press onward."
return 'Cerulean_gym'
else:
print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
return 'Loser_gym'
class Cerulean_gym(Location):
def use(self):
print "Welcome to the final gym, the Cerulean Gym!"
print "Before you is a 3x3 platform, your job is to cross the platform."
print "Be warned that each tile can trigger a trap."
print "Good luck!"
correct_square = ['3', '1', '2']
jump = raw_input("Square 1, 2, or 3?:> ")
jumps = 0
while jumps < 3:
if jump == correct_square:
print "Nice job! You picked the correct square!"
jump += 1
correct_square = correct_square[0+jump]
jump = raw_input("Square 1, 2, or 3?:> ")
jumps += 1
else:
print "YOU FAIL! Goodbye you puny infidel."
return 'Loser_gym'
print 'NICE JOB. YOU WIN ALL THE BASE!'
Maps45.py
import Locations45
class Map(object):
locations = {
'Gold_gym' : Gold_gym(),
'Sapphire_gym' : Sapphire_gym(),
'Cerulean_gym' : Cerulean_gym(),
'Loser_gym' : Loser_gym()
}
def __init__(self, start_location):
self.start_location = start_location
print "start_location in __init__", self.start_location
def next_location(self, location_name):
print "start_location in next_location"
val = Map.locations.get(location_name)
print "next_location returns", val
return val
def opening_location(self):
return self.next_location(self.start_location)
Help please?

When you:
import Locations45
that module is imported under the namespace Locations45
So when you call
Gold_gym()
It looks in Maps45 for that object, never knowing to look in Locations45.
Change the line to read:
locations = {
'Gold_gym' : Locations45.Gold_gym(),
'Sapphire_gym' : Locations45.Sapphire_gym(),
'Cerulean_gym' : Locations45.Cerulean_gym(),
'Loser_gym' : Locations45.Loser_gym()

If you just do import Locations45, it doesn't import each of the names - instead, it imports it as a group. You can refer to individual things within the group using a period:
'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()
Alternatively, you could import all of the names specifically:
from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym
which would make those names available without needing to use the prefix.

Related

Can't seem to rid of the error message no matter what I've tried. From "Hello! Python" book

Here's the error I'm getting when I try to run the code below:
Traceback (most recent call last):
File "/Users/JPagz95/Documents/Hunt_the_Wumpus_3.py", line 76, in <module>
visit_cave(0)
File "/Users/JPagz95/Documents/Hunt_the_Wumpus_3.py", line 15, in visit_cave
unvisited_caves.remove(cave_number)
AttributeError: 'range' object has no attribute 'remove'
I understand how the int and range don't have those functions, but they shouldn't be defined that way originally. I realize it's a lot of code but I feel like the problem might be in more than one place. This code is based off of chapter to of the "Hello! Python" book if that helps. I would appreciate any help I can get!
from random import choice
cave_numbers = range(0,20)
unvisited_caves = range(0,20)
visited_caves = []
def create_tunnel(cave_from, cave_to):
""" create a tunnel between cave_from and cave_to """
caves[cave_from].append(cave_to)
caves[cave_to].append(cave_from)
def visit_cave(cave_number):
""" mark a cave as visited """
visited_caves.append(cave_number)
unvisited_caves.remove(cave_number)
def choose_cave(cave_list):
""" pick a cave from a list, provided that the
cave has less than 3 tunnels """
cave_number = choice(cave_list)
while len(caves[cave_number]) >= 3:
cave_number = choice(cave_list)
return cave_number
def print_caves():
""" print out the current cave structure """
for number in cave_numbers:
print (number, ":", caves[number])
print ('----------')
def setup_caves(cave_numbers):
""" create a starting list of caves """
caves = []
for number in cave_numbers:
caves.append([number])
return caves
def link_caves():
""" make sure all of the caves are connected with two way tunnels"""
while unvisited_caves != []:
this_cave = choose_cave(visited_caves)
next_cave = choose_cave(unvisited_caves)
create_tunnel(this_cave, next_cave)
visit_cave(next_cave)
def finish_caves():
""" link the rest of the caves with one way tunnels """
for cave in cave_numbers:
while len(caves[cave]) < 3:
passage_to = choose_cave(cave_numbers)
caves[cave].append(passage_to)
def print_location(player_location):
""" tell the player about where they are """
print ("You are in a cave ", player_location)
print ("From here you can see caves: ")
print (caves[player_location])
if wumpus_location in caves[player_location]:
print ("I smell a wumpus!")
def get_next_location():
""" Get the player's next location """
print ("Which cave next?")
player_input = input(">")
if (not player_input.isdigit() or
int(player_input) not in
caves[player_location]):
print(player_input + "?")
print ("That's not a direction I can see!")
return none
else:
return int(player_input)
caves = setup_caves(cave_numbers)
visit_cave(0)
print_caves()
link_caves()
print_caves()
finish_caves()
wumpus_location = choice(cave_numbers)
player_location = choice(cave_numbers)
while player_location == wumpus_location:
player_location = choice(cave_numbers)
print ("Welcome to Hunt the Wumpus!")
print ("You can see ", len(cave_numbers), " caves")
print ("To play, just type the number")
print ("of the cave you wish to enter next")
while True:
print_location(player_location)
new_location = get_next_location()
if new_location != None:
player_location = new_location
if player_location == wumpus_location:
print ("Aargh! You got eaten by a wumpus!")
Make sure you declare as
unvisited_caves = list(range(0,20))
by default range(0,20) returns an object that "generates" the values of 0 to 20. It is much more efficient because it just needs to remember the start and end values (0 and 20) along the step size (in your case 1).
Contrast this with a list that must store every value from 0 to 20, and you can remove individual values from this list.

Simple Python Game (stuck on classes)

I'm really stuck on this simple user input game I created. It's an exercise from learn python the hard way. I've been trying for over a week to figure it out on my own and finally caved in to asking for help. I think the problem point in my code is the Engine() class. Anyway here's the code:
from sys import exit
from random import randint
class Island(object):
def enter(self):
pass
class Engine(object):
def __init__(self, island_map):
self.island_map = island_map
def play(self):
current_island = island_map.opening_island()
last_island = self.island_map.next_island('Tropical')
while current_island != last_island:
next_island_name = current_island.enter()
current_island = self.island_map.next_island(next_island_name)
current_island.enter()
class Loser(Island):
snippets = ["Welcome to loser Island",
"Can't win them all",
"There's always next time"]
def enter(self):
print "Game over"
print Loser.snippets[randint(0,len(self.snippets)-1)]
exit(1)
class Jungle(Island):
def enter(self):
print "Welcome to the Jungle!"
print "You must fight the monkey to pass!"
print "Choose your weapon..."
weapons = ['stick', 'fly swatter', 'banana']
print weapons
fighter_weapon = raw_input("Choose from a a weapon above...")
if fighter_weapon == 'stick':
print "Stick can't beat a monkey!"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'fly swatter':
print "The monkey steals your fly swatter"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'banana':
print "The monkey is hypnotized by the banana"
print "You continue to the next island..."
return 'Frozen'
else:
print "What? Doesn't make sense"
return 'Jungle'
class Frozen(Island):
#add green, blue circle, and black diamond
def enter(self):
print "This is snow land"
print "Here's your snowboard, choose your path"
print "([[[[[[[[[)"
runs = ["green", "blue", "black"]
print runs
run_choice = raw_input(" >")
if run_choice == 'green':
print "Easy way out?"
print "No good"
print "Wrong"
return 'Loser'
elif run_choice == 'blue':
print "okay, at least not the easiest way"
print "You have some guts, I'll let you choose one more time"
return 'Frozen'
elif run_choice == 'black':
print "I like your style"
print "Going for the hard choice shows courage"
print "Continue to the next island"
return 'Tropical'
else:
print "Say whaaat?!"
return 'Frozen'
class Tropical(Island):
def enter(self):
print "You made it to the final Island!"
print "Look here's the treasure chest!"
print " All that's left to do is guess the code on the chest"
print "Be smart, you only get five guesses..."
t_key = "1234"
chest_guess = raw_input("What do you think it is?")
guesses = 0
while chest_guess != t_key and guesses < 4:
print "Guess again"
guesses += 1
chest_guess = raw_input(" ?")
if chest_guess == t_key:
print "You guessed right!"
print "You won"
else:
print "Sorry"
return 'Loser'
class Map(object):
islands = {
'Loser': Loser(),
'Jungle': Jungle(),
'Frozen': Frozen(),
'Tropical': Tropical(),
}
def __init__(self, start_island):
self.start_island = start_island
def next_island(self, island):
val = Map.islands.get(island)
return val
def opening_island(self):
return self.next_island(self.start_island)
mj_map = Map('Jungle')
mj_game = Engine(mj_map)
mj_game.play()
Right now I'm stuck on an error that states "island_map" is not defined in my Engine class. Which I don't understand because to me it looks like it is defined. Any input would be appreciated.
def play(self):
current_island = island_map.opening_island()
needs to be changed to
def play(self):
current_island = self.island_map.opening_island()
as it is apart of that instance

Python script executing in different order that I want

For simplicity I'm posting here only two modules (the other modules have "pass" in them). start.py module worked right up until I changed something in player.py module, in the class CreateNewPlayer and now what happens is this:
I start with start.py from my command line but instead of first showing my intro (splashcreen function) it jumps straight to CreateNewPlayer right away.
What did I do wrong?
This is the first file start.py:
import sys
import custom_error
import player
import handler
import prompt
import game
def splash_screen():
print chr(27) + "[2J"
print "*" * 80
print "***** Welcome to ZOMBIE ADVENTURE *****"
print "*" * 80
print "\nSelect option:"
print "1. Start a new game"
print "2. Load existing game"
print "3. Quit"
while True:
action = prompt.menu()
if action == 1:
create_player = player.CreateNewPlayer()
new_player = player.Player(create_player.name, create_player.age, create_player.male, create_player.inventory)
print "\nYour name is %s and you're %d old." % (new_player.name, new_player.age)
print "It is %s that you're a man." % new_player.male
print "\n1. Continue to game"
print "2. Back to main menu"
action = prompt.menu()
while True:
if action == 1:
game.Engine.launchgame()
elif action == 2:
exit(1)
else:
custom_error.error(1)
# a_game = game.Engine('Room1')
# a_game.LaunchGame(new_player)
elif action == 2:
handler.load()
elif action == 3:
exit(1)
else:
custom_error.errortype(0)
splash_screen()
Now second file called player.py:
import sys
import custom_error
import prompt
import game
class Player(object):
male = True
inventory = []
def __init__(self,name,age,male,inventory):
self.name = name
self.age = age
self.male = male
self.inventory = inventory
class CreateNewPlayer(object):
print chr(27) + "[2J"
print "-" * 80
print "Character creation"
print "-" * 80
name = raw_input("Type your character name > ")
age = int(raw_input("Put down your age in numbers > "))
male = True
sex = raw_input("Are you a male or female? M/F > ")
if sex.lower() == "m":
male = True
elif sex.lower() == "f":
male = False
else:
print "Please type either 'M' or 'F'"
pass
inventory = []
The attributes within CreatePlayerCharacter are class attributes; all of the code within that class definition runs when the class is created, i.e. when the file is imported, rather than when a class instance is created.
Looking at your code so far, you would probably be better defining a class method Player.create:
class Player(object):
...
#classmethod
def create(cls):
name = raw_input("Type your character name > ")
...
return cls(name, age, male, [])
This can be accessed:
new_player = Player.create()
and will return a Player instance directly.
You should also remove male and inventory class attributes from Player.

I'm making a python text-adventure. Need help making an 'inventory'

I'm making a python text adventure. It is based off of ex41 in Learn Python the Hard Way, so it is somewhat similar. My question, however, has nothing to do with that exercise. I'm trying to make an inventory so that an item can be picked up and used (i.e. a key or febreeze).
At first my plan was to use a Boolean variable so that when the item was 'picked up' it would set a value to True, but it doesn't seem to be working. I think that the problem is that the value resets once I leave the room.
Now I'm trying a list and when the item is 'picked up' the item is appended into the inventory list.
How can I make an inventory, or at least 'pick up' an item and then later 'use' it?
The lines of code that I think are important to look at are 18-20 (under the def __init__(self, start)), 77(under the def cell(self)), 161-162(under the def janitor(self)).
from sys import exit
from random import randint
import time
prompt = '> '
class Game(object):
def __init__(self, start):
self.quips = [
"Way to go, you died."
"Now you're dead. Sweet.",
"Well isn't this just peachy? You're dead. (It's not peachy.)"
]
self.start = start
#self.smell = 0
#self.Febreeze = False
#self.key = False
self.inventory = []
#if self.smell >=2:
# return 'death'
def play(self):
next = self.start
while True:
print "\n-------"
room = getattr(self, next)
next = room()
def death(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
def intro(self):
print "You wake up."
print "You're in a dark cell."
print "You have no idea who you are or where you are."
print "The door is slightly open."
print "You stagger through the door. The light is blinding."
print "You have just escaped imprisonment and you're on the run."
return 'central_corridor'
def central_corridor(self):
print "In front of you is a long corridor with no doors on the side, but you think you can make out a door at the very end."
print "Behind you is the cell that you have just escaped."
next = raw_input(prompt)
if "cell" in next:
print "You decide to go back into your cell."
return 'cell'
elif "forward" in next:
print "You travel down the corridor towards the door."
return 'front_corridor'
else:
print "That command doesn't exist."
return 'central_corridor'
def cell(self):
print "You're standing in the middle of a musty cell."
print "There is a bed in the corner with a rotting mattress."
print "Under the bed the bricks are loose."
print "In the opposite corner there is a dirty toilet that implies that prison food is even worse than Taco Bell."
print "There are some scratches on the wall next to the toilet."
print "Behind you is an exit into the corridor."
next = raw_input(prompt)
if "toilet" in next:
print "It'd probably be best if this toilet wasn't described."
#self.smell = self.smell + 1
return 'cell'
elif "febreeze" in next and "Febreeze" in self.inventory #and self.Febreeze = True:
print "You use the Febreeze on the toilet to get rid of the odor."
print "Now you can go behind the toilet to read the rest of the scratches."
elif "scratches" in next:
print "The scratches on the wall seem to be tally marks. It goes up to 123. I wonder what it means."
print "You see more scratches behind the toilet, but the stench is too much for you to handle."
print "If only you could get rid of the smell..."
#self.smell = self.smell + 1
return 'cell'
elif "bed" in next:
print "There are various stains on the mattress. Some of the springs are poking up into the mattress. Ouch."
print "Buried between the wall and the mattress is a stuffed animal."
return 'cell'
elif "bricks" in next:
print "You pull the bricks out of the floor and find a few pieces of toilet paper."
print "There is a note written on them in what you hope is dried blood."
print "The note reads:\n -------------------------\nthe closet!! the closet in the walls i'm not \nsure\twhich one it is but its defin-\nly in the hall. i hear it in the bricks!\n---------------------------"
print "Hmm, maybe it's a hint or something."
elif "corridor" in next:
return 'central_corridor'
else:
print "I do not understand how to %s" % next
return 'cell'
def front_corridor(self):
print "You are standing in front of a door."
print "On the side of the door is a keypad."
next = raw_input(prompt)
if "keypad" in next:
return 'keypad'
elif "wall" in next:
return 'wall'
elif "back" in next:
return 'central_corridor'
else:
print "I don't understand %s" % next
return 'front_corridor'
def wall(self):
print "Which wall do you want to check?"
next = raw_input(prompt)
if "left" in next:
return 'left'
elif "right" in next:
return 'right'
elif "back" in next:
return 'front_corridor'
def right(self):
print "You examine the wall carefully, running your fingers across each of the bricks."
print "Unfortunately it doesn't look like anything of value is in this wall."
print "Well, you just wasted some time."
return 'wall'
def left(self):
print "You examine the wall carefully, running your fingers across each of the bricks."
print "One of the bricks seems to be protruding from the wall."
print "Do you push it?"
next = raw_input(prompt)
if next[0] == "y":
print "A few of the bricks shift, revealing a secret door way."
return 'janitor'
elif next[0] == "n":
print "You decide not to push the brick. Good thinking, it may have been a booby trap."
return 'front_corridor'
else:
print "That doesn't exactly make sense..."
return 'wall'
def janitor(self):
print "You are in a room filled with janitorial tools."
print "On your left you see a few cans of Febreeze, a plunger and a Playboy magazine."
next = raw_input(prompt)
if "febreeze" in next:
print "You pick up some Febreeze and put it in your back pocket."
print "Maybe this will be useful somewhere down the line."
self.inventory.append("Febreeze")
#self.Febreeze = True
return 'janitor'
elif "plunger" in next:
print "You try to pick up the plunger but it appears to be stuck in the ground."
print "After tugging for a few minutes the handle comes out, leaving the rubber suction cup plastered to the floor."
print "Who knows what's keeping it there."
print "You decide not to touch it."
return 'janitor'
elif "playboy" in next:
print "Well isn't that nice."
print "These janitors certainly have good taste."
return 'janitor'
elif "back" in next:
return 'front_corridor'
else:
print "Do WHAT with WHAT?"
return 'janitor'
def keypad(self):
print "Above the keypad there is a sign that reads:\n-----------\nInput a 3 digit code.\nWarning: If code is incorrect 3 times, keypad will self-destruct.\n-----------"
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("Password: ")
guesses = 0
while guess != code and guesses < 2:
print "BZZZZZEDD!"
guesses += 1
guess = raw_input("Password: ")
if guess == code:
print "The keypad beeps in acceptance. Wow, that was a good guess"
print "The door swings open."
print "Behind the door is a long bridge suspended over a lake of lava."
return 'bridge'
elif "key" in guess and key == True:
print "You flash your card key across the keypad."
print "There is a beep as the door swings open."
print "Behind the door is a long bridge suspended over a lake of lava."
return 'bridge'
else:
print "The keypad buzzes one last time and then you hear a sickening melting"
print "sound as the lock mechanism fuses together."
print "There is a small clicking while the keypad countsdown."
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print "There is a large explosion and you are caught right in the middle of it."
print "The fiery blast tears your skin from your body as you scream in agony."
return 'death'
def bridge(self):
print "You carefully walk onto the bridge."
print "One false move and you could be dead."
print "Across the bridge is a door leading to the outside world."
next = raw_input(prompt)
if "jump" in next:
print "You jump to your death."
print "Probably not the best idea."
elif "run" in next:
print "You run"
a_game = Game("intro")
a_game.play()
Your approach seems to work fine, but you have a couple of bugs. In cell(), you need a : after the elif "febreeze"... statement (before the comment starts). Also, at the end of that elif block, you need to return 'cell'. With these changes, I can pick up the Febreeze and use it.
If you define the inventory as a list(that's what I did), then you can do:
class Attributes:
def __init__(self, inventory):
self.inventory = inventory
Player = Attributes([])
Player.inventory.append("Febreeze")
The square brackets make the inventory, and the "append" adds Febreeze to it.
if you tryed to define it as a list e.g (guessing this is on python)
def inventory[]
inventory.append
add item (inventory)
cannot rember how to add it to the inventory but there is the basics

How to have a versatile function call that can call different functions in Python?

I'm trying to make a text-based game in Python, however, code could get out of hand pretty quickly if I can't do one thing on one line.
First, the source code:
from sys import exit
prompt = "> "
inventory = []
def menu():
while True:
print "Enter \"start game\" to start playing."
print "Enter \"password\" to skip to the level you want."
print "Enter \"exit\" to exit the game."
choice = raw_input(prompt)
if choice == "start game":
shell()
elif choice == "password":
password()
elif choice == "exit":
exit(0)
else:
print "Input invalid. Try again."
def password():
print "Enter a password."
password = raw_input(prompt)
if password == "go back":
print "Going to menu..."
else:
print "Wrong password. You are trying to cheat by (pointlessly) guess passwords."
dead("cheating")
def shell(location="default", item ="nothing"):
if location == "default" and item == "nothing":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
else:
print "Error: Closing game."
def location():
print "Nothing to see here."
# Placeholder location so the script won't spout errors.
def dead(reason):
print "You died of %s." % reason
exit(0)
print "Welcome."
menu()
First, an explanation on how my game basically works.
The game has a 'shell' (where input is done) which receives information from and sends information to the different 'rooms' in the game, and it stores the inventory. It can receive two arguments, the location and an eventual item to be added to the inventory. However, line 40-42 (the first elif block in 'shell') and line 43-45 (the last elif block in 'shell') are supposed to go back to whatever location the location was (line 42 and 45, to be exact). I've tried "%s() % location" but that doesn't work, it seems to only work when printing things or something.
Is there any way to do this? If not, even writing an engine for this game would be a nightmare. Or I'd have to make an entirely different engine, which I think would be a way better approach in such a case.
Sorry if I made any mistakes, first question/post ever.
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
I guess you want to call a function having its name. For that you need a reference to the module or class inside which it was defined:
module = some_module # where the function is defined
function = getattr(module, location) # get the reference to the function
function() # call the function
If the function is defined in the current module:
function = globals()[location]
function() # call the function
If I correctly understand what you want is something like this : player will enter a location name and you want to call the related method. "%s"()%location will not work, a string (that is what is "%s" is not callable).
Let's try an OOP way :
class Maze:
def __init__(self):
# do what you need to initialize your maze
def bathroom(self):
#go to the bathroom
def kitchen(self):
# go to the kitchen
def shell(self, location="", item=""):
if location == "" and item == "":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location and item:
print "You picked up %s." % item
inventory.append(item)
getattr(self, location)()
elif location and item == "":
print "You enter the room."
getattr(self, location)()
else:
print "Error: Closing game."
maze = Maze()
while True: # or whatever you want as stop condition
location = raw_input("enter your location :")
item = raw_input("enter your location :")
maze.shell(location=location, item=item)
I think you can use the getattr() method.
Example : You want to call method "helloword()" from module "test", you would then do :
methodYouWantToCall = getattr(test, "helloworld")
caller = methodYouWantToCall()
Hope it gives you a clue.

Categories