def Myfunc():
print "Stuff"
#Title: "CrashLanding"
#By: Python User
#November 16, 2009
#Features improved coding style, or at least I think so
#note:code based on J.G.S'S code-I really learned alot from his code Some credit goes to him
#note:I dont think that is his actual username so keep that in mind
#Can you guys please look over my code? Is it a good coding style? Like i said, its based
#of off J.G.S'S code as i am rather inexp...this is my first real text adventure
#note:crystals same as gold, only i wanted to have a different name for the currency
crystals = 0
gotCrystals_cell=0
gotCrystals_sewer=0
gotCrystals_lair=0
gotCrystals_caves=0
gotCrystals_cavelake=0

crystals_found1=0
crystals_found2=0
crystals_found3=0
crystals_found4=0
crystals_found5=0
dust_movedlair=0

def pass1():
    print 'you posess', crystals, 'crystals'
    prompt_cell()
def pass2():
    print 'you posess', crystals, 'crystals.'
    prompt_sewer()
def pass3():
    print 'you posess', crystals, 'crystals.'
    prompt_lair()


def help1():
    print '''The following is the list of commands that you can make.
    commands should be written in lowercase font only. north, south, east, west, look(object), look inside(object), help, get(item), use(item), talk(npc), use ship(endgame)'''
    print
    pass1()
def help2():
    print '''The following is the list of commands that you can make.
    commands should be written in lowercasef only. north, south, east, west, look(object), look inside(object), help, get(item), use(item), talk(npc),  use ship(endgame)'''
    print
    pass2()
def help3():
    print '''The following is the list of commands that you can make.
    commands should be written in lowercasef only. north, south, east, west, look(object), look inside(object), help, get(item), use(item), talk(npc), use ship(endgame)'''
    print
    pass3()
def help4():
    print '''The following is the list of commands that you can make.
    commands should be written in lowercasef only. north, south, east, west, look(object), look inside (object), help, get(item), use(item), talk(npc), use ship(endgame)'''
    print
    pass4()
def help5():
    print '''The following is the list of commands that you can make.
    commands should be written in lowercasef only. north, south, east, west, look(object), look inside(object), help, get(item), use(item), talk(npc), use ship(endgame)'''
    pass5()

def began():
    print '''You awake to a sudden pain in your side. Looking around, you see that you are inside a dimly lit cell.
You were supposed to be part of a raiding party on Earth but were shot down over City012.
The last thing you remeber before you blacked out was that you saw your ship crashland into the side of a mountain.
If your lucky, your ship could still be flyable thanks to shield technology. But what matters you most is escaping
this cell.

Your ship is powerd by purple cyrstals found naturally on your homeworld.
In order to fly the ship, you'll have to find 30 of them. Unfortunly for you,
the humans most likly took all of them in order to study and then reverse engineer them to power their machines.
Remember, you still have to find the ship before you can put the 30 crystals to good use.'''
    cell()

def cell():
    print 'you posess', crystals, 'crystals'
    print '''Upon studying your cell futher, through the blanket of darkness you can make out a note lying on the ground and a bunkbed.To the north is a sewer,
to the south is a group of caves below the cell connected by a hidden floor door.'''
    prompt_cell()
def prompt_cell():
    global crystals
    global gotCystals_cell
    global gold_found1
    prompt_cell = raw_input('>')
    if prompt_cell == 'north':
        sewer_room()
    elif prompt_cell == 'south':
        hiddendoor_room()
    elif prompt_cell == 'north':
        caves()
    elif prompt_cell == 'look note':
        print '''you pick up the note and began to read: If anyone is reading this,I stashed some loot in the bunkbed up against the wall. Don't ask how
                 I obtained them, but anyone who finds all 30 crystals meet me at once
                 inside a hidden cave network underneath this facility.'''
    elif prompt_cell=='help':
        help1()
    elif prompt_cell == 'look inside bunkbed':
        print '''you lift up the mattress on the bunkbed and as the note clearly stated, you find 5 crystals underneath'''
        gold_found1 = 1
        pass1()

    if prompt_cell == 'get crystals':
    #this code will not run. i got this error from the program:
    #line 101, in prompt_cell UnboundLocalError: local variable 'gotCrystals_cell' referenced before assignmen]
         if gotCrystals_cell == 0 and crystals_found1 == 1:
            print '''You get the gold that was under the mattress of the bunkbed.'''
            gold = crystals+5
            gotCrystals_cell = 1
            pass1()
         elif gotCrystals_cell == 0 and crystals_found1 == 0:
            print '''You don't see any crystals.'''
            pass1()
         elif gotCrystals_cell == 1 and crystals_found1 == 1:
            print '''You do know you already have the crystals, right?'''
            pass1()
    else:
        print '''I don't know how to perform that.'''
        pass1()
        
  
                       
#I'm going to add the four other rooms and other code later, im burnt after all this typing.
#I hope to add more commands and more layers of difficulty,
#like i want to hide the space ship in several objects, more roms, etc
#but that will have to wait
#began the game:
began()

I need help near the end of my code. Something about an unboundlocalerror. Can you guys look through my code and see if i did

something wrong: this is the "offending" code i think: if gotCrystals_cell == 0 and crystals_found1 == 1:

At first i thought it was the spaces i made but that was not it.
Spent like 40 minutes rewriting it before becoming completly
stumped.

The rest of the code was OK, though.

Much appreciated,
Python User

Look at the beginning of prompt_cell. You misspelled one of the global variables. :)

However, your code looks extremely ill-formed. Though it will work like this, this is a very shakey way to write it. Do you know what classes are? Also, you can pass functions as arguments, so you don't need to write up five help functions that do the same thing and then execute a different function, just make one function that you pass another function.

As Mathhax0r take upp your code is really not god at all it`s a big mess.
I think helping you now is difficult because of your code design.

Never use global variabels like this, or at all.
The are ugly an as code grow the will give a lot of problems.

Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
When you use global like this you are pollutioning the global namespace

As Mathhax0r take upp your code is really not god at all it`s a big mess.
I think helping you now is difficult because of your code design.

Never use global variabels like this, or at all.
The are ugly an as code grow the will give a lot of problems.

Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
When you use global like this you are pollutioning the global namespace

Thanks. Im going to go try to clean up the code. I kind of understand classes. I did misspell prompt. So, should i put all the variables and the code in classes? If so, why? how does classes make the code neater? I found a good tut on the net that rly makes it clear: www.sthurlow.com/ I'll try and clean it up.

Any info about classes you could give me...much welcomed.

ALSO: how do you pass funtions as arugements?

Thanks. Im going to go try to clean up the code. I kind of understand classes. I did misspell crystals as cystals. So, should i put all the variables and the code in classes? If so, why? how does classes make the code neater? I found a good tut on the net that rly makes it clear: www.sthurlow.com/ I'll try and clean it up.

Any info about classes you could give me...much welcomed.

ALSO: how do you pass funtions as arugements?

i misspelled crystals as cystals, lol.

whats all this jibber jabber about what you said here: Never use global variabels like this, or at all.
The are ugly an as code grow the will give a lot of problems.

Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
When you use global like this you are pollutioning the global namespace

can you explain it, or show me to a site that can?

,python user

NOTE: When i do fix my code hopfully, i will release it and id like to see your opinions.

Well, you'll notice there are other errors in your code you haven't gotten to as well. For example, in pass1, it will fail. The reason is, pass1 doesn't know what the variable crystals . If you want to make it see crystals, which was defined outside of the function, then you need to write it like this:

def pass1():
    global crystals
    print 'you posess', crystals, 'crystals'
    prompt_cell()

The line global crystals says there is a variable named crystals that you defined globally (outside of any function). Before I even get into why this can be bad, let's rewrite all of your help functions.
*Quick sidenote: You never defined pass4 and pass5*

def help(argGoWhere):
    print '''The following is the list of commands that you can make.
    commands should be written in lowercase font only. north, south,
    east, west, look(object), look inside(object), help, get(item), 
    use(item), talk(npc), use ship(endgame)'''
    print
    global crystals
    print 'You possess', crystals, 'crystals.' #lol, you misspelled possess in your original.
    argGoWhere()

Here's how you'd use this new function in your code. On line 96 where you call help1, you'd instead do this: help(prompt_cell) and it would pass the function prompt cell to help, and help would print what it needs to, then call that function.

Another thing you need to fix in your code is your variable names. You have a variable named prompt cell, and also a function. That's fairly confusing.

Now I know you are inexperienced, and that's the cause for some of your errors, but the fact that you use global variables and don't use classes is really gonna hurt you. Notice how the new help function I made gets rid of pass1, pass2, pass3, pass4, pass5, help1, help2, help3, help4, and help5 and replaces them all with one function. If you didn't use this new help function, then you would just keep making new functions that did almost the exact same thing. This makes you much more prone to errors simply because you're typing more. Classes are just a way of making your code more understandable, and more abstract, both allowing you to type less and make less errors. What do you know about classes already? I'll try to fill in the rest of what you need to know.

Well, you'll notice there are other errors in your code you haven't gotten to as well. For example, in pass1, it will fail. The reason is, pass1 doesn't know what the variable crystals . If you want to make it see crystals, which was defined outside of the function, then you need to write it like this:

def pass1():
    global crystals
    print 'you posess', crystals, 'crystals'
    prompt_cell()

The line global crystals says there is a variable named crystals that you defined globally (outside of any function). Before I even get into why this can be bad, let's rewrite all of your help functions.
*Quick sidenote: You never defined pass4 and pass5*

def help(argGoWhere):
    print '''The following is the list of commands that you can make.
    commands should be written in lowercase font only. north, south,
    east, west, look(object), look inside(object), help, get(item), 
    use(item), talk(npc), use ship(endgame)'''
    print
    global crystals
    print 'You possess', crystals, 'crystals.' #lol, you misspelled possess in your original.
    argGoWhere()

Here's how you'd use this new function in your code. On line 96 where you call help1, you'd instead do this: help(prompt_cell) and it would pass the function prompt cell to help, and help would print what it needs to, then call that function.

Another thing you need to fix in your code is your variable names. You have a variable named prompt cell, and also a function. That's fairly confusing.

Now I know you are inexperienced, and that's the cause for some of your errors, but the fact that you use global variables and don't use classes is really gonna hurt you. Notice how the new help function I made gets rid of pass1, pass2, pass3, pass4, pass5, help1, help2, help3, help4, and help5 and replaces them all with one function. If you didn't use this new help function, then you would just keep making new functions that did almost the exact same thing. This makes you much more prone to errors simply because you're typing more. Classes are just a way of making your code more understandable, and more abstract, both allowing you to type less and make less errors. What do you know about classes already? I'll try to fill in the rest of what you need to know.

Well, I know a class is written something like this:

# Defining a class
class class_name:
[statement 1]
[statement 2]
[statement 3]
[etc]

self refers to things from within the class itself. to access functions and variables elsewhere inside your class, the name must be preceded with self and a full-stop(e.g self.variable_name).

the __init__ function allows you to call the name of your class. To create an instance of your class you give it it's name and than in brackets you pass the variables to __init__ function.

this info is coped from: http://www.sthurlow.com/python/lesson08/

* When we first describe a class, we are defining it (like with functions)
* The ability to group similar functions and variables together is called encapsulation
* The word 'class' can be used when describing the code where the class is defined (like how a function is defined), and it can also refer to an instance of that class - this can get confusing, so make sure you know in which form we are talking about classes
* A variable inside a class is known as an Attribute
* A function inside a class is known as a method
* A class is in the same category of things as variables, lists, dictionaries, etc. That is, they are objects
* A class is known as a 'data structure' - it holds data, and the methods to process that data.

Inheritance and the Pointers and Dictionaries of Classes is a little
confusing, but than again it all is.

I have a little question: for this code: #

crystals = 0
#
gotCrystals_cell=0
#
gotCrystals_sewer=0
#
gotCrystals_lair=0
#
gotCrystals_caves=0
#
gotCrystals_cavelake=0
#

#
crystals_found1=0
#
crystals_found2=0
#
crystals_found3=0
#
crystals_found4=0
#
crystals_found5=0
#
dust_movedlair=0

Is it possible to make those into a class? Is it true you can pretty much turn any code into a class if you wanted to?

A class is a prototypical object. An example would be at a restaurant. So that you don't have to keep rewriting code, you could make a chair class and a table class. That'd be pretty boring and empty, so how about a customer and waiter class. They're both people, so you could make a person class, and both the customer class and waiter class inherit from it (i.e. have all the properties of it).

A method is a function of a class. You can think of it as something a class can do. For example, a person can walk and sit down, so each of those would be functions you would give the class person. We can also breathe, eat, sleep, etc. Do you see the possibilities?

Remember that classes are a way of classifying things, and you have to make an object of that class before you can use it. Example: you can make chair class, but there are still no chairs until you do this:

chair1 = Chair()

This chair talk is all good, but it probably is still a bit confusing, right? I made you a simple working text-adventure that you can use to further work on your code if you'd like:

class Room:
	
	def __init__(self,argDesc,argDir):
		#here we're just saying that a room has a
		#string called description, and a dictionary
		#called dir (directions)
		self.desc = argDesc
		self.dir = argDir

	def narrarate(self):
		print self.desc

	def goTo(self, argWhere):
		if self.dir.has_key(argWhere) == 0:
			return None
		else:
			return self.dir[argWhere]

landing_site = []; next_room = []; this_room = []; that_room = []
#I had to make these all lists with one element because you have to
#define something before you can use it. If you want to make rooms of
#your own, then first make an empty list up here. Afterwards, you can
#append a room to it like I did.

landing_site.append(Room("Your ship crashed in a glacial room. There is only \
one way out, north.", {"north": next_room}))

next_room.append(Room("Two roads diverged in a yellow wood. East or west.",  \
{"east": this_room, "west": that_room, "south": landing_site}))

this_room.append(Room("You are trapped!", {}))

that_room.append(Room("You are trapped!", {}))

#this loop is the main game loop. The whole game happens inside of here.
#currRoom is where you are at. That stupid [0] is because I had to wrap
#all of the rooms with a list to make them work properly. I might fix
#that later, but it works for now.
currRoom = landing_site[0]
while True:
	currRoom.narrarate() #say the description of the room
	print; whatTheySay = raw_input(">>"); print
	whatTheySay = whatTheySay.split(" ") #break it into words
	if whatTheySay[0] == "go":
		c1 = (whatTheySay[1] == "north") 
		c2 = (whatTheySay[1] == "south")
		c3 = (whatTheySay[1] == "east")
		c4 = (whatTheySay[1] == "west")
		if c1 or c2 or c3 or c4:
			if currRoom.goTo(whatTheySay[1]) == None:
				print "You cannot go this way...\n"
			else:
				currRoom = currRoom.goTo(whatTheySay[1])[0]
				print "You travel %s.\n" % whatTheySay[1]
		else:
			print "That isn't a direction. Try lowercase if you think it is.\n"
	elif whatTheySay[0] == "quit":
		break
	elif whatTheySay[0] == "help":
		print "I'm sure <Python User> will put a list of commands here later. ;)"
	else:
		print "That isn't an acceptable command. Try help for a list of commands."

print "Bye!"

I kind of made it on the fly, so it doesn't have crystals or looking in rooms or anything, yet, but that can all be added later. Do you see how simple each of my rooms are compared to yours? I could add 100 custom rooms with about 200 lines of code, where you might need several thousand lines. Whether or not you use this, I hope this helps you understand a bit better. Good luck with your game.

A class is a prototypical object. An example would be at a restaurant. So that you don't have to keep rewriting code, you could make a chair class and a table class. That'd be pretty boring and empty, so how about a customer and waiter class. They're both people, so you could make a person class, and both the customer class and waiter class inherit from it (i.e. have all the properties of it).

A method is a function of a class. You can think of it as something a class can do. For example, a person can walk and sit down, so each of those would be functions you would give the class person. We can also breathe, eat, sleep, etc. Do you see the possibilities?

Remember that classes are a way of classifying things, and you have to make an object of that class before you can use it. Example: you can make chair class, but there are still no chairs until you do this:

chair1 = Chair()

This chair talk is all good, but it probably is still a bit confusing, right? I made you a simple working text-adventure that you can use to further work on your code if you'd like:

class Room:
	
	def __init__(self,argDesc,argDir):
		#here we're just saying that a room has a
		#string called description, and a dictionary
		#called dir (directions)
		self.desc = argDesc
		self.dir = argDir

	def narrarate(self):
		print self.desc

	def goTo(self, argWhere):
		if self.dir.has_key(argWhere) == 0:
			return None
		else:
			return self.dir[argWhere]

landing_site = []; next_room = []; this_room = []; that_room = []
#I had to make these all lists with one element because you have to
#define something before you can use it. If you want to make rooms of
#your own, then first make an empty list up here. Afterwards, you can
#append a room to it like I did.

landing_site.append(Room("Your ship crashed in a glacial room. There is only \
one way out, north.", {"north": next_room}))

next_room.append(Room("Two roads diverged in a yellow wood. East or west.",  \
{"east": this_room, "west": that_room, "south": landing_site}))

this_room.append(Room("You are trapped!", {}))

that_room.append(Room("You are trapped!", {}))

#this loop is the main game loop. The whole game happens inside of here.
#currRoom is where you are at. That stupid [0] is because I had to wrap
#all of the rooms with a list to make them work properly. I might fix
#that later, but it works for now.
currRoom = landing_site[0]
while True:
	currRoom.narrarate() #say the description of the room
	print; whatTheySay = raw_input(">>"); print
	whatTheySay = whatTheySay.split(" ") #break it into words
	if whatTheySay[0] == "go":
		c1 = (whatTheySay[1] == "north") 
		c2 = (whatTheySay[1] == "south")
		c3 = (whatTheySay[1] == "east")
		c4 = (whatTheySay[1] == "west")
		if c1 or c2 or c3 or c4:
			if currRoom.goTo(whatTheySay[1]) == None:
				print "You cannot go this way...\n"
			else:
				currRoom = currRoom.goTo(whatTheySay[1])[0]
				print "You travel %s.\n" % whatTheySay[1]
		else:
			print "That isn't a direction. Try lowercase if you think it is.\n"
	elif whatTheySay[0] == "quit":
		break
	elif whatTheySay[0] == "help":
		print "I'm sure <Python User> will put a list of commands here later. ;)"
	else:
		print "That isn't an acceptable command. Try help for a list of commands."

print "Bye!"

I kind of made it on the fly, so it doesn't have crystals or looking in rooms or anything, yet, but that can all be added later. Do you see how simple each of my rooms are compared to yours? I could add 100 custom rooms with about 200 lines of code, where you might need several thousand lines. Whether or not you use this, I hope this helps you understand a bit better. Good luck with your game.

Thanks a bunch for your class explanation and the whole example code. I have begun to rewrite my previous code using classes and thanks to you i rly understand it now. :-))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.