Skip to the content

Project: game characters

JavaScript · Unit 13: Inheritance

You're going to build the characters of a game. They all have a name, health and power. When they take a hit they lose health, never going below 0, and when they attack they give the other one their hit(), which for now is their power.

This is the parent class of them all:

class Character {
  constructor(name, health, power) {
    this.name = name;
    this.health = health;
    this.power = power;
  }
  hit() {
    return this.power;
  }
  take(n) {
    this.health -= n;
    if (this.health < 0) {
      this.health = 0;
    }
  }
  attack(other) {
    other.take(this.hit());
  }
}
const mia =
  new Character("Mia", 50, 8);
const ogre =
  new Character("Ogre", 30, 5);
mia.attack(ogre);
console.log(ogre.health);

Prints

22

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Every warrior starts with 120 health and 10 power; only the name changes. Fill in the class.

  2. 2. Write the code

    Write the Warrior class. It inherits from Character, gets its name and the edge of its sword, and always starts with 120 health and 10 power. Its hit is its power plus the edge: override hit(). The duel function below is ready.

  3. 3. Write the code

    Now the Wizard: it starts with 70 health, 4 power and 20 mana. Write its hit(). If it has at least 10 mana, it spends 10 and casts a spell that hits 5 times its power. If it doesn't have enough, it hits like any character: use super.hit(). The round function puts the warrior and the wizard to fight together.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →