Random Number Game

Here is a possible solution.
The idea is to use a loop to repeatedly asking from user to “roll” the dices, for testing purposes only I put 3 dices here, but you can extend to 5 dices.

I maintain a boolean variable that will be true if and only if all the dices has the same value, if that the case, the program will break out from loop, and will print a successful message.

#include <iostream>
#include <string>

using namespace std;

int main()
{
   // Intro Instruction
   cout << "Welcome to Random Number game!\n";
   cout << "The objective of this game to get all 5 dice the same number.\n";

   string command;
   int magic = 0;

   do
   {
      cout << "To begin the game please type roll: ";
      cin >> command;

      if(command == "roll")
      {
         int dice1 = rand() % 6 + 1;
         int dice2 = rand() % 6 + 1;
         int dice3 = rand() % 6 + 1;

         cout << "First Dice: " << dice1 << endl;
         cout << "Second Dice: " << dice2 << endl;
         cout << "Third Dice: " << dice3 << endl;

         cout << "Which Dice do you want to keep? : (Enter 1, 2 or 3)" << endl;
         int keep_dice;
         cin >> keep_dice;

         if(keep_dice == 1)
         {
            magic = dice1;
            break;
         }
         else if(keep_dice == 2)
         {
            magic = dice2;
            break;
         }
         else if(keep_dice == 3)
         {
            magic = dice3;
            break;
         }
      }
   }
   while(true);

   cout << "You choose the number: " << magic << ". Roll the other dices until you get for both this number." << endl;    

   do
   {
      cout << "Type roll: ";
      cin >> command;

      if(command == "roll")
      {
         int dice1 = rand() % 6 + 1;
         int dice2 = rand() % 6 + 1;

         cout << "First Dice: " << dice1 << endl;
         cout << "Second Dice: " << dice2 << endl;

         if(dice1 == magic && dice2 == magic)
         { 
            break;
         }
      }
   }
   while(true);


   cout << "You won !" << endl;

}

Alternative Solution:
My idea is to create a function that will accept two parameters: num_dice the remaining dices to be rolled if you have 5 dices that will be 4, if you have n dices this will be n-1 and so on.

The other parameter will be the lucky number that the user will choose (easy with an if or with switch statement)

You will then repeat that with the same logic within your function until you get your n-1 dices equal to lucky number.

Moreover, think that my code may need a bit alteration, so that the first roll of all dices will happen once and not repeatedly, and then with the function you will do the repeat “job”.

Leave a Comment