Advertisement
Spocoman

03. Man O War

Nov 12th, 2023
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manOWar(input) {
  2.     let isIndexValid = (i, ship) => i >= 0 && i < ship.length,
  3.         pirateShip = input.shift().split('>').map(Number),
  4.         warShip = input.shift().split('>').map(Number),
  5.         maxSectionHealth = Number(input.shift()),
  6.         tokens, command, index, finalIndex, damage, health, count = 0;
  7.  
  8.     while (input[0] !== "Retire") {
  9.         tokens = input.shift().split(' ');
  10.         command = tokens[0];
  11.         index = Number(tokens[1]);
  12.  
  13.         if (command === "Fire" && isIndexValid(index, warShip)) {
  14.             damage = Number(tokens[2]);
  15.             warShip[index] -= damage;
  16.             if (warShip[index] <= 0) {
  17.                 console.log("You won! The enemy ship has sunken.");
  18.                 warShip = [];
  19.                 break;
  20.             }
  21.         } else if (command === "Defend") {
  22.             finalIndex = Number(tokens[2]);
  23.             if (isIndexValid(index, pirateShip) && isIndexValid(finalIndex, pirateShip)) {
  24.                 damage = Number(tokens[3]);
  25.                 for (let i = index; i <= finalIndex; i++) {
  26.                     pirateShip[i] -= damage;
  27.                     if (pirateShip[i] <= 0) {
  28.                         console.log("You lost! The pirate ship has sunken.");
  29.                         pirateShip = [];
  30.                         return;
  31.                     }
  32.                 }
  33.             }
  34.         } else if (command === "Repair" && isIndexValid(index, pirateShip)) {
  35.             health = Number(tokens[2]);
  36.             pirateShip[index] += health;
  37.             if (pirateShip[index] > maxSectionHealth) {
  38.                 pirateShip[index] = maxSectionHealth;
  39.             }
  40.         } else if (command === "Status") {
  41.             count = pirateShip.filter(x => x < maxSectionHealth / 5).length;
  42.             console.log(`${count} sections need repair.`);
  43.         }
  44.     }
  45.  
  46.     if (pirateShip.length > 0 && warShip.length > 0) {
  47.         let sum = (ship) => ship.reduce((a, b) => a + b, 0);
  48.         console.log(`Pirate ship status: ${sum(pirateShip)}`);
  49.         console.log(`Warship status: ${sum(warShip)}`);
  50.     }
  51.     return;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement