Project: game characters
JavaScript · Unit 13: Inheritance
- Full plan
- JavaScript
- Project
- 3 exercises
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. Complete the code
Every warrior starts with 120 health and 10 power; only the name changes. Fill in the class.
2. Write the code
Write the
Warriorclass. It inherits fromCharacter, gets its name and theedgeof its sword, and always starts with 120 health and 10 power. Its hit is its power plus the edge: overridehit(). Theduelfunction below is ready.3. Write the code
Now the
Wizard: it starts with 70 health, 4 power and 20 mana. Write itshit(). 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: usesuper.hit(). Theroundfunction puts the warrior and the wizard to fight together.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.