Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Oct 3rd, 2007, 6:57 PM   #11
Jabo
Not a user?
 
Join Date: Sep 2007
Posts: 228
Rep Power: 1 Jabo is on a distinguished road
Another important aspect of OOP is polymorphism, or function overloading. It can save a lot of typing.
Jabo is online now   Reply With Quote
Old Oct 3rd, 2007, 8:04 PM   #12
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
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
DaWei is offline   Reply With Quote
Old Oct 4th, 2007, 6:57 AM   #13
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
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)
  1. class Room:
  2. def __init__(self, name, description):
  3. self.name = name
  4. self.description = description
  5.  
  6. def examine(self, player):
  7. return self.name + "\n\n" + self.description
Obviously incomplete, but the beginnings of something potentially useful. Note that the Room class groups together the room's name and its description, and gives us a method by which a player can examine the room.

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)
  1. class DarkRoom(Room):
  2. def examine(self, player):
  3. if player.has_light_source:
  4. return Room.examine(self, player)
  5. else:
  6. return "Darkness\n\nIt is dark. You are likely to be eaten by a grue."
Now, the most important thing to realise is that both Room and DarkRoom implement a standard "examine" function. We don't need to know whether a room is a normal lit Room, or an unlit DarkRoom, as that's all taken care of inside the class. Thus, our main game loop might look something like this:

python Syntax (Toggle Plain Text)
  1. while True:
  2. current_room.examine(player)
  3. process_input(raw_input("> "))
In a program that wasn't object orientated, we'd have to put in some sort of if statement to check whether a room was dark, but in an object orientated program, that is factored out into the object. The current_room could be lit, unlit, or underwater, or whatever - so long as it has the "examine" function, Python doesn't care.

Does that help you understand the power of OOP in tackling certain problems?
Arevos is offline   Reply With Quote
Old Oct 4th, 2007, 9:47 AM   #14
nisim777
Newbie
 
Join Date: May 2005
Posts: 17
Rep Power: 0 nisim777 is on a distinguished road
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.
nisim777 is offline   Reply With Quote
Old Oct 4th, 2007, 12:29 PM   #15
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
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)
  1. class Item:
  2. def on_pickup(self, creature):
  3. pass
  4.  
  5. class Creature:
  6. def pickup(self, item):
  7. self.inventory.append(item)
  8. item.on_pickup(self)
  9.  
  10. class MundaneObject(Item):
  11. pass
  12.  
  13. class AncientTreasure(Item):
  14. def on_pickup(self, creature):
  15. creature.send_message("The temple begins to collapse!")
If a creature happens to pick up the mundane object, nothing untoward will happen. But if a creature happens to take the ancient treasure, a custom message is displayed.
Arevos is offline   Reply With Quote
Old Oct 4th, 2007, 12:40 PM   #16
nisim777
Newbie
 
Join Date: May 2005
Posts: 17
Rep Power: 0 nisim777 is on a distinguished road
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.
nisim777 is offline   Reply With Quote
Old Oct 4th, 2007, 1:05 PM   #17
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
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.
Arevos is offline   Reply With Quote
Old Oct 4th, 2007, 2:44 PM   #18
nisim777
Newbie
 
Join Date: May 2005
Posts: 17
Rep Power: 0 nisim777 is on a distinguished road
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. ")
nisim777 is offline   Reply With Quote
Old Oct 5th, 2007, 12:51 PM   #19
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
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)
  1. class Room:
  2. def __init__(self, description):
  3. self.description = description
  4. self.exits = {}
A class is like a template. We can use this template to create more specific objects:

python Syntax (Toggle Plain Text)
  1. foyer = Room("You are in the foyer of the house...")
  2. kitchen = Room("You step into a dark kitchen...")
  3.  
  4. foyer.exits["west"] = kitchen
  5. kitchen.exits["east"] = foyer
In order to interact with these objects, we need a player:

python Syntax (Toggle Plain Text)
  1. class Player:
  2. def __init__(self, room):
  3. self.room = room
  4.  
  5. def look(self):
  6. print self.room.description
  7.  
  8. def move(self, direction):
  9. self.room = self.room.exits[direction]
  10.  
  11. me = Player(foyer)
Now we have two classes (Room and Player), and three objects (foyer, kitchen and me). The neatest thing about this arrangement is that we can actually play the game via Python's interactive interpreter:

>>> 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...
Okay, so eventually we'd need to create our own command handler (so we could type "look" rather than "me.look()"), but you can see that the functionality is already there. In fact, we can play and debug the game at the same time:
>>> 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'
Oops! Looks like we could use some better error handling in the "move" function:
python Syntax (Toggle Plain Text)
  1. def move(self, direction):
  2. if direction in self.room.exits:
  3. self.room = self.room.exits[direction]
  4. else:
  5. print "You cannot go in that direction!"
Now let's try the interactive interpreter:
>>> me.move("up")
You cannot go in that direction!
Much better! Essentially, try representing physical things, such as rooms and items, as Python objects, and try representing commands, such as "look" and "move", as methods.
Arevos is offline   Reply With Quote
Old Oct 5th, 2007, 11:45 PM   #20
nisim777
Newbie
 
Join Date: May 2005
Posts: 17
Rep Power: 0 nisim777 is on a distinguished road
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.
nisim777 is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

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




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 3:15 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC