Create a gist now

Instantly share code, notes, and snippets.

Minimalist RPG example written with ES2015 syntax
class Character {
constructor(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
}
describe() {
return this.name + " has " + this.health +
" health points and " + this.strength + " strength";
}
attack(target) {
if (this.health > 0) {
var damage = this.strength;
console.log(this.name + " is attacking " + target.name + " and deals " + damage + " damage points");
target.health -= damage;
if (target.health > 0) {
console.log(target.name + " has " + target.health + " health points left");
} else {
target.health = 0;
console.log(target.name + " has died !");
}
} else {
console.log(this.name + " cannot attack: he's dead...");
}
}
}
class Player extends Character {
constructor(name, health, strength) {
super(name, health, strength);
this.xp = 0;
}
describe() {
return super.describe() + ", with " + this.xp + " XP points";
}
attack(target) {
super.attack(target);
if (target.health === 0) {
console.log(this.name + " killed " + target.name + " and wins " +
monster.value + " XP points");
this.xp += target.value;
}
}
}
class NPC extends Character {
constructor(name, health, strength, race, value) {
super(name, health, strength);
this.race = race;
this.value = value;
}
describe() {
return super.describe() + ". It's a " + this.race + " worth " + this.value + " XP points";
}
}
console.log("Welcome to this adventure game ! Here are our fearless heroes :");
var player1 = new Player("Aurora", 150, 25);
console.log(player1.describe());
var player2 = new Player("Glacius", 120, 30);
console.log(player2.describe());
var monster = new NPC("ZogZog", 40, 20, "orc", 10);
console.log("An ugly monster is coming :");
console.log(monster.describe());
monster.attack(player1);
monster.attack(player2);
player1.attack(monster);
player2.attack(monster);
console.log(player1.describe());
console.log(player2.describe());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment