【发布时间】:2020-10-10 10:26:52
【问题描述】:
我正在使用 Javascript 构建基于文本的选择 RPG 游戏。我可以在对象中添加函数并运行它们,但是,如果选择了选项(文本节点),我希望函数运行。
目前,我声明一个函数,然后在页面底部调用它。问题是,我希望在选择选项后立即运行。
这是我到目前为止的代码......
function addRadiatedStatus(){
character.radiated = true;
}
const textNodes = [
{
id: 1,
text: "Do you want to help this person?",
options: [
{
text: "Yes",
nextText: 2
},
{
text: "No",
nextText: 2
},
],
faction: "Greaser"
},
{
id: 2,
text: "It was a trap, do you run or kill them?",
options: [
{
text: "Run",
nextText: 3,
damage: 0,
},
{
text: "Kill",
nextText: 5,
damage: 8,
moneyDrop: 20,
radiationDamage: 2,
function: function update(){
if(character.greaser == true && textNodes[1].faction ==
"greaser"){
console.log("greaser check worked");
}
console.log("upadte function worked")
character.health -= this.damage;
character.cash += this.moneyDrop;
character.radiationLevel += this.radiationDamage;
character.maxHP -= this.radiationDamage;
if(this.radiationDamage >= 1 ){
addRadiatedStatus();
}
console.log("character HP" + " " + character.health);
console.log("character maxHP" + " " + character.maxHP);
console.log("moneyDrop " + " " + this.moneyDrop);
console.log("character cash" + " " + character.cash);
console.log("radiation level" + " " + character.radiationLevel);
console.log("character Raditated?" + " " + character.radiated);
}
}
],
faction: "Greaser",
}
]
textNodes[1].options[1].function();
我尝试了一些不同的方法,包括添加另一个密钥 run: update()、run: this.update()、run: this.function 等。
我也有点困惑,因为我认为 ES6 允许我删除 function 关键字,但这似乎是不允许的(我可能只是做错了,或者基于如何我设置了我的对象)。
我不确定如何从调用 textNodes[1].options[1].function 到动态调用嵌套在特定选项选项中的任何函数。
提前感谢您的帮助。
【问题讨论】:
标签: javascript function oop