| 你现在骄傲地拥有了不是一只而是两只虚拟宠物。你的责任就 是让它们保持健康。如果它们的健康值低于零,它们就会死掉。 按start 钮可以赋予它们生命. |
|
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;
}
数据挖掘研究院
| 这个构造函数有两个参数:宠物名字和要显示其信息的表单号。 要创建两个宠物,我们这么做:
我们把构造函数写的能使每个宠物都不一样。用了 我们已建立好了属性,现在来看看方法。我并不打算把每个方 |
function feed()
{
var meal_quality = Math.random() * 2;
this.hunger = this.hunger - meal_quality;
if (this.hunger <0)
{
this.hunger = 0;
}
this.display();
}
| 这是一个喂宠物的方法。如果你调用了 pet1.feed()方法,首 先它会产生一个0到2之间的数,然后把饥饿度减去这个数。 我们确使饥饿度不小于0,然后调用显示方法去显示信息。 显示方法的代码如下: 数据挖掘研究院 |
function display()
{
var the_string = "";
if (this.health < min_health)
{
the_string = this.pet_name + " IS DEAD!";
} else {
the_string += "Happiness " + parseInt(this.happiness);
the_string += ". Health: " + parseInt(this.health);
the_string += ". Hunger: " + parseInt(this.hunger);
the_string += ". Age: " + parseInt(this.age);
the_string += ".";
}
window.document.forms[this.form_number].pet_status.value = the_string;
} 数据挖掘研究院
| This这个方法建立了一个字符串并把它显示到正确的文本框里, 表单号属性保证了状态信息放到合适的文本框。每当我们创建 一个宠物,我们就给它一个表单号 - 第一个宠物的表单号是0, 第二个宠物的表单号是1。使用这种表单号我们知道第一个宠物 的状态应放在 window.document.forms[0].pet_status.value, 而第二个宠物的状态应放在window.document.forms [1].pet_status.value. 这个方法里的最后一行根据 this.form_number决定在哪个form放状态信息. 这个方法里的另一个有趣的地方是 parseInt函数. 由于使用了 第三个有趣的方法是makeOlder().它把宠物年龄增加一岁并让 |
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();
}
| 你能看到,这个方法把宠物的年龄增加一岁,把快乐值降低了 一个随机数,把饥饿度增加了一个随机数。然后又设定了一些 规则(这儿只示意了一个),如“如果宠物真的饿极了,就让 它不快乐一点和不健康一点。 既然我们已经有了这些方法,就把它放进到构造函数里去完成 |
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();
}
数据挖掘实验室
| 最后设定让makeOlder()方法每三秒种就调用一次。这个函数 在你按动start按钮时被调用。 |
function moveTime()
{
pet1.makeOlder();
pet2.makeOlder();
the_time_out = setTimeout("moveTime();", 3000);
}
数据挖掘研究院
| 你可以看到这个函数调用了每个宠物的makeOlder()方法,并 在三秒种后又调用了它自己。这个定时事件将一直持续下去 直到用户通过clearTimeout(the_time_out)把它取消掉. 这个例子几乎用到了我们今天讲到的所有内容。如果你理 |

