Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function manOWar(input) {
- let pirateShip = input.shift().split(">").map(Number);
- let warShip = input.shift().split(">").map(Number);
- let maxHealth = Number(input.shift());
- for (let row of input) {
- let [command, num1, num2, num3] = row.split(" ");
- num1 = Number(num1);
- num2 = Number(num2);
- num3 = Number(num3);
- if (command === "Fire") {
- let index = num1;
- let damage = num2;
- if (index >= 0 && index < warShip.length) {
- warShip[index] -= damage;
- if (warShip[index] <= 0) {
- let end = console.log(`You won! The enemy ship has sunken.`);
- return end;
- }
- }
- } else if (command === "Defend") {
- let startIndex = num1;
- let endIndex = num2;
- let damage = num3;
- if (
- startIndex >= 0 &&
- startIndex < pirateShip.length &&
- endIndex >= 0 &&
- endIndex < pirateShip.length
- ) {
- for (let i = startIndex; i <= endIndex; i++) {
- pirateShip[i] -= damage;
- if (pirateShip[i] <= 0) {
- let end = console.log(`You lost! The pirate ship has sunken.`);
- return end;
- }
- }
- }
- }
- else if (command === "Repair") {
- let index = num1;
- let heal = num2;
- if (index >= 0 && index < pirateShip.length) {
- pirateShip[index] += heal;
- if (pirateShip[index] > maxHealth) {
- pirateShip[index] = maxHealth;
- }
- }
- } else if (command === "Status") {
- let count = 0;
- let minHealth = maxHealth * 0.2;
- for (let ship of pirateShip) {
- if (ship < minHealth) {
- count++;
- }
- }
- console.log(`${count} sections need repair.`);
- }
- }
- let pirateShipSum = pirateShip.reduce(
- (accumulator, currentValue) => accumulator + currentValue
- );
- let warshipSum = warShip.reduce(
- (accumulator, currentValue) => accumulator + currentValue
- );
- console.log(`Pirate ship status: ${pirateShipSum}`);
- console.log(`Warship status: ${warshipSum}`);
- }
Advertisement
Add Comment
Please, Sign In to add comment