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 i = 0; i < input.length; i++) {
- let commands = input[i].split(' ');
- let command = commands[0];
- let values = commands.slice(1).map(x => Number(x));
- switch (command) {
- case "Fire": fire(warShip, values[0], values[1]); break;
- case "Defend": defend(pirateShip, values[0], values[1], values[2]); break;
- case "Repair": repair(pirateShip, values[0], values[1], maxHealth); break;
- case "Status": status(pirateShip, maxHealth); break;
- case "Retire": {
- console.log(`Pirate ship status: ${pirateShip.reduce((a, c) => a + c, 0)}`);
- console.log(`Warship status: ${warShip.reduce((a, c) => a + c, 0)}`);
- break;
- }
- }
- if (isShipDead(warShip)) {
- console.log(`You won! The enemy ship has sunken.`);
- break;
- }
- if (isShipDead(pirateShip)) {
- console.log(`You lost! The pirate ship has sunken.`);
- break;
- }
- }
- function isShipDead(ship) {
- let deadSections = ship.filter(x => x <= 0);
- return deadSections.length > 0;
- }
- function fire(warShip, index, damage) {
- if (index >= 0 && index < warShip.length) {
- warShip[index] -= damage;
- }
- }
- function defend(warShip, startIndex, endIndex, damage) {
- if (startIndex >= 0 && startIndex < warShip.length && endIndex >= 0 && endIndex < warShip.length) {
- for (let i = startIndex; i <= endIndex; i++) {
- warShip[i] -= damage;
- }
- }
- }
- function repair(ship, index, heal, maxHealth) {
- if (index >= 0 && index < ship.length) {
- let missingHealth = maxHealth - ship[index];
- ship[index] += Math.min(missingHealth, heal);
- }
- }
- function status(ship, maxHealth) {
- let damagedSections = ship.filter(x => x < (maxHealth * 0.2));
- console.log(`${damagedSections.length} sections need repair.`);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment