Last active
December 13, 2021 19:16
-
-
Save vladislavaSim/7e4da9a833879c06fdc94ad957bf3219 to your computer and use it in GitHub Desktop.
robots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function makeSwap() { | |
let i = 0; | |
return function (a, b) { | |
if (i++ % 2 === 0) { | |
return [a, b]; | |
} | |
return [b, a]; | |
} | |
} | |
class Robot { | |
#hp; | |
constructor(name, attack, hp) { | |
this.name = name; | |
this.attack = attack; | |
this.#hp = hp; | |
} | |
get hp() { | |
return this.#hp; | |
} | |
setHp(hp) { | |
if(hp <= 0) { | |
this.#hp = 0 | |
} else { | |
this.#hp = hp | |
} | |
return this.#hp | |
} | |
} | |
let robot1 = new Robot('Green Robot', 1, 10); | |
let robot2 = new Robot('Red Robot', 1, 10); | |
let swap = makeSwap(); | |
function attack(robot1, robot2) { | |
return `${robot1.name} was attacked: -${robot2.attack} HP, ${robot1.setHp(robot1.hp -= robot2.attack)} HP left`; | |
} | |
function attackX2(robot1, robot2) { | |
return `${robot1.name} was attacked x2: -${robot2.attack} HP, ${robot1.setHp(robot1.hp -= robot2.attack * 2)} HP left`; | |
} | |
function suddenDeath(robot1, robot2) { | |
if (Math.round(Math.random() * 5) === 1) { | |
return `${robot1.setHp(0)} HP AFTER DEATH PUNCH! ${robot1.name} was killed at one attack` | |
} else { | |
return `${robot1.name} is lucky! HP saved`; | |
} | |
} | |
let attackTypes = [ | |
attack, | |
attackX2, | |
suddenDeath | |
]; | |
function getRandomAttack() { | |
let i = Math.floor(Math.random() * 3); | |
return attackTypes[i](...swap(robot1, robot2)) | |
} | |
function startFight(singleAttackMode = true) { | |
let fighting = setInterval(() => { | |
if(robot1.hp > 0 && robot2.hp > 0) { | |
if(singleAttackMode) { | |
console.log(getRandomAttack()) | |
} else { | |
if(!singleAttackMode) { | |
function tripleAttack(robotAttack, robotDefense) { | |
let attack; | |
for (let i = 0; i < 3; i++) { | |
if(robot1.hp > 0 && robot2.hp > 0) { | |
let i = Math.floor(Math.random() * 3); | |
attack = attackTypes[i](robotAttack, robotDefense) | |
console.log(attack) | |
} | |
} | |
} | |
tripleAttack(...swap(robot1, robot2)) | |
tripleAttack(...swap(robot1, robot2)) | |
} | |
} | |
} | |
else { | |
clearInterval(fighting); | |
showWinner() | |
} | |
}, 500) | |
} | |
startFight() | |
function showWinner() { | |
if(robot1.hp <= 0 || robot2.hp <= 0) { | |
console.log(robot1.hp > robot2.hp ? `${robot1.name} is a winner` : `${robot2.name} is a winner`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment