Dice roll function

Does anyone have an experience playing Senet? It's an eqyptian game that I have been tasked with writing a program for.

how would I go about writing a "dice roll" function for a 5 sided dice?

this is what I found in the forums:

1
2
3
4
5
6
7
8
9
10
11
12
13
//The following function simulates a die roll
int die1()
{
    for (int counter = 0; counter < 2; counter++)
    {
      srand(time(NULL));
      for (int i = 0; i <6; i++)
        {
          cout << rand()% 6+1 << endl;
          return rand()%6+1;
        }
    }      
}
> srand(time(NULL));
You should do this exactly once at the start of main().
Calling it multiple times won't make for better random numbers.
Calling it too often (like in a loop) will make it for distinctly non-random numbers.

> return rand()%6+1;
This makes both your loops redundant.

> cout << rand()% 6+1 << endl;
Which will be different to the one you return.
how would I go about writing a "dice roll" function for a 5 sided dice?


In which program language? C or C++?
how would I go about writing a "dice roll" function for a 5 sided dice?

With C++11's <random> library, a generic "number of pips" function (and ZERO error checking):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <random>

int roll_die(int);

int main()
{
   std::cout << "A five-sided die: " << roll_die(5) << '\n';

   std::cout << "A 100-sided die: " << roll_die(100) << '\n';
}

int roll_die(int pip)
{
   // create a C++11 random engine and seed with std::random_device
   // static to keep it alive between function calls
   static std::default_random_engine rng(std::random_device {} ());

   // create a C++11 static uniform distribution
   static std::uniform_int_distribution<> dist { };

   // generate a random die roll and return the value
   return dist(rng, decltype(dist)::param_type { 1, pip });
}


Fayezilla wrote:
this is what I found in the forums

In addition to the problems salem c mentioned, that is a C library routine for a 6-sided die, not 5-sided you originally requested.

Doing it "The C Way" (one way, there are others):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <ctime>

int roll_die(int);

int main()
{
   // seed the C random generator once with the current timebefore using it
   std::srand(static_cast<unsigned>(std::time(0)));

   std::cout << "A five-sided die: " << roll_die(5) << '\n';

   std::cout << "A 100-sided die: " << roll_die(100) << '\n';
}

int roll_die(int pip)
{
   // generate a random number
   return std::rand() % pip + 1;
}


Using the C random generator is not recommended when writing C++ code.
https://web.archive.org/web/20180123103235/http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Last edited on
Topic archived. No new replies allowed.