/**
This plugin provides basic "dice rolling" features, intended
for use in games/gaming utilities based on jQuery.
Usage:
$('#MyDieButton').bogoDice({ ... options ... });
Results are undefined if this plugin is applied to a non-button
UI element, but in theory it "should" work with any element
for which jQuery(...).click() behaves properly.
Options are:
- sides [integer, default=6], the number of sides the dice have.
- count [integer, default=3], the number of dice to roll.
- resultsTarget [Mixed, default=null], a target object to send the
dice results to. If it is a function, it is called and passed
the total of a dice roll result (as a string). If it is not
a function then it is assumed to be a jQuery selector, and
$(resultsTarget).text(...) will be called and passed the die
results.
- verbose [Boolean, default=true], if false then only the
grand total of a die result is sent to the resultsTarget,
otherwise an "informative" form is used. e.g. rolling 3d6
will have a result in the form of "3 + 2 + 5 = 10".
- label [string, default=count+'d'+sides], a label string to
apply to the target button.
///////////////////////////////////////////////////////////////////////
Example usage:
Click a die button
...
$('#Button1d6').bogoDice({
sides:1,
count:1,
resultsTarget:'#DieResults'
});
$('#Button5d6').bogoDice({
sides:1,
count:1,
label:'5 dice',
resultsTarget:'#DieResults'
});
///////////////////////////////////////////////////////////////////////
Potential TODOs:
- Ability to fetch results using Ajax, to allow server-produced
results.
- Add a modifier to the roll total (e.g. 3d6+3 or 1d6-1).
- Somehow support special types of dice, like dF (Fudge dice).
///////////////////////////////////////////////////////////////////////
Author:
http://wanderinghorse.net/home/stephan/
License: Public Domain
Revision history:
- 20070805: initial release
*/
jQuery.fn.bogoDice = function( props ) {
props = jQuery.extend({
sides:6,
count:3,
resultsTarget:null,
verbose:true
},
props ? props : []);
props = jQuery.extend({
label:props.count+'d'+props.sides
},
props);
function rollDie(sides,count,target) {
if( ! count ) count = 1;
var accum = target ? new Array() : null;
var total = 0;
var res =0;
for( var i = 0; i < count; ++i ) {
res = Math.floor(Math.random()*sides+1);
total += res;
if( accum ) accum[i] = res;
}
if( target ) {
var msg = ''+total;
if( props.verbose ) {
msg = count+'d'+sides+': ';
if( count == 1 ) { msg += total; }
else {
msg += (accum.join(' + '))+' = '+total;
}
}
if( 'function' == typeof target ) {
target( msg );
} else {
$(target).text( msg );
}
}
return total;
};
this.text(props.label);
this.click(function(){
rollDie( props.sides, props.count, props.resultsTarget );
});
return this;
};