TZinovieva

Man-O-War JS Fundamentaks

Feb 15th, 2023
123
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.  
  7.     for (let i = 0; i < input.length; i++) {
  8.         let commands = input[i].split(' ');
  9.         let command = commands[0];
  10.         let values = commands.slice(1).map(x => Number(x));
  11.  
  12.         switch (command) {
  13.             case "Fire": fire(warShip, values[0], values[1]); break;
  14.             case "Defend": defend(pirateShip, values[0], values[1], values[2]); break;
  15.             case "Repair": repair(pirateShip, values[0], values[1], maxHealth); break;
  16.             case "Status": status(pirateShip, maxHealth); break;
  17.             case "Retire": {
  18.                 console.log(`Pirate ship status: ${pirateShip.reduce((a, c) => a + c, 0)}`);
  19.                 console.log(`Warship status: ${warShip.reduce((a, c) => a + c, 0)}`);
  20.                 break;
  21.             }
  22.         }
  23.         if (isShipDead(warShip)) {
  24.             console.log(`You won! The enemy ship has sunken.`);
  25.             break;
  26.         }
  27.         if (isShipDead(pirateShip)) {
  28.             console.log(`You lost! The pirate ship has sunken.`);
  29.             break;
  30.         }
  31.     }
  32.  
  33.     function isShipDead(ship) {
  34.         let deadSections = ship.filter(x => x <= 0);
  35.         return deadSections.length > 0;
  36.     }
  37.  
  38.     function fire(warShip, index, damage) {
  39.         if (index >= 0 && index < warShip.length) {
  40.             warShip[index] -= damage;
  41.         }
  42.     }
  43.  
  44.     function defend(warShip, startIndex, endIndex, damage) {
  45.         if (startIndex >= 0 && startIndex < warShip.length && endIndex >= 0 && endIndex < warShip.length) {
  46.             for (let i = startIndex; i <= endIndex; i++) {
  47.                 warShip[i] -= damage;
  48.             }
  49.         }
  50.     }
  51.  
  52.     function repair(ship, index, heal, maxHealth) {
  53.         if (index >= 0 && index < ship.length) {
  54.             let missingHealth = maxHealth - ship[index];
  55.             ship[index] += Math.min(missingHealth, heal);
  56.         }
  57.     }
  58.  
  59.     function status(ship, maxHealth) {
  60.         let damagedSections = ship.filter(x => x < (maxHealth * 0.2));
  61.         console.log(`${damagedSections.length} sections need repair.`);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment