Having decided to brush up on my programming, I wanted to try and make a Yahtzee game, only console based. It is object-oriented for the most part.

My trouble is with generating different numbers for each die. I will post my Dice class to help show what I am doing:

class Dice {
  public:
    Dice();                     
    
    int roll();
    int getFaceValue() const; 
  
  private:
    void rollDie(); 
    
    int faceValue;
    bool hold;
};

and the rest

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

#include "Dice.h"

Dice::Dice() {
  rollDie();
  
  srand( time(0) );
  hold = true;
}

int Dice::roll() {
  rollDie();
  return faceValue;
}

int Dice::getFaceValue() const {
  return faceValue;
}

void Dice::rollDie() {
  if ( !hold ) {
    faceValue = (1 + rand() % 6);
  }
}

Just to test it I run this code:

Dice dice[5];
  
  int i = 0;
  while ( i < 20 ){
  rollTheDice(dice);
  cout << endl;
  i++;
  }

All "rollTheDice(dice)" does is call the "roll()" function for each object in the array. To simulate someone rolling dice.

I get the same values each iteration of the loop, I suspect this is because each Dice object is created with the same code, so the numbers generated are the same.

What I am looking for is the way to generate different values for each Dice object each time.

Alright, so I solved my own problem, for now. Initialized the "hold" boolean to true prevented the roll function from actually executing.

I will still take suggestions though!

You call srand ONCE during each program, then you call rand to generate the numbers. If you want ten numbers, call srand (time(0)) once at the very beginning of the program, then call rand () ten times:

srand (time (0));  // first line of program

for (int i = 0; i < 10; i++)
{
   int randNum = rand () % 10;
   cout << randNum << endl;
}

I acctualy just finished writing a Yatzhee game and what i did was i created two functions like so:

void Player::dice(int i=0);
void Player::random();

Anyway when ever i want all dices rethrown i call dice() since default argument is 0 which rethrows all dices it calles random 5 times.
Random looks like so

int Player::random()             //Random function called by dice()
{
    return rand() % 6)+1;
}

or you could call dice() with an argument like such dice(3);
Which would call random() and only change the third dice.
The dices are declated in Player.

//K0ns3rv

As VernonDozier said, call srand( ) only once in a program.

What happens, when you call it in the function as you did, and the function gets called repeatedly in a loop, the calls to srand( ) occur too quickly for the clock time to have changed, so you keep setting the initial random number to the same point in the list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.