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 Review

This chapter has introduced a large number of concepts and terms. Let's practice using them by reviewing our virtual zoo program for the last time in this chapter.

Our virtual zoo game has two classes: VirtualZoo (the main class) and VirtualPet (which represents the pets in the zoo).

When our program starts, the Flash runtime automatically creates an instance of VirtualZoo (because VirtualZoo is the application's main class). The act of creating the VirtualZoo instance causes the VirtualZoo constructor method to execute. The VirtualZoo constructor method creates an instance of the VirtualPet class, with a single constructor argument, "Stan."

The VirtualPet class defines three instance variables, petName, currentCalories, and creationTime. Those three instance variables represent the following pet characteristics: the pet's nickname, the amount of food in the pet's stomach, and the pet's birth date. For a new VirtualPet object, the initial value of currentCalories is a number created using the literal expression 1000. The initial value of creationTime is a Date object representing the time at which each VirtualPet object is created. When a VirtualPet object is created, petName is assigned the value of the required constructor parameter, name. The constructor parameter name receives its value through a constructor argument, supplied by the new expression that creates the VirtualPet object.

The VirtualPet class defines two instance methods, eat( ) and getAge( ). The eat( ) method increases currentCalories by the specified numeric value. The getAge( ) method calculates and returns the pet's current age, in milliseconds.

Example 1-2 displays the current code for our zoo program.

Example 1-2. Zoo program

// VirtualPet class
package zoo {
  internal class VirtualPet {
    internal var petName;
    private var currentCalories = 1000;
    private var creationTime;

    public function VirtualPet (name) {
      this.creationTime = new Date();
      this.petName = name;
    }

    public function eat (numberOfCalories) {
      this.currentCalories += numberOfCalories;
    }

    public function getAge () {
      var currentTime = new Date();
      var age = currentTime.time - this.creationTime.time;
      return age;
    }
  }
}

// VirtualZoo class
package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo () {
      this.pet = new VirtualPet("Stan");
    }
  }
}

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