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

Using Functions in the Virtual Zoo Program

Let's apply our new knowledge of functions to our virtual zoo program. (For a refresher on our program's existing code, see the VirtualPet class in Example 4-1 in Chapter 4.)

Recall that when we last saw our virtual zoo program, pets had the ability to eat (i.e., gain calories), but not to digest (i.e., lose calories). To give our pets the ability to digest, we'll add a new method to the VirtualPet class, named digest( ). The digest( ) method will subtract calories from the VirtualPet object on which it is invoked. To simulate digestion over time, we'll create an interval that invokes digest( ) once per second. The amount of calories consumed at each digest( ) invocation will be determined by a new static variable, caloriesPerSecond. By default, we'll set caloriesPerSecond to 100, allowing a pet to survive a maximum of 20 seconds on a "full stomach."

The following code shows the caloriesPerSecond variable definition:

private static var caloriesPerSecond = 100;

The following code shows the digest( ) method. Notice that because digestion is an internal task, digest( ) is declared private.

private function digest () {
  currentCalories -= VirtualPet.caloriesPerSecond;
}

To create the interval that invokes digest( ) once per second, we use the built-in setInterval( ) function. Each pet should start digesting as soon as it is created, so we'll put our setInterval( ) call in the VirtualPet constructor method. We'll also store setInterval( )'s returned ...

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