In: Computer Science
C program with functions
Make a dice game with the following characteristics:
must be two players with two dice.
when player 1 rolls the marker is annotated
when player 2 rolls the marker is annotated
in other words, for each roll the added scores must be shown.
Example:
Round 1:
player 1 score = 6
player 2 score = 8
Round 2:
player 1 score = 14
player 2 score = 20
Whoever reaches 35 points first wins.
if a player goes over 35 points, the last shot does not count, example:
If a player is at 30 points and when he rolls the two dice he gets 6 points, the sum (30 + 6) would be 36, it goes over 35 so that throw does not count and the score remains at 30.
Whoever gets double 3 or double 5 loses automatically.
here is the required solution
here is the code
#include <stdio.h>
#include<stdlib.h>
//function to get roll the dice
int rolldice()
{ //roll of dice1 and dice2
int dice1=rand()%6+1;
int dice2=rand()%6+1;
if(dice1==dice2 && (dice1==3 || dice1==5))
return -1;
else
return dice1+dice2;
}
int main()
{ //declaration of relevant variable
int player1=0,player2=0,prev1=-1,prev2,tem, i=1;
while(1)
{ printf("Round %d\n",i++);
tem=rolldice();
//check if double 3 or 5 occur
if(tem==-1)
{
printf("Player 2 win");
break;
}
prev1=tem;
//add score if after adding score is less than 36
if(player1+prev1<=35)
player1=player1+prev1;
//if player1 reaches 35 than won
if(player1==35)
{
printf("player 1 win");
break;
}
printf("player 1 score=%d\n",player1);
tem=rolldice();
//check if double 3 or 5 occur
if(tem=-1)
{
printf("Player 1 win");
break;
}
prev2=tem;
//add score if after adding score is less than 36
if(player2+prev2<=35)
player2=player2+prev2;
printf("player 2 score=%d\n",player2);
//if player1 reaches 35 than won
if(player2==35)
{printf("Player 2 win");
break;}
//print the score
printf("player 1 score =%d\n",player1);
printf("player 2 score =%d\n",player2);
}
return 0;
}