Search code examples
carraysdie

Specific dice to reroll in C


I am working on a game of Yahtzee and one part of the game is the user can choose which dice out of 5 they wish to re-roll. I don't really know how to approach this besides writing a ton of if if-else statements, but there has to be a more efficient way to re-roll the specific die/ dice. I wrote out a snippet of what I am trying to accomplish, its not exactly like this in my actual code, but hopefully it is enough to answer the question :)

#include<stdio.h>

int main(void)
{
    int die1 = 0, die2 = 0, die3 = 0, die4 = 0, die5 = 0;
    int *ptr_die1 = &die1, *ptr_die2 = &die2, *ptr_die3 = &die3, *ptr_die4 = &die4, *ptr_die5 = &die5;
    int choice = 0;
    int die[5] = { 0 };


    for (int i = 0; i < 5; i++)
    {
        die[i] = rand() % 6 + 1;
    }



    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);


    choice = printf("Please select which die to reroll\n");
    scanf("%d", &choice); 

    printf("%d\n", choice);

    for (int i = 0; i < 5; i++)
    {
        die[choice-1] = rand() % 6 + 1;
    }

    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);

    return 0;
}

after this I am really lost on how to change the die because the user could want to change just 1, or all 5 or any combination in between...


Solution

  • You have way too many variables that are not really needed.

    int main(int argc, char **argv) 
    {
      int i;
      int choice;
      int dices[5];
      srand(time(NULL));
    
      while(1){
        for (i = 0; i < 5; i++)
          dices[i] = rand() % 6 + 1;
    
        choice = printf("Please select which die to reroll (or enter 0 to quit)");
        scanf("%d", &choice);
        if (choice == 0)   // end the game
           break;    
        if (choice < 1 || choice > 5 ){  // make sure that input is valid
          fprintf(stderr, "error, input should be between 1 to 5 (inclusive)\n");
          return -1;
        }
        printf("dice shows: %d", dices[choice-1]);
      }
      return 0;
    }
    

    You need to ask the user for the ending it, e.g. "Enter 0 to end the game". Otherwise it would be an infinite loop.