Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function manOWar(input) {
- let isIndexValid = (i, ship) => i >= 0 && i < ship.length,
- pirateShip = input.shift().split('>').map(Number),
- warShip = input.shift().split('>').map(Number),
- maxSectionHealth = Number(input.shift()),
- tokens, command, index, finalIndex, damage, health, count = 0;
- while (input[0] !== "Retire") {
- tokens = input.shift().split(' ');
- command = tokens[0];
- index = Number(tokens[1]);
- if (command === "Fire" && isIndexValid(index, warShip)) {
- damage = Number(tokens[2]);
- warShip[index] -= damage;
- if (warShip[index] <= 0) {
- console.log("You won! The enemy ship has sunken.");
- warShip = [];
- break;
- }
- } else if (command === "Defend") {
- finalIndex = Number(tokens[2]);
- if (isIndexValid(index, pirateShip) && isIndexValid(finalIndex, pirateShip)) {
- damage = Number(tokens[3]);
- for (let i = index; i <= finalIndex; i++) {
- pirateShip[i] -= damage;
- if (pirateShip[i] <= 0) {
- console.log("You lost! The pirate ship has sunken.");
- pirateShip = [];
- return;
- }
- }
- }
- } else if (command === "Repair" && isIndexValid(index, pirateShip)) {
- health = Number(tokens[2]);
- pirateShip[index] += health;
- if (pirateShip[index] > maxSectionHealth) {
- pirateShip[index] = maxSectionHealth;
- }
- } else if (command === "Status") {
- count = pirateShip.filter(x => x < maxSectionHealth / 5).length;
- console.log(`${count} sections need repair.`);
- }
- }
- if (pirateShip.length > 0 && warShip.length > 0) {
- let sum = (ship) => ship.reduce((a, b) => a + b, 0);
- console.log(`Pirate ship status: ${sum(pirateShip)}`);
- console.log(`Warship status: ${sum(warShip)}`);
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement