In this recipe, we'll create a Model class which is responsible for initializing and updating the hero, the bad guys, the level, and the health bar. These objects can be seen as the "data" of our game.
Follow these steps to create the model for Canvas Hero:
Define the
Model
constructor:/* * Game model * * The model is responsible for initializing and * updating the hero, level, bad guys, and health bar */ function Model(controller){ this.controller = controller; this.healthBar = null; this.hero = null; this.level = null; this.badGuys = []; // array of bad guys this.heroCanvasPos = {}; }
Define the
removeDefeatedBadGuys()
method which loops through the bad guy array and then removes the ones that are no longer alive:Model.prototype.removeDefeatedBadGuys = function(){ for (var n = 0; n < this.badGuys.length; n++) { var badGuy = this.badGuys[n]; if (!badGuy.alive && badGuy.opacity == 0) { ...