The challenge
Write class Pet with a name, energy starting at 10, and play() which lowers energy by 3 (never below 0) and returns "NAME is tired" when energy hits 0, or "NAME had fun!" otherwise. Then write class Dog extends Pet whose play() uses 2 energy instead of 3 (but the same messages).
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
new Pet("Tom").play()gives"Tom had fun!"- A pet gets tired after 4 games:
(() => { const p = new Pet("Tom"); p.play(); p.play(); p.play(); return [p.play(), p.energy]; })()gives["Tom is tired", 0] - Dogs use 2 energy:
(() => { const d = new Dog("Rex"); d.play(); return d.energy; })()gives8 - A Dog is a Pet:
new Dog("Rex") instanceof Petgivestrue
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Give Pet a helper like useEnergy(amount) that both play methods can share.
Hint 2
In Dog, you could override a property like this.cost instead of rewriting play.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
class Pet {
constructor(name) {
this.name = name;
this.energy = 10;
this.cost = 3;
}
play() {
this.energy = Math.max(0, this.energy - this.cost);
return this.energy === 0 ? `${this.name} is tired` : `${this.name} had fun!`;
}
}
class Dog extends Pet {
constructor(name) {
super(name);
this.cost = 2;
}
}
Learn what you need
This exercise uses what Sophomore Year: Classes & Object-Oriented JavaScript teaches. Read those notes first if any of it is new.