Created
September 18, 2015 15:34
-
-
Save alexkahn/b0988e0a466553c0c59d to your computer and use it in GitHub Desktop.
A simple OOish JavaScript demonstration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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