O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Virtual Zoo Program Code

Example 6-3 shows the code for the VirtualZoo class, the program's main class.

Example 6-3. The VirtualZoo class

package zoo {
  import flash.display.Sprite;

  public class VirtualZoo extends Sprite {
    private var pet;

    public function VirtualZoo () {
      pet = new VirtualPet("Stan");
      pet.eat(new Apple());
      pet.eat(new Sushi());
    }
  }
}

Example 6-4 shows the code for the VirtualPet class, whose instances represent pets in the zoo.

Example 6-4. The VirtualPet class

package zoo { import flash.utils.setInterval; import flash.utils.clearInterval; internal class VirtualPet { private static var maxNameLength = 20; private static var maxCalories = 2000; private static var caloriesPerSecond = 100; private var petName; private var currentCalories = VirtualPet.maxCalories/2; private var digestIntervalID; public function VirtualPet (name) { setName(name); digestIntervalID = setInterval(digest, 1000); } public function eat (foodItem) { if (currentCalories == 0) { trace(getName() + " is dead. You can't feed it."); return; } if (foodItem is Apple) { if (foodItem.hasWorm()) { trace("The " + foodItem.getName() + " had a worm. " + getName() + " didn't eat it."); return; } } var newCurrentCalories = currentCalories + foodItem.getCalories(); if (newCurrentCalories > VirtualPet.maxCalories) { currentCalories = VirtualPet.maxCalories; } else { currentCalories = newCurrentCalories; } trace(getName() + " ate some " + foodItem.getName() + "." + " It now has " + currentCalories + " calories remaining."); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required