Skip to content

Instantly share code, notes, and snippets.

@bpesquet
Created September 20, 2015 17:22
Show Gist options
  • Save bpesquet/c7b9ac3745b38ccc2827 to your computer and use it in GitHub Desktop.
Save bpesquet/c7b9ac3745b38ccc2827 to your computer and use it in GitHub Desktop.
Minimalist RPG exemple written in the OLOO style
var Character = {};
Character.initCharacter = function (name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
};
Character.attack = function (target) {
if (this.health > 0) {
var damage = this.strength;
console.log(this.name + " attacks " + target.name + " and deals " + damage + " damage");
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...");
}
};
var Player = Object.create(Character);
Player.initPlayer = function (name, health, strength) {
this.initCharacter(name, health, strength);
this.xp = 0;
};
Player.describe = function () {
return this.name + " has " + this.health + " health points, " +
this.strength + " strength and " + this.xp + " XP points";
};
Player.battle = function (npc) {
this.attack(npc);
if (npc.health === 0) {
console.log(this.name + " has killed " + npc.name + " and wins " +
npc.value + " XP points");
this.xp += npc.value;
}
}
var NPC = Object.create(Character);
NPC.initnpc = function (name, health, strength, race, value) {
this.initCharacter(name, health, strength);
this.race = race;
this.value = value;
};
var player1 = Object.create(Player);
player1.initPlayer("Aurora", 150, 25);
var player2 = Object.create(Player);
player2.initPlayer("Glacius", 130, 30);
console.log("Welcome to this adventure game ! Here are our fearless heroes :");
console.log(player1.describe());
console.log(player2.describe());
var master = Object.create(NPC);
master.initnpc("ZogZog", 40, 20, "orc", 10);
console.log("An ugly monster is coming : it's a " + master.race + " named " + master.name);
master.attack(player1);
master.attack(player2);
player1.battle(master);
player2.battle(master);
console.log(player1.describe());
console.log(player2.describe());
@srameshr
Copy link

srameshr commented Nov 6, 2015

Tracing the prototype chain is so much easier with this approach, rather than with the constructor style

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment