/*---- implementation file for function: GameDie A GameDie object represents a single game die. 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. adapted from Astrachan's "A Computer Science Tapestry" 2nd edition, pp. 214, 217 (but also adapting David Tuttle's example of rand from his Die class from Fall 2020 CS 112 - Week 8 Lecture 2 in-class examples) by: Owen Astrachan adapted by: Sharon Tuttle last modified: 2021-06-23 ----*/ #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <ctime> #include "GameDie.h" using namespace std; // constructors // if number of sides not specified, GameDie will have 6 sides; // and, initial top will be 1 GameDie::GameDie() { /* initialize random seed for future rand calls in roll() method? */ srand (time(NULL)); num_sides = DEFAULT_NUM_SIDES; curr_top = 1; } // initial top will be 1 in specifed-number-of-sides case, also GameDie::GameDie(int desired_num_sides) { /* initialize random seed for future rand calls in roll() method? */ srand (time(NULL)); num_sides = desired_num_sides; curr_top = 1; } // accessors int GameDie::get_num_sides() const { return num_sides; } int GameDie::get_curr_top() const { return curr_top; } // other methods /*--- signature: roll: void -> int purpose: expects nothing, computes a pseudo-random int in [1, num_sides], changes curr_top of the calling GameDie to that computed value, and also returns that computed value as the result of this call to roll tests: for: GameDie demo; demo_die.roll() <= 6 demo_die.roll() >= 1 if you had: int rolled_result = demo_die.roll(); then, afterwards: rolled_result == demo_die.get_curr_top() for: GameDie deca_die(10); deca_die.roll() <= 10 deca_die.roll() >= 1 if you had: int deca_rolled = deca_die.roll(); then, afterwards: deca_rolled == deca_die.get_curr_top(); ---*/ int GameDie::roll() { // copying/adapting from David Tuttle's comment in his Die class' roll // method from Fall 2020 CS 112 - Week 8 Lecture 2 in-class examples //----- // rand() % num_sides // will be a value from 0 to (num_sides - 1), because % gives // the remainder when dividing rand() by num_sides. // We add 1 to that to get an integer in [1, num_sides]. // WARNING: this is NOT a "professional-grade" randomizer // statement! It'll be slightly biased toward the smaller // values. More elaborate code is needed to make this "fairer", // but this will do for now 8-) curr_top = (rand() % num_sides) + 1; return curr_top; }