Before scoffing at my erroneous code let me briefly inform you what I am trying to accomplish, and where I am going wrong.
Craps is a game played with 2 dice. If you roll 7 or 11 on the first roll you win. If you roll 2, 3 or 12 on the first roll you lose. Any other roll is called the "point" and the game continues. Now the player wins if on any subsequent roll the player rolls "point" again. However if the player rolls a 7 before rolling the "point" then the player loses. Any other roll (aside from "point" or 7) is ignored and we continue rolling until we hit "point" or 7.
In my simulation the roll_dice
function should generate two random numbers between 1 and 6 and add them. The play_game
function should play one craps game and returns true
if the player wins and false
if the player loses. It is also responsible for displaying messages showing the results of the player's dice rolls. We keep track of the numbers of wins and losses in main
.
The problem in my code happens when the roll_dice
function returns a number that is not: 7, 11 or 2, 3, 12. I.e. When it rolls a "point". When it rolls a "point" then the subsequent roll is also always the "point" and the game finishes with a win. I'm looking at the last for
loop in play_game
and I suspect the error is there but I don't know why it's wrong. For some reason the value of the score2
variable is always the "point" (if score1
is a "point") and I don't know why this is the case. Surely by invoking roll_dice
a second time score2
should sometimes not be equal to score1
?
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int roll_dice(void);
bool play_game(void);
int main(void)
{
int wins = 0, losses = 0;
for(;;) {
if(play_game())
{
printf("You win!\n");
wins++;
}
else
{
printf("You lose!\n");
losses++;
}
char x;
printf("\nPlay again? ");
scanf("%c", &x);
getchar(); //absorbs the "ENTER" button once y,Y,n or N has been typed
if(x == 'y' || x == 'Y')
continue;
if(x == 'n' || x == 'N')
{
printf("Wins: %d Losses: %d\n", wins, losses);
break;
}
}
return 0;
}
int roll_dice(void)
{
int die1, die2;
srand((unsigned) time(NULL));
die1 = 1 + rand() % 6;
die2 = 1 + rand() % 6;
return die1 + die2;
}
bool play_game(void)
{
int score1 = roll_dice();
if(score1 == 7 || score1 == 11)
{
printf("You rolled: %d\n", score1);
return true;
}
if(score1 == 2 || score1 == 3 || score1 == 12)
{
printf("You rolled: %d\n", score1);
return false;
}
else
{
printf("You rolled %d\nYour point is %d\n", score1, score1);
}
for(;;){
int score2 = roll_dice();
if(score2 == 7) {
printf("You rolled: %d\n", score2);
return false; }
if(score2 == score1) {
printf("You rolled: %d\n", score2);
return true; }
else printf("You rolled: %d\n", score2);
}
}