I am working on a Tic-Tac-Toe game using C++ and I was wondering if it is possible to randomize a number but it could only choose either 2 or 5.
I made random start between user and the computer in order to make a fair start with these blocks of codes:
srand(time(NULL));
cout << "The First Person to go is randomly chosen!" << endl;
FirsttoGo = (rand()%2) + 1;
cout << "The first move goes to Player: " << FirsttoGo << endl;
turn = FirsttoGo;
The feature that I would like to add is whoever starts the game will be able to pick either X or O but if the computer starts first, the computer should be able to pick between X or O. I also created constant values for X and O
static const int O = 5;
static const int X = 2;
Is there anyway to do this?
In C++11 there are very nice and safer additions for the generation of random number in a range (see code below):
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 2);
for (int n=0; n<10; ++n) std::cout << dis(gen) << ' ';
std::cout << '\n';
}
Furthermore, in this nice talk Stephan T. Lavavej illustrates the reasons why using rand() considered harmful.
Based on the above example you could adjust it for your problem like this:
int getRandomIDX(int const a = 5, int const b = 2) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 2);
return (dis(gen) == 1)? a : b;
}
(rand() > RAND_MAX/2) ? 2 : 5;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With