﻿// base.js must be included first !

//--------------------------------------------------------------------------------------------------------------
// Basic die function
//--------------------------------------------------------------------------------------------------------------

function d(max)
{
	var result = Math.ceil(Math.random()*max)
	debugprint("rolling a d"+max+": "+result+"&nbsp;-&nbsp;");
	return result;
}

//--------------------------------------------------------------------------------------------------------------
// Dices Array (thrown DieSet; see bellow)
//--------------------------------------------------------------------------------------------------------------

// add a die from this die value array
function dva_add(value)
{
	this.vals[this.nbdices++] = value;
}

// remove n dices from this die value array
function dva_remove(nToRemove)
{
	if (nToRemove > this.nbdices)
		nToRemove = this.nbdices;
		
	var lowestindex;
	var lowestvalue;
	while (nToRemove)
	{	
		lowestvalue = 65000; 
		lowestindex = -1;
		for (i=0; i<this.nbdices; i++)
			if (this.vals[i]<lowestvalue)
			{
				lowestindex = i;
				lowestvalue = this.vals[i];
			}
		debugprint("Removing "+this.vals[lowestindex]+"&nbsp;");
		for (i=lowestindex; i<this.nbdices-1; i++)
			this.vals[i] = this.vals[i+1];
		nToRemove--;
		this.nbdices--;
	}
}

// compute de total of this die value array
function dva_total()
{
	tot = 0;
	for (i=0; i<this.nbdices; i++)
		tot+=this.vals[i];
	return tot;
}

// die value array ctor
function dva()
{
	this.nbdices = 0;
	this.vals = new Array;
	this.add = dva_add;
	this.remove = dva_remove;
	this.total = dva_total;
	return this;
}

//--------------------------------------------------------------------------------------------------------------
// Die Set
//--------------------------------------------------------------------------------------------------------------

function ds_dump()
{
	return ""+this.ndices+(this.nthrow!=this.ndices ? "/"+this.nthrow : "")+"d"+this.dietype;
}

function ds_throwr()
{
	var Dices = new dva;
	for (i=0; i<this.nthrow; i++)
		Dices.add(d(this.dietype));
	TheDices.remove(this.nthrow - this.ndices);
	return Dices;
}

function ds_throwit()
{
	var result=0;
	var i=0;
	var TheDices = dva();
	for (i=0; i<this.nthrow; i++)
		TheDices.add(d(this.dietype));

	TheDices.remove(this.nthrow - this.ndices);
	result = TheDices.total();

	debugprint(this.dump()+"="+result+"<br>");

	delete TheDices;
	return result;
}

function dieset(dietype, ndices, nthrow)
{
	if (ndices==null)
		ndices = 1;
	if (nthrow==null)
		nthrow=ndices;
	this.dietype = dietype;	// type of die
	this.ndices = ndices;	// final number of dices
	this.nthrow = nthrow;	// number of dices thrown (only the ndices best ones will be kept)
	this.dump = ds_dump;
	this.throwr = ds_throwr;
	this.throwit = ds_throwit;
	return this;
}
