HTML and CSS Reference
In-Depth Information
Q.Loot = Q.Sprite.extend({
init: function(props) {
sheet: 'items',
frame: Math.floor(Math.random() * 30 * 9) + 150,
z: 10,
gold: Math.floor(Math.random() * 100)
interact: function(data) {
In each case the sprite consists of an init constructor function that sets up the object's properties and binds
to the aforementioned interact method. Because each of the sprites are also selectively unhidden when the
player is near, each is also hidden at the start.
The interact method for each of the elements is where the interesting behavior occurs. In the case of the
Q.Enemy class, the user is viewed to be attacking the enemy when they interact. (This seems reasonable. Do
you normally ask enemies for directions?) The method reduces the enemy's health by the passed-in amount and
either dies a quick death or attacks the player. If the enemy dies, it triggers an xp (experience point) event on the
player, which could be used to level-up the player. The attack also triggers a health event on the enemy, which
is used in the next section to update a health bar.
The interact method for the Q.Fountain class calls a heal method on the player to restore some
amount of health to the player. Finally, the Q.Loot class triggers a gold event on the player.
By binding to an event in each case rather than calling a specific method on the destination, the source and
recipient are uncoupled, meaning that one doesn't need to know anything about the other and that interdepend-
encies are reduced. It also means that components can easily hook into the system to add additional functionality
to the core sprite behaviors.
For the player to interact with other elements, the class needs to be extended to handle collision and attack
events. It also needs an interact method to handle when it is attacked by an enemy.
Modify the Q.Player class to match the code in Listing 13-11 .
Listing 13-11: The modified player sprite
Q.Player = Q.Sprite.extend({
init: function(props) {
sheet: 'characters',
frame: 65,
wait: 0,
Search WWH ::

Custom Search