/** * a class representing a game die, * such as can be used in a game * such as D&D, Yahtzee, Monopoly, etc., * to get a pseudo-random integer * in a certain range * * It has a set number of sides, each numbered from * 1 to the number of sides, and it can be rolled, * which results in a number between 1 and the number of * sides. It also has a top, whose value is initially 1, * and afterwards is set to the value of the most-recet * roll. * * adapted from C++ class Dice from Astrachan's * "A Computer Science Tapestry", 2nd edition, * pp. 214, 217 * * @author Owen Astrachan * @author adapted by Sharon Tuttle * @version 2016-10-21 */ public class GameDie { // data fields private int numSides; private int top; private int numRolls; /** * create a new GameDie instance with * the specified number of sides, * whose top is initially 1 * * @param desiredNumSides number of sides for this die */ public GameDie(int desiredNumSides) { this.numSides = desiredNumSides; this.top = 1; this.numRolls = 0; } /** * this returns the top of the calling GameDie * * @return value of top for calling die */ public int getTop() { return this.top; } /** * this returns the number of sides of the * calling GameDie * * @return number of sides of calling die */ public int getNumSides() { return this.numSides; } /** * return the number of times the * calling GameDie has been rolled * * @return number of times calling die has been rolled */ public int getNumRolls() { return this.numRolls; } /** * this will roll the calling die, * returning a pseudo-random result * in the range [1, this.numSides] * * @return the value of this roll of this game die */ public int roll() { int rollResult = (int) (1 + Math.ceil(Math.random() * (this.numSides - 1))); this.top = rollResult; this.numRolls++; return rollResult; } }