我正在尝试使用 JS 编写一个简单的文本 RPG,我想执行以下操作:
我有两个对象:Player 和 Item。 “药水”是物品的一种实例,使用时会增加玩家 30 点生命值。
我正在使用以下代码,它工作正常,但我想知道是否有一种“更好”的方法来执行此操作而不使用“eval”。请注意,Item 实例中的“ef”键必须指定它影响 Player 的哪些键以及它必须执行的操作。
class Player {
constructor(a={}) {
this.na = a.na
this.st = {hp: 100, atk: 10, def: 10, en: 50}
}
}
class Item {
static potion = new this({
na: "Potion",
ef: ['st.hp', '+= 30']
})
constructor(a={}) {
this.na = a.na
this.ef = a.ef ?? []
}
use(target) {
eval(`target.${this.ef[0]} ${this.ef[1]}`)
}
}
const me = new Player({na: "Azmuth"})
Item.potion.use(me)
console.log(me)
抱歉英语/解释不好,提前谢谢你。
我建议在玩家类中处理应用项目,因为它有更多关于自身的信息来正确分配值,而且将数据存储为数组也不是很好,只需使用单独的属性即可。你可以引入负面
class Player {
constructor(a={}) {
this.na = a.na
this.st = {hp: 100, atk: 10, def: 10, en: 50}
}
useItem(item){
const {key, value} = item;
let node = this;
const path = key.split('.');
const valKey = path.pop();
for(const k of path){
node = node[k] ??= {};
}
node[valKey] += value;
}
}
class Item {
static potion = new this({
na: "Potion",
key: 'st.hp',
value: 30
})
constructor(a = {}) {
return a;
}
}
const me = new Player({na: "Azmuth"})
me.useItem(Item.potion);
console.log(me)