Javascript - Challenge 2: Classes
Code Life
By Pierre Marsaa
Arena Showdown
Second final challenge: build a small battle engine with classes, then let the Codémon fight.
This challenge combines classes and inheritance, this, a while loop, and an error thrown and caught on purpose.
Step 1: Codemon takes a name, hp and power. Its methods: isAlive() returns whether hp is above 0; attack(target) throws an Error with the message "name has fainted and cannot attack" if this Codémon is not alive, otherwise lowers the target's hp by power (never below 0 — Math.max() helps) and returns "name hits target for X (target at Y)".
Step 2: Legendary extends Codemon. Its constructor takes the same three parameters but passes double the power to the parent constructor with super.
Step 3: battle(a, b) prints "--- a vs b ---", then makes the fighters attack each other in turns (a first) with a while loop, until one of them faints. Each hit is printed as "[Turn N] message". Finally it prints "Winner: name".
Step 4: run battle(zap, aquachu) then battle(rockachu, zap). Then, inside a try...catch, make Aquachu attack Zap and print "Error: message".
Expected output:
Loading editor...
↗️
Loading editor...
↶
↷
💡 Show Solution
Finish