Challenge 2: Classes

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — 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:

--- Zap vs Aquachu --- [Turn 1] Zap hits Aquachu for 15 (Aquachu at 30) [Turn 2] Aquachu hits Zap for 10 (Zap at 30) [Turn 3] Zap hits Aquachu for 15 (Aquachu at 15) [Turn 4] Aquachu hits Zap for 10 (Zap at 20) [Turn 5] Zap hits Aquachu for 15 (Aquachu at 0) Winner: Zap --- Rockachu vs Zap --- [Turn 1] Rockachu hits Zap for 18 (Zap at 2) [Turn 2] Zap hits Rockachu for 15 (Rockachu at 45) [Turn 3] Rockachu hits Zap for 18 (Zap at 0) Winner: Rockachu Error: Aquachu has fainted and cannot attack
Starter code
// Write your classes and the battle function here // The fighters const zap = new Codemon("Zap", 40, 15); const aquachu = new Codemon("Aquachu", 45, 10); const rockachu = new Legendary("Rockachu", 60, 9); // Run the battles here
Back to the course