1 回答
TA贡献1815条经验 获得超10个赞
对于每项费用,您必须从全局 gameData 上下文中扣除该金额...像这样:
const wood = {
name: 'Wood',
amount: 500, // Start out with enough to build stuff
}
const stone = {
name: 'Stone',
amount: 300, // Start out with enough to build stuff
}
const gameData = {
resourcesArray: [wood, stone],
}
const farm = {
name: "Farm",
amount: 0,
cost: {
'Wood': 10,
'Stone': 5,
},
}
function buyBuilding(thing = farm) {
console.log(`Time to build a ${thing.name}!`);
Object.keys(thing.cost).forEach(resource => {
const amount = thing.cost[resource];
console.log(`* This requires ${amount} ${resource}...`);
const gameResource = gameData.resourcesArray.find(r => r.name === resource);
console.log(` | You have ${gameResource.amount} ${resource} available.`);
// @TODO Check if you have enough before deducting
gameResource.amount -= amount;
console.log(` | Only ${gameResource.amount} ${resource} left now.`);
});
console.log(`New game state:`, gameData.resourcesArray);
}
// Do the actual building!
buyBuilding(farm);
添加回答
举报