Two players are each given a set of 3 dice. The first player throws the 3 dice and the
numbers on the top face of each die is recorded. Then the second player similarly
throws his 3 dice and the numbers on the top face of each die is also recorded. The
two sets of readings are compared and a player is deemed to have won that round if
any of the following occurs: -
(a) A set of all same numbers are obtained e.g. all 1s, or all 2s, or any other number
therein. If both players fall into this scenario during that round, then it is a draw
for that round. If only one player throws all the same numbers, then he wins
that round.
(b) Both players throw their dice and obtained three different numbers. All three
numbers are totalled up and whoever has the larger total, wins that round.
However, if the total of both players are the same then it is a draw.
After N rounds, the first player to reach a total accumulated round wins of 10 is declared
the overall winner.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void roll_dice(int dice[], int n) {
  for (int i=0; i<n; i++) {
    dice[i] = rand() % 6 + 1;
  }
}
void print_dice(int dice[], int n) {
  cout << "Dice:";
  for (int i=0; i<n; i++) {
    cout << " " << dice[i];
  }
  cout << endl;
}
bool all_same(int dice[], int n) {
  for (int i=1; i<n; i++) {
    if (dice[0] != dice[i]) {
      return false;
    }
  }
  return true;
}
int sum_dice(int dice[], int n) {
  int sum = 0;
  for (int i=0; i<n; i++) {
    sum += dice[i];
  }
  return sum;
}
void play_round(int& win1, int& win2) {
  int dice1[3], dice2[3];
  roll_dice(dice1, 3);
  cout << "Player 1 roll" << endl;
  print_dice(dice1, 3);
  roll_dice(dice2, 3);
  cout << endl << "Player 2 roll" << endl;
  print_dice(dice2, 3);
  cout << endl;
  if (all_same(dice1, 3) && !all_same(dice2, 3)) {
    cout << "Player 1 won the round" << endl;
    win1++;
    return;
  }
  if (!all_same(dice1, 3) && all_same(dice2, 3)) {
    cout << "Player 2 won the round" << endl;
    win2++;
    return;
  }
  if (all_same(dice1, 3) && all_same(dice2, 3)) {
    cout << "It is a draw" << endl;
    return;
  }
  if (sum_dice(dice1, 3) > sum_dice(dice2, 3)) {
    cout << "Player 1 won the round" << endl;
    win1++;
    return;
  }
  if (sum_dice(dice1, 3) < sum_dice(dice2, 3)) {
    cout << "Player 2 won the round" << endl;
    win2++;
    return;
  }
 Â
  cout << "It is a draw" << endl;
}
int main() {
  int win1=0, win2=0;
  int round=1;
  srand(time(nullptr));
  while (win1 < 10 && win2 < 10) {
    cout << endl << "Round " << round << endl;
    cout << "-------------------------------" << endl;
    play_round(win1, win2);
    cout << "Player 1: " << win1 << "  Player 2: " << win2 << endl;
    round++;
    cout << endl;
  }
  if (win1 == 10) {
    cout << "Player 1 won!";
  }
  else {
    cout << "Player 2 won!";
  }
  return 0;
}
Comments
Leave a comment