JavaScript基于文本的宠物游戏

时间:2015-05-05 03:04:17

标签: javascript function properties constructor

我正在尝试创建一个基于文本的虚拟宠物护理游戏。我希望能够通过修改对象属性为您提供两只宠物(具有属性的对象)和与这些对象交互的函数。所以这就是我所拥有的:

function Pet(pet_name){
    this.pet_name = pet_name;
    this.pet_hunger = Math.floor((Math.random() * 10) + 1);
    this.pet_health = Math.floor((Math.random() * 10) + 1);
    this.pet_happiness = Math.floor((Math.random() * 10) + 1);

    this.feed = feed;
    this.show = show;
}

pet1 = new Pet("Brian");
pet2 = new Pet("Lassy");

function feed(){
    var amount = Math.floor((Math.random() *2) + 1);
    this.pet_hunger = this.pet_hunger - amount;
    if (this.pet_hunger < 0){
        this.pet_hunger = 0;
    }
    this.show();
 }

function show(){
    var the_string = "";
    if (this.pet_health === 0){
        the_string = this.pet_name + " is dead!";
    }
    else {
        the_string += "Name: " + this.pet_name;
        the_string += "Hunger: " + this.pet_name;
        the_string += "Health: " + this.pet_health;
        the_string += "Happiness: " + this.pet_happinesss;
    }
}

当我运行代码时:

console.log(pet1);
console.log(pet1.feed());  
console.log(pet1);

我收到以下内容:

{ pet_name: 'Brian',
  pet_hunger: 4,
  pet_health: 4,
  pet_happiness: 10,
  feed: [Function: feed],
  show: [Function: show] }
undefined
{ pet_name: 'Brian',
  pet_hunger: 2,
  pet_health: 4,
  pet_happiness: 10,
  feed: [Function: feed],
  show: [Function: show] }

所以我们可以看到feed函数正在运行。但是,我仍然不确定为什么undefined会显示。现在,我创建了一个名为show的函数。这应该整齐地显示四个人的统计数据(名字,饥饿,健康,幸福)。但是,当我尝试运行时:

console.log(pet1.show);
console.log(pet1.feed());
console.log(pet1);

我收到以下内容:

[Function: show]
undefined
{ pet_name: 'Brian',
  pet_hunger: 4,
  pet_health: 1,
  pet_happiness: 9,
  feed: [Function: feed],
  show: [Function: show] }

我不确定为什么我的show功能不起作用。我真的只是希望我的控制台能够干净利落地显示出来:姓名:饥饿:健康:幸福:任何有想法的人?

1 个答案:

答案 0 :(得分:2)

您正在获取undefined,因为当您执行代码时,浏览器将记录函数的返回值。由于您没有指定return,因此函数返回undefined,这就是控制台记录的内容。

如果你想在show函数中返回该字符串,你必须......好吧,返回字符串:

// ...

function feed(){
    var amount = Math.floor((Math.random() *2) + 1);
    this.pet_hunger = this.pet_hunger - amount;
    if (this.pet_hunger < 0){
        this.pet_hunger = 0;
    }
    return this.show();
}

function show(){
    var the_string = "";
    if (this.pet_health === 0){
        the_string = this.pet_name + " is dead!";
    }
    else {
        the_string += "Name: " + this.pet_name + ", ";
        the_string += "Hunger: " + this.pet_hunger + ", ";
        the_string += "Health: " + this.pet_health + ", ";
        the_string += "Happiness: " + this.pet_happiness;
    }
    return the_string;
}

console.log(pet1.show()); 
// Logs 'Name: a, Hunger: b, Health: c, Happiness: d'

你也有一些错别字(在纠正之前,你的宠物的幸福是undefined,哈),所以我纠正了它们,并用逗号分隔了字符串中的每个属性,你可以改变它。