Objectives
We would like to :- Review structures.
- Employ a structure to improve our implementation of a die.
Notes
- We are working on how to make a reusable, independent die
- I probably didn't make that clear before, but that is really the goal.
- We had decided that some form of the following code is bad.
die1 = rand_r(&seed1) % die1Sides + 1;
- We need to keep track of 2 - 3 variables.
- We need to not mistype the equation
- And it most likely breaks cohesion, as this is a low level detail
- write a struct that holds the die
- What is the syntax of a struct?
- Take a look at the reference at https://en.cppreference.com/w/c/language/struct.html
- Discussed on page 23 of the book.
- What do we use a struct for?
- "... structs are not typically used for OO programming in C++..."
- Do we have a naming convention for a struct?
- As far as I can see, we have three fields associated with a die
- The number of sides
- The seed
- The current value.
- So the struct
-
struct DieT { int sides{6}; unsigned int seed{1}; int value; }; - This assumes that the most common die is 6 sided.
-
- How do i
- Declare a die?
- Set the sides of a die?
- print the value of a die?
- Our code should become something like task3pre.cpp.
- Do you understand all of this code?
- There are some parts that bother me.
- Initializing the die
- The value should be set based on the seed, but it is not.
- An programmer might use a 0 for the value of the die.
- The seed is set to 1, but I need to remember
die1.seed = static_cast
(rand());
- Rolling the die is messy
- Initializing the die
- Could we clean this up with some functions?
- Initialize a die
- Roll a die
- Get the value of a die
- Get the number of sides of a die.
- You might not like the last two, but live with it for now.
- Take a look at task3Bpre.cpp
- Next let's implement a game with this die.