我正在制作一个闲置游戏库供我使用,我不确定如何创建一个系统,该系统需要成对的资源和数量,检查它们是否可用,如果可用,则调整所有值。访问上述资源并将它们放入一个对象中以传递给 Building() 是相当困难的。
我需要做的是从
player.resources
中对象内的方法获取 player.building
中的资源,其中包含每种资源的数量。
我想将所有这些信息传递到一个 new class Building()
对象中,如下所示:
// Inside player.buildings
purple: new Building(0, "#purple", /*data goes here*/)
class Building extends Thing(){
constructor(amount, tag, requirements){
super(amount, tag)
this.requirements = requirements
/*
This is roughly the shape of the input. It is the reference to the resources and the respective amounts needed.
requirements = {
player.resources.red: 5,
player.resources.blue: 92,
}
*/
}
buy(){
// Check if each of the required resources are avaliable
for(let resource of this.requirements){
if(resource.amount >= resource.needed){
continue
}else{
//Break the loop and return false, signaling that you cant buy this right now.
return false
}
}
// If you can buy it then go through each of the required resources and decrement them.
for(let resource of this.requirements){
resource.amount -= resource.needed
}
this.amount += 1
}
}
对于上下文,事物或资源具有以下结构:
resource:{
amount: x,
tag: "#tag", //Used for rendering on the page
}
玩家对象具有这样的结构
player:{
resources:{
red: {
amount: 3,
tag: "#red"
},
blue: {
amount: 4,
tag: "#blue"
},
buildings:{
purple: {
amount: 0,
tag: "#purple",
requirements: "data structure",
}
},
}
调用buy函数时可以传入player对象。 然后用你之前的逻辑,你可以检查玩家是否有足够的资源,然后扣除它们。 这里我也将建筑物添加到玩家的“建筑物”对象中作为示例。
class Thing {
constructor(amount, tag){
this.amount = amount;
this.tag = tag;
}
}
class Building extends Thing {
constructor(amount, tag, requirements){
super(amount, tag)
this.requirements = requirements;
}
buy(player){
// Check if each of the required resources are avaliable
for (let [type, amount] of Object.entries(this.requirements)) {
if(player.resources[type].amount >= amount){
continue
}else{
return false
}
}
// If you can buy it then go through each of the required resources and decrement them.
for (let [type, amount] of Object.entries(this.requirements)) {
player.resources[type].amount -= amount;
}
this.amount += 1;
// do something with this building (add it to the player's "buildings" property, for example)
player.buildings[this.tag] = this;
return true;
}
}
const logCabin = new Building(0, "log cabin", {red: 1, blue: 1});
const player1 = {
resources:{
red: {
amount: 3,
tag: "#red"
},
blue: {
amount: 4,
tag: "#blue"
}
},
buildings:{}
};
let result = logCabin.buy(player1);
console.log(result);
console.log(player1);