Skip to content

Instantly share code, notes, and snippets.

@bpesquet
Last active September 17, 2015 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpesquet/6dac5adeb5f31fdc1951 to your computer and use it in GitHub Desktop.
Save bpesquet/6dac5adeb5f31fdc1951 to your computer and use it in GitHub Desktop.
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