This code should be in C++ You are coding a simple game called Pig. The rules ar
ID: 2246696 • Letter: T
Question
This code should be in C++
You are coding a simple game called Pig. The rules are as follows:
• Two players (you and the computer) are racing to reach 100 points. • Each turn, the active player faces a decision:
– Hold: take your turn total and add it to the player's overall total. The next player becomes active.
– Roll: generate a random number between 1 and 6. Results are: * 1 Lose turn, no turn total added to overall total. All the
points you have accumulated this turn are lost.
* 2..6 Add this number to the turn total. Player goes again.
Use Structured Programming or Object Oriented Programming Techniques.
Use function prototypes and comment them. Every program you write in this class has this constraint EVEN IF NOT EXPRESSLY STATED.
Make a simple AI by randomly generating a number 1,2,3 - hold, 4,5,6 - roll, etc.
Keep count of the number of turns it took to win/lose.
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<stdbool.h>
int roll(void)
{
int num = (rand()%6)+1;
return num;
}
/*
void player(void)
{
int i=0;
int sum=0;
int dice;
char turn;
while(i!=6)
{
printf("Player 1- roll or hold? ");
turn = getchar();
while(getchar()!=' ');
if(turn=='r')
{
dice = roll();
if(dice!=1)
{
sum+=dice;
printf("Rolled = %i Your turn total = %i ",dice,sum);
}
else
{
sum=0;
}
}
else if(turn =='h')
{
printf("Your total score is = %i ",sum);
}
i++;
}
}
*/
int sum1player2=0;
void player2(void)
{
_Bool j=true;
int sum1=0;
int dice;
char turn;
while(j)
{
printf("Player 2- roll or hold? ");
turn = getchar();
//j++;
while(getchar()!=' ');
if(turn=='r')
{
dice = roll();
if(dice!=1)
{
sum1+=dice;
printf("Rolled = %i Your turn total = %i ",dice,sum1);
}
else
{
printf("Sorry, you rolled 1, Your score is 0 Next player turn.");
j=false;
}
}
else if(turn =='h')
{
j=false;
sum1player2+=sum1;
printf("Your total score is = %i ",sum1player2);
}
}
if(sum1player2 < 100)
{
player1();
}
else
{
printf("player 1 wins");
}
}
int sumPlayer1=0;
int player1(void)
{
_Bool k=true;
int sum=0;
int dice;
char turn;
while(k)
{
printf("Player 1 - roll or hold? ");
turn = getchar();
while(getchar()!=' ');
if(turn=='r')
{
dice = roll();
if(dice!=1)
{
sum+=dice;
printf("Rolled = %i Your turn total = %i ",dice,sum);
}
else
{
printf("Sorry, you rolled 1, Your score is 0 Next player turn.");
k=false;
}
}
else if(turn =='h')
{
k=false;
sumPlayer1+=sum;
printf("Your total score is = %i ",sumPlayer1);;
}
}
if(sumPlayer1 < 100)
{
player2();
}
else
{
printf("player 2 wins");
}
return 0;
}
int main(void)
{
srand(time(NULL));
player1();
}