Thread: Why OOP?
View Single Post
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: 5 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