/***
|''Name:''|DiceRollPlugin |
|''Description:''|Dice roller. |
|''Version:''|0.1 |
|''Date:''|2008.08.19 |
|''Source:''|http://www.draugrheim.net/rpgwiki/rpgwiki.html |
|''Status''|stable |
|''Author:''|[[Martin Andersen|mailto:draugen@draugrheim.net]] |
|''Contributors''|[[Devon Jones|http://www.legolas.org/gmwiki/dev/gmwikidev.html]] |
|''Type:''|plugin |
|''License:''|GPL |
|''CoreVersion:''|2.4 |
!Description
Dice roller utility library for RPGWiki
!Notes
!Usage
!Revision history
!!0.1 - 2208-08-19
Initial release. Complete rewrite/refactor of original code.
!Todo
* Better input validation
!Code
***/
if (!window.RPG) {
	window.RPG = {};
}
RPG.die = function (sides) {
	// TODO proper input type checking
	// (function should only accept
	//  positive integers and the
	//  characters 'f' and 'F')
	var result = 0;
	var roll = function () {
		if (sides === "F" || sides === "f") { // fudge die
			roll.result = Math.floor(3 * Math.random()) - 1;
		}
		else if (!isNaN(parseInt(this.sides, 10))) { // normal die
			roll.result = Math.floor(this.sides * Math.random()) + 1;
		}
		return roll.result;
	};
	var toString = function () {
		var s;
		s	= result ? 'Rolled a D' + sides + ': ' + result : 'The die has not been rolled yet';
		return s;
	};
	return {
		sides: sides,
		roll: roll,
		result: result,
		toString: toString
	};
};

function Dice(count, die) { 
	this.count = !isNaN(parseInt(count, 10)) ? count : 1; // default to 1 die
	this.die = die || new RPG.die(20);								// with 20 sides
	this.rolls = [];
	this.roll();
}
Dice.prototype.roll = function () {
	this.rolls = [];
	this.rolls.total = 0;
	for (var i = 0;  i < this.count; i++) {
		this.rolls.total += this.die.roll();
		this.rolls.push(this.die.roll.result);
	}
	return this.rolls.total;
};
Dice.prototype.toString = function () {
	var s = this.count + "d" + this.die.sides; 
	s += " (rolled " + this.rolls.join(" + ");
	s += " = " + this.rolls.total +")";
	return s;
};

function Dicebag() {
	this.dice = arguments;
}
Dicebag.prototype.roll = function () {
	for (var i = 0; i < this.dice.length; i++) {
		this.dice[i].roll();
	}
};