Search code examples
cwhile-loopdice

Crap games in C


I'm trying to make a craps game where there would be dice rolling to check if it hits the target. I can't be sure what's wrong with my while loop but it keeps running even when the while loop requirement is false. Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int rollDice() {
    int sum, d1, d2;
    sum = 0;
    d1 = (rand() % 6) + 1;
    d2 = (rand() % 6) + 1; 
    sum = d1 + d2;
    printf("Player rolled %d + %d = %d\n", d1, d2, sum);
    return sum;
}

int main() {
    int player, target, tries;
    srand(time(NULL));
    tries = 0;
    player = rollDice();
    target = player;
    if (player == 7 || player == 11) {
        printf("Player wins.\n");
    }
    else if (player == 2 || player == 3 || player == 12) {
        printf("Player loses.\n");
    } else {
        printf("Point is %d. The game continues: \n", target);
        player = rollDice();
    }
    printf("Player is %d, Target is %d.\n", player, target);
    while (target != player || player != 7) {
        player = rollDice();
    }
    return 0;
}

Solution

  • The game ends when a 7 is thrown or when the player's score is thrown again. Hence the while test should be while (target != player && player != 7), not while (target != player || player != 7).

    You must also move the while loop inside the last else block.

    Here is a modified version:

    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    
    int rollDice(void) {
        int sum, d1, d2;
        sum = 0;
        d1 = rand() % 6 + 1;
        d2 = rand() % 6 + 1; 
        sum = d1 + d2;
        printf("Player rolled %d + %d = %d\n", d1, d2, sum);
        return sum;
    }
    
    int main() {
        int player, target, tries;
        srand(time(NULL));
        tries = 0;
        player = rollDice();
        target = player;
        if (player == 7 || player == 11) {
            printf("Player wins.\n");
        } else
        if (player == 2 || player == 3 || player == 12) {
            printf("Player loses.\n");
        } else {
            printf("Point is %d. The game continues:\n", target);
            player = rollDice();
    
            printf("Player is %d, Target is %d.\n", player, target);
            for (;;) {
                if (player == 7) {
                    printf("Pass loses\n");
                    break;
                }
                if (player == target) {
                    printf("Pass wins\n");
                    break;
                }
                player = rollDice();
            }
        }
        return 0;
    }