Gig11
Gig11

Reputation: 21

Adding the result of X dices with n sides and a constant in C

I have to make a program in which I have to add the result of x dices with n faces plus or minus a constant(C). The input should be a string like this: "xDn+-C" (x, n and C must be a decimal number). For example: "4D5+6" or "6D9-5". The D just means "Dice".

I used a function to randomize the rolls but I don't know how to continue...

void initD6(void) {
    
   srand((unsigned)time( NULL ) );
}

int D6(void) {

   return ((rand()%6)+1);
}

int main(){
   char Dice[4];

   for(i=0; i<5; i++){
     
   Dice[i] = D6();

   return 0;
}

I don't know how should I take that input as a string and the adding or substracting, and also don't know what should I do next.

Upvotes: 0

Views: 51

Answers (2)

Costantino Grana
Costantino Grana

Reputation: 3428

Assuming no errors in the input, a function which solves your task is:

int throw_dice(const char* s) 
{
    int num, sides, res; 
    sscanf(s,"%iD%i%i", &num, &sides, &res);
    for (int i = 0; i < num; ++i) {
        res += rand() % sides + 1;
    }
    return res; 
}

For simple string parsing sscanf() is a pretty good function. For more complex tasks it's better to use a regular expression library.

As usual, don't relay on rand() for anything but the most simple dice games, with no money involved.

You can try it with the following full example:

#include <stdio.h>

int throw_dice(const char* s) 
{
    int num, sides, res; 
    sscanf(s,"%iD%i%i", &num, &sides, &res);
    for (int i = 0; i < num; ++i) {
        res += rand() % sides + 1;
    }
    return res; 
}

void throw_multiple_times(const char* s, int times)
{
    printf("%s: ", s);
    for (int i = 0; i < times; ++i) {
        printf("%i ", throw_dice(s));
    }
    printf("\n");
}

int main(void) 
{
    srand((unsigned)time(NULL));
    const char* s;
    
    throw_multiple_times("4D5+6", 100);
    throw_multiple_times("6D9-5", 100);

    return 0;
}

Test it here.

Upvotes: 1

Miguel Sandoval
Miguel Sandoval

Reputation: 181

  1. Add a struct:
    struct rules
    {
        int dices;
        int facesPerDice;
        int offset;
    };
  1. Solve the dice problem:
    int throwDice(int faces)
    {
        return (rand() % faces) + 1;
    }
    
    int playGame(struct rules rules)
    {
        int result = 0;
        
        for (int i = 0; i < rules.dices; i++)
            result += throwDice(rules.facesPerDice);
        
        return result + rules.offset;
    }
  1. Solve the parsing problem:
    /**
        Converts a string to a unsigned int until an invalid character is found or a null character is found.
        
        You should replace this with the function you normally use to convert a string to a integer.
    */
    unsigned int stringToUInt(char *str)
    {
        unsigned int result = 0;
        
        int charindex = 0;
        char currentchar;
        while ((currentchar = str[charindex++]) != '\0')
        {
            if (currentchar < '0' || currentchar > '9')
                break;
            result *= 10;
            result += currentchar - '0';
        }
        
        return result;
    }
    
    /** 
        Reads a string and generates a struct rules based on it.
        
        The string is expected to be given in the following format:
            [uint]'D'[uint]['+' or '-'][uint]
        where:
            the first uint is the number of dices to roll
            the second uint is the number of faces per dice
            the third uint is the offset
            
        Terminates the program if something goes wrong.
    */
    struct rules parse(char *str)
    {
        struct rules result;
        
        result.dices = stringToUInt(str);
        
        while (*(str++) != 'D')
            if (*str == '\0')
                exit(1);
    
        result.facesPerDice = stringToUInt(str);
        
        while (*(str++) != '+' && *(str-1) != '-')
            if (*str == '\0')
                exit(1);
        
        result.offset = stringToUInt(str);
        result.offset *= (*(str-1) == '+' ? 1 : -1);
        
        return result;
    }
  1. Put everything together:
    int main(int argc, char *argv[])
    {
        srand(time(NULL));

        char input[] = "3D6+9"; //You could use console input if you want
        struct rules rules = parse(input);
        int gameResult = playGame(rules);
        printf("Game result: %d\n", gameResult);

        return 0;
    }

Upvotes: 2

Related Questions