Skip to content

Instantly share code, notes, and snippets.

@alexkahn
Created September 18, 2015 15:34
Show Gist options
  • Save alexkahn/b0988e0a466553c0c59d to your computer and use it in GitHub Desktop.
Save alexkahn/b0988e0a466553c0c59d to your computer and use it in GitHub Desktop.
A simple OOish JavaScript demonstration
function Character(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
}
Character.prototype.attack = function 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...");
}
};
function Player(name, health, strength) {
Character.call(this, name, health, strength);
this.xp = 0;
}
Player.prototype = Object.create(Character.prototype);
Player.prototype.describe = function () {
return [
this.name,
"has",
this.health,
"health points and",
this.strength,
"strength, with",
this.xp,
"XP Points"
].join(" ");
};
Player.prototype.attack = function playerAttack() {
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 if (target.health === 0) {
console.log(this.name + " killed " + target.name + " and wins " +
monster.value + " XP points");
this.xp += target.value;
} else {
console.log(this.name + " cannot attack: he's dead...");
}
};
function NPC(name, health, strength, race, value) {
Character.call(this, name, health, strength);
this.race = race;
this.value = value;
}
NPC.prototype = Object.create(Character.prototype);
NPC.prototype.describe = function npmDescribe() {
return [
this.name,
"has",
this.health,
"health points and",
this.strength,
"strength. It's a",
this.race,
"worth",
this.value,
"XP points"
].join(" ");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment