Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 4

by Thau!

Page 7 — Your Object-Oriented Virtual Pet

You are now the proud owner of not one, but two virtual pets. It's your responsibility to keep them healthy. If their health drops below zero, they die. Let there be life by hitting the start button.


Name:
Status:
Name:
Status:


As you've probably guessed, I'm a tad bitter about my inadequacies as a virtual pet owner. My poor pets die young every time.

Anyway, this entire thing was programmed using objects. Each pet is an instantiation of a Pet object. Each pet has these properties:

  • health
  • happiness
  • hunger
  • age
  • pet_name
  • form_number — the HTML form the pet lives in

These properties are affected by the following methods:

  • play() — increases happiness
  • feed() — decreases hunger
  • medicate() — increases health a little bit
  • makeOlder() — makes the pet older
  • display() — displays information about the pet in the status box

So, with this in mind, let's create a Pet object. The first thing we have to do is make a constructor. Here is the basic constructor (which we'll create without the method calls for now):

function Pet(the_pet_name, the_form_number)
{
   this.age = 0;
   this.hunger = Math.random() * 5;  // random number between 0 and 4.99
   this.health = Math.random() * 5 + 1 ;  // random number between 1 and 3.99
   this.happiness = Math.random() * 5;
   this.pet_name = the_pet_name;
   this.form_number = the_form_number;
   window.document.forms[the_form_number].pet_name.value = the_pet_name;
}

This constructor takes two parameters: the name of the pet and the position of the form in which that pet should be displayed. To create two pets, we do this:

var pet1 = new Pet("barney",0);

var pet2 = new Pet("betty",1);
The constructor is written to make each virtual pet different. It uses the Math.random() method to generate random numbers between zero and one. The Math.random() method isn't perfectly random, but for our purposes it's good enough, since it does allow us to give each pet a different initial hunger, health, and happiness. The name of the pet is set to whatever name gets passed to the constructor, and the pet's age starts at zero. The last two lines set the number of the pet's form and puts the name of the new pet into the appropriate textbox. Remember that the first form on a page can be referred to as window.document.forms[0], the second form on a page is window.document.forms[1], and so on.

We have the properties; let's work on the methods. Rather than outline each method, I'll just show you a few of them to get you started:


function feed()
{
   var meal_quality = Math.random() * 2;
   this.hunger = this.hunger — meal_quality;
   if (this.hunger <0)
   {
	this.hunger = 0;
   }
   this.display();
}

This is the method used to feed the pet. If you execute the comment pet1.feed(), this method gets called. First, it generates a random number between zero and two. Then it subtracts this number from the hunger of the appropriate pet. We make sure that the hunger isn't less than zero, and then we call the display method.

The display method looks like this:

function display()
{
   var the_string = "";

   if (this.health 


This method constructs a string and displays it in the correct textbox. The form_number property drops the status information into the proper textbox. When we created each pet, we gave it a form_numberpet1 got the form number 0, and pet2 got the form number 1. Using this form_number, we know that the status of pet1 should go into window.document.forms[0].pet_status.value and the status of pet2 should go into window.document.forms[1].pet_status.value. The last line of this method determines which form to drop the status using this.form_number.

The other interesting thing in this method is the parseInt function. Thanks to the way we generated the random numbers, the values for things like health and happiness look something like this: 2.738993720. They're real numbers, but they can get pretty long. So parseInt chops off everything after the decimal point; e.g., parseInt(2.738) ends up as simply 2.

The third interesting method is makeOlder(). It ages the pet and makes it a little more hungry and a little less happy. This method gets called every second using a setTimeout, which I'll show you next. I won't go through the whole makeOlder() method, just enough to give you an idea about what it's doing.

function makeOlder()
{

   var max_hunger = 5;
   var good_happiness = 5; 

   if (this.health > min_health)
   {
			
	this.age +=1;
	this.happiness -= Math.random() * 2;
	this.hunger += Math.random() * 2;
	if (this.hunger > max_hunger)
	{
	     this.health -= Math.random() * 2;
	     this.happiness -= Math.random() * 2;
	}

   }

   this.display();
}
As you can see, the method adds one to the age of the pet, decreases its happiness, and increases its hunger by some random amount. Then a set of rules, only one of which is shown here, says, "If the pet is really hungry, make it more unhappy and less healthy."

Now that we have these methods, we will add them to the constructor to make a complete virtual pet object:

function Pet(the_pet_name, the_form_number)
{
   this.age = 0;
   this.hunger = Math.random() * 5;  // random number between 0 and 4.99
   this.health = Math.random() * 3 +1 ;  // random number between 1 and 3.99
   this.happiness = Math.random() * 5;
   this.pet_name = the_pet_name;
   this.form_number = the_form_number;

   this.feed = feed;
   this.play = play;
   this.medicate = medicate;
   this.display = display;
   this.makeOlder = makeOlder;

   window.document.forms[the_form_number].pet_name.value = the_pet_name;
   this.display();
}
The last piece of the picture is the code that sics the makeOlder() method on each pet every three seconds. This function is called when you hit the start button.
function moveTime()
{
   pet1.makeOlder();
   pet2.makeOlder();
   the_time_out = setTimeout("moveTime();", 3000);
}	
As you see, it calls makeOlder() on each pet and calls itself again one second later. After a second passes, the function gets called yet again. The pets age and the setTimeout is called. This continues until an overworked user calls clearTimeout(the_time_out).

This example utilizes almost everything we've learned to date. If you understood what's going on, you know a big heap of JavaScript. Take another break before you go on to today's last topic: using JavaScript shortcuts to get at hard-to-reach objects.

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.