Saturday, December 11, 2010

Objects and Instances

There is a very important distinction between an object and an instance of an object. An object is actually a definition, or a template for instances of that object. An instance of an object is an actual thing that can be manipulated. For instance, we could define a Person object, which may include such member data as hair color, eye color, height, weight, etc. An instance of this object could be "Dave" and Dave has values for hair color, eye color, etc. This allows for multiple instances of an object to be created. Let's go back to the medieval video game example and define the monster object.
Monster Object:
data:
   health
   skin thickness
   claws
   tail spikes
actions:
   move
   attack player with claws
   attack player with tail
END;
Now, our game could have one instance of a player:
Player Instance #1:
data:
    health = 16
    strength = 12
    agility = 14
    type of weapon = "mace"
    type of armor = "leather"
END;
and our game could have two instances of monsters:
a tough one:and a weak one:
Monster Instance #1:
data:
   health = 21
   skin thickness = 20
   claws = "sharp"
   tail spikes = "razor sharp"
END;
Monster Instance#2:
data:
   health = 9
   skin thickness = 5
   claws = "dull"
   tail spikes = "quite dull"
END;
Notice how an instance of an object contains information on member data, but holds nothing about member functions. Every instance of the Monster object performs "attack player" the same way. There is a series of steps in this member function. But each instance of the monster has its own value for the member data. In the preceding example, we can tell the two monsters in our game apart, because of their member data. One monster is tough and the other monster is weak.Let's say that we had a "Battle" function in our game. The pseudocode for it may go something like the following:
Function Battle(parameters: _player = the Player Object instance
                            _monster = the Monster Object instance)
   turn = PLAYER; 
   while ((_player's health > 0) AND (_monster's health > 0)) {
      if (turn == PLAYER){      
         player attack's monster;
         turn = MONSTER;
      }
      else {
         monster attack's player
         turn = PLAYER;
      }
   }
} // END FUNCTION Battle
In the "attack" phase, the attacking person would somehow deduct points from the defending person. Let's say that the player was fighting with the weaker monster. The weaker monster's health value is 9. If the player attacked the monster and did 5 points of damage to the monster, the monster's new health value would be 4. The monster keeps this value as its health value until it is undated again. So if the monster ran away at this point, and later in the game, the player discovered the weaker monster again, it's health value would still be 4.

No comments:

Post a Comment