![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#11 |
|
Not a user?
Join Date: Sep 2007
Posts: 228
Rep Power: 1
![]() |
Another important aspect of OOP is polymorphism, or function overloading. It can save a lot of typing.
|
|
|
|
|
|
#12 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Actually, it isn't an old thread. It started yesterday. As I stated in the material I linked to, I though polymorphism was a cross-dressing parrot. Oh well. I'll get it, one day.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#13 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
Object orientation is more a philosophy than a certain piece of language functionality. Objects group together related functions and objects into a single package, allowing the developer to organise their programs more effectively, and to factor out common behavior. Certain tasks lend themselves more to OOP than others; GUIs and games are two major areas where OOP is often advantageous.
I'll provide a quick example using your adventure game idea, nisim777. In an adventure game, you typically have a set of rooms. These can be represented by a Room class: python Syntax (Toggle Plain Text)
However, in quite a few early adventure games, you also had rooms that were dark unless the player had a light source, such as the inside of a cave. These types of rooms can be thought of as a subclass of our normal "lit" rooms: python Syntax (Toggle Plain Text)
python Syntax (Toggle Plain Text)
Does that help you understand the power of OOP in tackling certain problems? |
|
|
|
|
|
#14 |
|
Newbie
Join Date: May 2005
Posts: 17
Rep Power: 0
![]() |
Thanks all. I'm still working on understanding the inner workings of objects, but this has helped thus far. Arevos, from your example, I can definitely see the use, even if I don't understand how the small snippets would fit into the larger program. I'll play around with it.
|
|
|
|
|
|
#15 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
Perhaps you should try designing a simple adventure game in the procedural style you're used to, then to try designing an identical game using an object orientated philosophy. This will give you an idea of the advantages of OO in a wider context.
OO is largely about common interfaces. Rooms, items and NPCs might all have "examine" functions. Rooms, NPCs and some other containers (such as chests) might have "add_item" functions. You can also add unused functions to classes that act as "triggers" or events: python Syntax (Toggle Plain Text)
|
|
|
|
|
|
#16 |
|
Newbie
Join Date: May 2005
Posts: 17
Rep Power: 0
![]() |
I have the procedural game designed. That is actually what made me start this topic. I was trying to figure out how to turn it into an OO game. I'll give it a shot and see how it goes. I think my main problem is in understanding the syntax of OOP. I'll figure it out though. Thanks for the help.
|
|
|
|
|
|
#17 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
If you want to post the procedural code up somewhere, I'm sure there are a few developers here on the forums who could come up with some good suggestions about a OO redesign.
|
|
|
|
|
|
#18 |
|
Newbie
Join Date: May 2005
Posts: 17
Rep Power: 0
![]() |
re:
Here is what I have coded so far. The rest of the game is designed out, just not coded yet. Also, the stuff at the end of my code in the kitchen() function is something I am just playing with. The plan is to make a gameover function that will handle this stuff, I just threw it in there to test it on a whim.
I have no character creation yet. Wasn't really planning on it, but it seems like OOP was built for things like that, so I may add it for practice. Here's the code: # Collection Notice
import random
global souls
global encounter
global foySoul
global encounterCount
souls = 0
encounter = 0
foySoul = 0
def help1():
print """
Type (without the qoutes):
'look' to see the room description again.
'examine (object)' to examine an object.
'take (item)' to take an item.
'use (item)' activates and uses items such as lightswitches.
"""
def start():
print """
Collection Notice v.1.0
"Life is the jailer, death the angel sent to draw the unwilling bolts
and set us free."
- James Russell Lowell
You are a soul collector. You are charged to see that the dying have an
uneventful transition into the next life. Because Death is not omnipotent,
those mortals indebted to him serve as collectors.
The Angel of Death has informed you that tonight's task shall be enough
to repay your debt in full.
You stand before an expansive mansion and note to yourself that it
would better be labled a compound. As you step into the front door
you already know what to expect. Fifty seven people have been massacred
on this night. You are here to find and collect their souls.
"""
raw_input("Press enter to continue: ")
foyer()
def foyer():
global souls
global foySoul
global encounterCount
print """
You are in the foyer of the house. The air is thick with death here.
Humidity has already caught the death stench and it permeates the house.
The house is dark. On the wall beside the entrance is a light switch.
Directly in front of you is a passage way leading deeper into the house.
At the far end of the passage way is a window, which allows a bit of
moonlight to shine into the darkness. On the left and right sides of the
hallway are small tables. Sitting on the right-hand table is the smiling
head of an elderly man, and he seems to be looking at you.
"""
raw_input("Press enter to continue: ")
print """
As you look around the foyer you notice a dark shape in the corner.
AS you slowly walk toward the shape, the face of a small girl dips
into the dim light of the moon from the doorway. You start back,
suprised to see anyone alive in this house.
"Who are you?" You say.
The little girl smiles at you.
"Yours shall be mine, Soul Collector." Her voice is a mix of an
innocent child, and innocence defiled - a growling demonic voice.
She smiles again and melts into the shadows.
"""
print "Your exits are n, s, e, w"
foy_prompt()
def foy_prompt():
global souls
global foySoul
choice = raw_input("What would you like to do? ").lower()
if choice == "s":
if souls < 57:
print "You cannot leave this place until you have collected all souls."
foy_prompt()
elif choice == "n":
intersection()
elif choice == "w":
kitchen()
elif choice == "e":
den()
elif choice == "use lightswitch":
print "The light above you flickers for a moment then explodes in a"
print "shower of sparks."
foy_prompt()
elif choice == "examine head":
if foySoul == 0:
print "As you peer into the eyes of the decapetated head, you see"
print "the tiny shimmering light of a soul lingering deep within."
foy_prompt()
else:
print "The soul is gone. It is now just a bloody head."
foy_prompt()
elif choice == "take soul":
if foySoul == 0:
foySoul = 1
print "You reach into the head and grap the wisp of soul."
souls = souls + 1
print "You now have", souls, "souls."
foy_prompt()
else:
print "You have already collected this soul."
elif choice == "help":
help1()
foy_prompt()
elif choice == "examine":
print "Examine what?"
foy_prompt()
else:
print "That is an invalid choice. Try something else."
foy_prompt()
def kitchen():
global encounterCount
global souls
global kitchenSouls
print """ You step into a dark kitchen. An dim emergency light is
glowing above the stove, casting a yellow tint across the room. In the
center of the kitchen is a small island counter, upon which is a bloody
knife. The body of a middle-aged man is slumped against the island. There
is a low hum coming from the garbage disposal in the sink. On the wall is
an magnetic strip holding a number of knives.
"""
encounter = random.randrange(100) + 1
encounterChance = 0
if (encounter <= 50) and (encounterChance == 0):
encounterChance = 1
if encounterCount != 9:
print """ For a brief moment the light in the room seems to grow
brighter. A large knife jumps from the knife strip on the wall and
sails toward you. You lunge out of the way just in time, but it still
slices into your arm. As you stand up you hear the laughter of a little
girl.
"""
else:
print """ You feel a cold hand crawling across your back. As you
turn confront the owner of said had you are paralyzed as the hand
reaches into your body. You can feel it grasp your soul, tugging.
"I told you your's would be mine." The breath of the little girl
is hot on the knape of your neck.
"I am darker than death, and his shall be mine soon."
The girl gives a final tug and all goes dark.
"""
raw_input("Press enter to continue: ")
print """ When you awaken you know you are different. You have of
those with your condition. You are a Souless. You cannot die,
because Death's punishment to those with no soul is unfathomable.
You are forced to walk to earth forever, feasting upon the souls of
the living to remain alive. You know that you will struggle with
this at first, but survival will override that struggle. But
eventually, all Souless learn to enjoy the deaths - just like the
little girl who enjoyed yours.
You have lost
Game Over"""
encounterCount += 1
print "Your exits are to the e and w."
raw_input("What would you like to do? ")
kit_prompt()
# encounter = random.randrange(100) + 1
# encounterChance = 0
# if (encounter <= 80) and (encounterChance == 0):
# encounterChance = 1
start()
raw_input("Press enter to exit. ") |
|
|
|
|
|
#19 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
It's my belief that you're thinking a little too directly, nisim777. You've created some code to build a specific adventure game, when what you really want to do is to take a step back and consider the problem more generally.
You've divided each room into a specific function, but since each room will have many common attributes, I think you'll find that as your program grows more complex, you'll find yourself repeating yourself more and more. Instead of beginning by building a specific room like a kitchen or a foyer, start by considering the behaviour of a generic room. python Syntax (Toggle Plain Text)
python Syntax (Toggle Plain Text)
python Syntax (Toggle Plain Text)
>>> me.look()
You are in the foyer of the house...
>>> me.move("west")
>>> me.look()
You step into a dark kitchen...
>>> me.move("east")
>>> me.look()
You are in the foyer of the house...>>> me.move("up")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
me.move("up")
File "C:/Python25/t.py", line 20, in move
self.room = self.room.exits[direction]
KeyError: 'up' python Syntax (Toggle Plain Text)
>>> me.move("up")
You cannot go in that direction! |
|
|
|
|
|
#20 |
|
Newbie
Join Date: May 2005
Posts: 17
Rep Power: 0
![]() |
re:
Here is what I've done with what you have given me, thus far:
class Room(object):
def __init__(self, description):
self.description = description
self.exits = {}
class Player(object):
def __init__(self, room):
self.room = room
def look(self):
print self.room.description
def move(self, direction):
if direction in self.room.exits:
self.room = self.room.exits[direction]
me.look()
else:
print "You cannot go in that direction."
foyer = Room("You are in the foyer of a house...")
kitchen = Room("You are in a dark kitchen...")
foyer.exits["west"] = kitchen
kitchen.exits["east"] = foyer
me = Player(foyer)
while True:
choice = raw_input("What would you like to do? ").lower()
if choice == "look":
me.look()
elif choice == "n":
me.move("north")
elif choice == "w":
me.move("west")
elif choice == "e":
me.move("east")
elif choice == "s":
me.move("south")I'll keep you posted on my progress. The next thing I am going to work on is an items class so the user can examine certain things in a room. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Learning old languages | Wizard1988 | Coder's Corner Lounge | 26 | Sep 16th, 2007 10:10 PM |
| OOP design question | rwm | C++ | 7 | May 28th, 2007 2:46 AM |