victoriaSD

Man O War

Feb 17th, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manOWar(input) {
  2.   let pirateShip = input.shift().split(">").map(Number);
  3.   let warShip = input.shift().split(">").map(Number);
  4.   let maxHealth = Number(input.shift());
  5.  
  6.   for (let row of input) {
  7.     let [command, num1, num2, num3] = row.split(" ");
  8.     num1 = Number(num1);
  9.     num2 = Number(num2);
  10.     num3 = Number(num3);
  11.  
  12.     if (command === "Fire") {
  13.       let index = num1;
  14.       let damage = num2;
  15.  
  16.       if (index >= 0 && index < warShip.length) {
  17.         warShip[index] -= damage;
  18.  
  19.         if (warShip[index] <= 0) {
  20.           let end = console.log(`You won! The enemy ship has sunken.`);
  21.           return end;
  22.         }
  23.       }
  24.     } else if (command === "Defend") {
  25.       let startIndex = num1;
  26.       let endIndex = num2;
  27.       let damage = num3;
  28.  
  29.       if (
  30.         startIndex >= 0 &&
  31.         startIndex < pirateShip.length &&
  32.         endIndex >= 0 &&
  33.         endIndex < pirateShip.length
  34.       ) {
  35.  
  36.         for (let i = startIndex; i <= endIndex; i++) {
  37.           pirateShip[i] -= damage;
  38.  
  39.           if (pirateShip[i] <= 0) {
  40.             let end = console.log(`You lost! The pirate ship has sunken.`);
  41.             return end;
  42.           }
  43.         }
  44.       }
  45.     }
  46.     else if (command === "Repair") {
  47.       let index = num1;
  48.       let heal = num2;
  49.  
  50.       if (index >= 0 && index < pirateShip.length) {
  51.         pirateShip[index] += heal;
  52.  
  53.         if (pirateShip[index] > maxHealth) {
  54.           pirateShip[index] = maxHealth;
  55.         }
  56.       }
  57.     } else if (command === "Status") {
  58.       let count = 0;
  59.       let minHealth = maxHealth * 0.2;
  60.  
  61.       for (let ship of pirateShip) {
  62.        
  63.         if (ship < minHealth) {
  64.           count++;
  65.         }
  66.       }
  67.  
  68.       console.log(`${count} sections need repair.`);
  69.     }
  70.   }
  71.  
  72.   let pirateShipSum = pirateShip.reduce(
  73.     (accumulator, currentValue) => accumulator + currentValue
  74.   );
  75.   let warshipSum = warShip.reduce(
  76.     (accumulator, currentValue) => accumulator + currentValue
  77.   );
  78.  
  79.   console.log(`Pirate ship status: ${pirateShipSum}`);
  80.   console.log(`Warship status: ${warshipSum}`);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment