Skip to content

Instantly share code, notes, and snippets.

@csasbach
Created March 28, 2011 14:34
Show Gist options
  • Save csasbach/890570 to your computer and use it in GitHub Desktop.
Save csasbach/890570 to your computer and use it in GitHub Desktop.
This module exposes static methods for rolling dice.
/**
* Dice
*
* @author C. Scott Asbach
*
* This module exposes static methods for rolling dice.
*/
using System;
namespace Dice
{
// define dice
public enum Die
{
d2 = 2, // coin
d4 = 4, // tetrahedron
d6 = 6, // cube
d8 = 8, // octahedron
d10 = 10, // deltohedron
d12 = 12, // dodecahedron
d20 = 20, // icosahedron
} // end enum Die
// provide static methods for Rolling dice
public static class Roll
{
// create a Random object for seeding die rolls
private static Random Seed = new Random();
/**
* Cast a die n times.
* Return the total.
*
* @param Die
* @param int
*/
private static int cast( Die die, int rolls=1 )
{
int total = 0;
for ( int i = 0; i < rolls; i++ )
{
total += Seed.Next( 1, ( int )die + 1 );
} // end for
return total;
} // end method cast
/**
* Cast a die with 2 faces n times.
* Return the total.
*
* @param int
*/
public static int d2( int rolls = 1 )
{
return cast( Die.d2, rolls );
} // end method d2
/**
* Cast a die with 4 faces n times.
* Return the total.
*
* @param int
*/
public static int d4( int rolls = 1 )
{
return cast( Die.d4, rolls );
} // end method d4
/**
* Cast a die with 6 faces n times.
* Return the total.
*
* @param int
*/
public static int d6( int rolls = 1 )
{
return cast( Die.d6, rolls );
} // end method d6
/**
* Cast a die with 8 faces n times.
* Return the total.
*
* @param int
*/
public static int d8( int rolls = 1 )
{
return cast( Die.d8, rolls );
} // end method d8
/**
* Cast a die with 10 faces n times.
* Return the total.
*
* @param int
*/
public static int d10( int rolls = 1 )
{
return cast( Die.d10, rolls );
} // end method d10
/**
* Cast a die with 12 faces n times.
* Return the total.
*
* @param int
*/
public static int d12( int rolls = 1 )
{
return cast( Die.d12, rolls );
} // end method d12
/**
* Cast a die with 20 faces n times.
* Return the total.
*
* @param int
*/
public static int d20( int rolls = 1 )
{
return cast( Die.d20, rolls );
} // end method d20
/**
* Try a given roll n times.
* Return the greatest result.
*
* @param Die
* @param int
* @param int
*/
public static int BestOf( int tries, Die die, int rolls = 1 )
{
int best = 0;
for ( int i = 0; i < tries; i++ )
{
int roll = cast(die, rolls);
if ( roll > best )
{
best = roll;
} // end if
} // end for
return best;
} // end method BestOf
} // end class Roll
} // end namespace Dice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment