/** * 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-recent * 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 2017-09-20 */ public class GameDie { // data fields private int numSides; private int top; /** * create a new GameDie instance with 6 sides, * whose top is initially 1 */ public GameDie() { this.numSides = 6; this.top = 1; } /** * 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; } /** * return the number of sides of the * calling GameDie * * @return number of sides of the calling die */ public int getNumSides() { return this.numSides; } /** * return the current top of the calling GameDie * * @return value of top for the calling die */ public int getTop() { return this.top; } /** * roll the calling die, setting its top * to a pseudo-random value in [1, this.numSides], * and return its new top value * * @return the value of this roll of this game die */ public int roll() { // after lab, changed because still worried about // case if Math.random() returns 0.0, as it CAN this.top = (int) (1.0 + (Math.random() * this.numSides)); return this.top; } }