Write a program that simulates the game of craps, which is played with two dice.
ID: 675004 • Letter: W
Question
Write a program that simulates the game of craps, which is played with two dice. On the first roll, the player wins if the sum of the dice is 7 or 11. The player loses if the sum is 2, 3, or 12. Any other roll is called the "point", and the game continues. On each subsequent roll, the player wins if he or she rolls the point again. The player loses by rolling a 7. Any other roll is ignored and the game continues. At the end of the each game, the program will ask the user whether or not to play again. When the user enters a response other than 'y' or 'Y', the program will display the number of wins and losses and then terminate. Specifications: Write the program using three functions: main, roll_dice, and play_game. Use the following function prototypes: int roll_dice(void) ; bool play_game(void) ;Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#include <time.h>
#include <strings.h>
#define ALPHABET 26
struct dice
{
int die_1;
int die_2;
int dice_sum;
};
int roll_dice(void);
bool play_game(void);
int main(void)
{
int wins = 0;
int losses = 0;
char choice[2] = "Y";
srand((unsigned)time(NULL));
while (strcasecmp(choice, "N")) {
play_game() ? ++wins : ++losses;
printf("Play again? (y/n): ");
scanf("%1s", choice);
}
printf("wins: %d losses: %d ", wins, losses);
return 0;
}
int roll_dice(void)
{
struct dice;
printf(" Roll dice... ");
roll.die_1 = (rand() % 6) + 1;
roll.die_2 = (rand() % 6) + 1;
roll.dice_sum = roll.die_1 + roll.die_2;
printf("| %d | | %d | ", roll.die_1, roll.die_2);
printf("You rolled: %d ", roll.dice_sum);
return roll;
}
bool play_game(void)
{
bool win = false;
bool win_point = false;
int point = 0;
struct dice game;
game = roll_dice();
switch(game.dice_sum) {
case 7: case 11: win = true;
break;
case 2: case 3: case 12: win = false;
break;
default: point = game.dice_sum;
}
if (point) {
printf("Your point is %d ", point);
do {
game = roll_dice();
if (game.dice_sum == 7) {
win_point = true;
win = false;
printf("Bad luck, Snake Eyes! ");
}
if (game.dice_sum == point) {
win_point = true;
win = true;
}
} while (win_point == false);
}
printf("You %s ", win ? "Won!" : "Lost... :-(");
return win;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.