Advertisement
dilyana2001

Untitled

Jul 9th, 2021 (edited)
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manOWar(arr) {
  2.     let pirateShip = arr.shift().split('>').map(Number);
  3.     let warShip = arr.shift().split('>').map(Number);
  4.     let maximumHC = Number(arr.shift());
  5.  
  6.     arr.forEach(row => {
  7.         let [command, ...args] = row.split(' ');
  8.         if (command == 'Retire') {
  9.             console.log(`Pirate ship status: ${pirateShip.reduce((a, b) => a + b, 0)}`);
  10.             console.log(`Warship status: ${warShip.reduce((a, b) => a + b, 0)}`);
  11.         } else if (command == 'Fire') fire(...args);
  12.         else if (command == 'Defend') defend(...args);
  13.         else if (command == 'Repair') repair(...args);
  14.         else if (command == 'Status') console.log(`${pirateShip.filter(x => x < (maximumHC * 0.2)).length} sections need repair.`);
  15.     })
  16.  
  17.     function fire(index, damage) {
  18.         index = Number(index);
  19.         damage = Number(damage);
  20.         if (index < warShip.length && index > -1) {
  21.             if (warShip[index] - damage > 0) warShip.splice(index, 1, warShip[index] - damage);
  22.             else {
  23.                 warShip[index] = 0;
  24.                 console.log(`You won! The enemy ship has sunken.`);
  25.             }
  26.         }
  27.     }
  28.  
  29.     function defend(startIndex, endIndex, damage) {
  30.         startIndex = Number(startIndex);
  31.         endIndex = Number(endIndex);
  32.         if (startIndex < pirateShip.length && startIndex > -1 && endIndex < pirateShip.length && endIndex > -1) {
  33.             for (let i = startIndex; i <= endIndex; i++) pirateShip[i] = Math.max((pirateShip[i] - Number(damage)), 0);
  34.             let setted = Array.from(new Set(pirateShip)).filter(x => x > 0);
  35.             if (setted.length == 0) console.log(`You lost! The pirate ship has sunken.`);
  36.         }
  37.     }
  38.  
  39.     function repair(index, health) {
  40.         index = Number(index);
  41.         if (index < pirateShip.length && index > -1) pirateShip[index] = Math.min((pirateShip[index] + Number(health)), maximumHC);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement