Advertisement
Pijomir

Man-O-War

Oct 17th, 2023
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manageBattleBetweenShips(input) {
  2.     let pirateShip = input.shift().split('>').map(Number);
  3.     let warShip = input.shift().split('>').map(Number);
  4.     let maxHealthCapacity = Number(input.shift());
  5.     for (let element of input) {
  6.         if (element === 'Retire') {
  7.             break;
  8.         }
  9.         let el = element.split(' ');
  10.         let currentCommand = el.shift();
  11.         el = el.map(Number);
  12.         switch (currentCommand) {
  13.             case 'Fire': let [index, warShipDamage] = el;
  14.                 if (warShip[index]) {
  15.                     warShip[index] - warShipDamage < 0 ? warShip[index] = 0 : warShip[index] -= warShipDamage;
  16.                 }
  17.  
  18.                 if (warShip.includes(0)) {
  19.                     console.log('You won! The enemy ship has sunken.');
  20.                     return;
  21.                 }
  22.  
  23.                 break;
  24.             case 'Defend': let [startIndex, endIndex, pirateShipDamage] = el;
  25.                 if (pirateShip[startIndex] && pirateShip[endIndex]) {
  26.                     for (let i = startIndex; i <= endIndex; i++) {
  27.                         pirateShip[i] - pirateShipDamage <= 0 ? pirateShip[i] = 0 : pirateShip[i] -= pirateShipDamage;
  28.                     }
  29.                 }
  30.                 if (pirateShip.includes(0)) {
  31.                     console.log('You lost! The pirate ship has sunken.');
  32.                     return;
  33.                 }
  34.  
  35.                 break;
  36.             case 'Repair': let [repairIndex, health] = el;
  37.                 if (pirateShip[repairIndex]) {
  38.                     pirateShip[repairIndex] + health > maxHealthCapacity ? pirateShip[repairIndex] = maxHealthCapacity : pirateShip[repairIndex] += health;
  39.                 }
  40.  
  41.                 break;
  42.             case 'Status': let allSectionsForRepair = pirateShip.filter(a => a < maxHealthCapacity * 0.2);
  43.                 console.log(`${allSectionsForRepair.length} sections need repair.`);
  44.                 break;
  45.         }
  46.     }
  47.  
  48.     let pirateShipStatus = pirateShip.reduce((a, b) => a + b, 0);
  49.     let warShipStatus = warShip.reduce((a, b) => a + b, 0);
  50.     console.log(`Pirate ship status: ${pirateShipStatus}\nWarship status: ${warShipStatus}`);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement