I wrote a solution for the game of craps.
Here is how it is played :
Each round has two phases: "come-out" and "point". To start a round, the shooter makes one or more "come-out" rolls. A come-out roll of 2, 3 or 12 (called "craps", the shooter is said to "crap out") ends the round with players losing their "pass line" bets. A come-out roll of 7 or 11 (a "natural") results in a win for "pass line" bets. The shooter continues to make come-out rolls until he rolls 4, 5, 6, 8, 9, or 10, which number becomes the "point". The dealers then move an "On" button to the point number signifying the second phase of the round. If the shooter rolls the point number, the result is a win for bets on the pass line. If the shooter rolls a seven (a "seven-out"), the pass line loses, the don't pass wins, and the round ends.
and here is the code :
Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
//function declarations
int roll_dice(void);
bool play_game(void);
int main (int argc, const char * argv[]) {
// insert code here...
bool result;
int wins = 0;
int losses = 0;
char ch;
do {
result = play_game();
if (result == true)
{
printf("\nYou win!");
wins++;
printf("\n\nPlay again?");
ch = getchar();
}
else
{
printf("\nYou lose!");
losses++;
printf("\n\nPlay again?");
ch = getchar();
}
} while (ch != 'n');
printf("\n\nWins: %d\tLosses: %d", wins, losses);
}
int roll_dice(void)
{
srand((unsigned)time(NULL));
int firstDice;
int secondDice;
firstDice = rand() % 6 + 1;
secondDice = rand() % 6 + 1;
return (firstDice + secondDice);
}
bool play_game(void)
{
int result = roll_dice();
int point = 0;
int newDice;
printf("You rolled: %d", result);
if (result == 7 || result == 11)
{
return true;
}
else if (result == 2 || result == 3 || result == 12)
{
return false;
}
else {
point = result;
printf("\nYour point is: %d", point);
do {
newDice = roll_dice();
printf("\nYou rolled: %d", newDice);
}
while (newDice != 7 && newDice != point);
if (newDice == 7)
return false;
else
return true;
}
}
The problem is with the point case.When I run it I always get the same roll as the previous one and the user always win.
If I debug the program I get other rolls which is the result that I want.
Does it have to do with the speed of the machine?
Thank you.