Classes and inheritance: a virtual pet

“Virtual pet shop”, a Black belt challenge from the CurlyScript Dojo. It uses what Sophomore Year: Classes & Object-Oriented JavaScript teaches, and 4 tests check your answer.

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.

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; })() gives 8
  • A Dog is a Pet: new Dog("Rex") instanceof Pet gives true

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning