Created
June 8, 2014 22:44
-
-
Save PaulMaynard/973d8fcf61e5abbbe75e to your computer and use it in GitHub Desktop.
Gist from mistakes.io
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 roll(die) { | |
var result = 0, a = /(\d+)d(\d+)(?:([\+\-\*\/])(\d+))?/.exec(die); | |
var times = a[1], sides = a[2], op = a[3], mod = +a[4]; | |
result = roll.raw(times, sides); | |
if(op && mod) result = roll.ops[op.replace(/x/g, '*')](result, mod); | |
return result | |
} | |
roll.raw = function(times, sides, total) { | |
total = total || 0; | |
total += Math.ceil(Math.random() * sides); | |
return times <= 1 ? total : roll.raw(times - 1, sides, total); | |
} | |
roll.ops = function(ops) { | |
var o = {}; | |
ops.forEach(function(op) { | |
o[op] = new Function('a, b', 'return a ' + op + ' b;') | |
}) | |
return o; | |
}('+-*/'.split('')); | |
function Point(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
Point.prototype.dist = function dist(p) { | |
return Math.sqrt(Math.pow(Math.abs(this.x - p.x), 2) | |
+ Math.pow(Math.abs(this.y - p.y), 2)); | |
} | |
Point.prototype.toString = function() { | |
return '(' + this.x + ',' + this.y + ')' | |
} | |
function Creature (name, hp, weapon, pos) { | |
this.name = name; | |
this.weapon = weapon; | |
this.hp = this.maxhp = hp; | |
this.pos = pos; | |
this.dead = false; | |
} | |
Creature.prototype.hit = function(target, times) { | |
if(this.pos.dist(target.pos) <= this.weapon.reach) { | |
target.hurt(roll(this.weapon.dam)); | |
} | |
}; | |
Creature.prototype.hurt = function(amt) { | |
this.hp -= amt; | |
if(this.hp <= 0) { | |
this.die() | |
} | |
}; | |
Creature.prototype.die = function() { | |
this.dead = true; | |
}; | |
var bob = new Creature('bob', 10, new Weapon('sword', '1d6', 1.5), new Point(1, 1)); | |
var orc = new Creature('orc', 15, new Weapon('dagger', '1d4', 1), 1.5, new Point(1, 1)); | |
bob.hit(orc); | |
bob; | |
orc; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment