gpt4 book ai didi

JavaScript 虚拟宠物

转载 作者:行者123 更新时间:2023-11-28 19:15:04 26 4
gpt4 key购买 nike

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

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 功能正在运行。但是,我仍然不确定为什么显示未定义。现在,我创建了一个名为 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 功能不起作用。我真的只是希望我的控制台能够清晰地显示:姓名:饥饿:健康:幸福:大家有什么想法吗?

最佳答案

例如,feed 方法可以是:

function feed(amountOfFood){
this.hunger += amountOfFood; //Same as this.hunger = this.hunger + amountOfFood;
}

然后,您可能会找到一种由用户调用此方法的方法,但我不确定您计划如何让用户与游戏交互,因此无法解释更多...

关于JavaScript 虚拟宠物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com