/** * A class representing a die (the thing you roll to get a number; * nothing to do with kicking the bucket.) * @author Ian Barland * @version 2006.Sep.22 */ class Die { /** The number of sides on the die. */ private final int numSides; /** The currently-showing face/side. */ private int face; /** An internal random number generator. */ private final java.util.Random randyGenerator = new java.util.Random(); /** Constructor: code called via "new Die". * @param sidesToHave The number of sides to create the new die with. */ public Die( int _numSides ) { numSides = _numSides; face = numSides; // Initialize the face to be the maximum possible. } /** Return the currently-showing face on the die. * @return the currently-showing face on the die. */ public int getFace() { return face; } /** Set the die's face (clamping the value to the legal region 1..getNumSides()) * We make setFace private, because other classes should * roll dice, but not set them themselves. * @param newFace the new value of the Die's face. */ private void setFace( int newFace ) { if (newFace < 1) { face = 1; } else if (newFace > getNumSides()) { face = getNumSides(); } else { face = newFace; } } /** Return the number of sides this die has. * @return the number of sides this die has. */ public int getNumSides() { return numSides; } /** Roll the die, and return the newly-showing face-up number. * @return the resulting face (in 1..getNumSides()). */ public int roll() { setFace( randyGenerator.nextInt(numSides) + 1 ); // Note: 1 is not considered magic. return getFace(); } public String toString() { return "[Die: face=" + getFace() + "; numSides = " + getNumSides() + "]"; } }