我造了两个功能工厂,一个是僵尸工厂,一个是人类工厂。我想要一个函数,它能区分僵尸健康和人类攻击之间的区别。它适用于每个人一人,但我无法思考如何做多个人和僵尸。我试着把人类的物体推到一个数组中,这样我就可以把所有的攻击加起来(我会重复一遍僵尸),但是没有运气.
//Create a Human spawning object
var humanArr = [];
const humanSpawns = (attack) => {
let human = {
attack: attack
};
humanArr.push(human);
};
//Create a Zombie spawning object
const zombieSpawns = (health) => {
return {
health: health
}
};
//Create function to have humans and zombies fight
function fight() {
var result = humanOne.attack - zombieOne.health;
if(result > 0) {
document.write('Live to see another day.');
} else {
document.write('The zombies are taking over!');
}
}
const zombieOne = zombieSpawns(12);
const humanOne = humanSpawns(11);
fight();发布于 2018-10-08 15:19:09
尝试类似于我的片段,您真正需要的是创建单元的方法。我使用了普通对象,但是如果您想返回casualties --比方说,您需要返回每个主对象的humanoids数组,并根据传入的伤害在战斗中对它们进行splice处理。放松点,你会看到你的军队战斗的!
--我追求的逻辑:
createHumanoid (应该将它重命名为createArmy)
1.2。createHumanoid将帮助为部队设置一些财产,其中有多少将在我的军队中。armies数组,在其中我将使用createHumanoid创建军队getArmyPower和power,这将在4.2.中使用。fight方法,并接受两个参数,一是armies,二是favoriteArmy。
4.2。使用.map方法,我将getArmyPower应用于我的每个军队(数组中的元素),以了解它们的威力。
4.3。然后我使用.sort将它们按army.power降序排序。
4.4。let victorious = armies[0];将从排序数组中获得第一个元素。拥有最高权力的人。或者您可以使用毁伤并像let [victorious] = armies;那样编写它(表示数组中的第一个元素)
4.5。我把victorious.name和favoriteArmy比较一下,看看我感兴趣的军队是赢了还是输了。
/**
* A function to create units
*/
const createHumanoid = (race, howMany, stats) => {
return {
name: race,
armySize: howMany,
unitStats: stats
}
};
/**
* Register the armies into battle
*/
let armies = [
createHumanoid('humans', 12, {
health: 10,
attack: 12
}),
createHumanoid('zombies', 5, {
health: 30,
attack: 12
}),
]
/**
* Get the max power of each army - you can adjust the algorithm
*/
const getArmyPower = (army) => {
return {
name: army.name,
power: +army.armySize * (+army.unitStats.health + +army.unitStats.attack)
}
}
/**
* Let them fight and see what your favorite army did in the battle
*/
function fight(armies, favoriteArmy) {
armies = armies
.map(army => getArmyPower(army))
.sort((a, b) => b.power - a.power);
let victorious = armies[0];
if (victorious.name.toLowerCase() === favoriteArmy.toLowerCase()) {
document.write('Live to see another day.');
} else {
document.write('The zombies are taking over!');
}
}
fight(armies, 'humans');
https://stackoverflow.com/questions/52704528
复制相似问题