Hide
Meet people who work on similar things as you – get help if you need it Join Siafoo Now or Learn More

Roll N Dice with M Sides Atom Feed 0

In Brief Pretty self-explanatory, with an example you can compile in by defining the compiler variable TEST.
# 's
 1/*_|_|   ROLLDICE.C
2_|_|_| A function to roll a definable number of dice (1 - 100),
3_|_|_| with a definable number of sides (2 to 255).
4_|_|_| No warrantees or guarantees are given or implied.
5_|_|_| Released to PUBLIC DOMAIN by Kurt Kuzba. (8/25/96)
6*/
7
8#include <stdlib.h>
9
10static int rnd(int min, int max)
11{
12 long t = (long)rand() * (long)(max - min + 1);
13 return min + (int)(t / RAND_MAX);
14}
15
16char *roll_dice(int d, int s)
17{
18 char *result = malloc(d * s + 1);
19 int shuffle_loop, die, side, temp, random;
20
21 if (result == NULL)
22 return NULL;
23 *(result + d * s) = '\0';
24
25 /* initialize your dice */
26
27 for (die = 0; die < d; die++)
28 {
29 for (side = 0; side < s; side++)
30 *(result + die * s + side) = (char)(side + 1);
31 }
32 for (shuffle_loop = 0; shuffle_loop < 16; shuffle_loop ++)
33 {
34 /* 'roll' your dice */
35
36 for (die = 0; die < d; die++)
37 {
38 for (side = 0; side < s; side++)
39 {
40 random = rnd(1, s) - 1;
41 temp = *(result + die * s + side);
42 *(result + die * s + side) =
43 *(result + die * s + random);
44 *(result + die * s + random) = (char)temp;
45 }
46 }
47 }
48 for (die = 0; die < d; die++) /* Make an 'upside' string */
49 *(result + die) = *(result + die * s);
50 *(result + d) = '\0'; /* Trim str for # of dice */
51 return result;
52}
53
54#ifdef TEST
55
56#include <stdio.h>
57#include <time.h>
58#include <string.h>
59#include <conio.h>
60
61int main(int c, char *v[])
62{
63 time_t t;
64 int dice, sides;
65 char *d;
66
67 srand((unsigned)time(&t));
68 dice = atoi(v[1]);
69 d = strchr(v[1], 'd');
70 sides = atoi(++d);
71 if (d == NULL || dice < 1 || dice > 100 || sides < 2 || sides > 255)
72 return !!puts("USAGE EX: ROLLDICE 2d6 (rolls 2 6-sided dice)");
73 d = roll_dice(dice, sides);
74 if (d == NULL)
75 return !puts("Malloc Failure.");
76 dice = sides = 0;
77 while (d[dice])
78 {
79 sides += d[dice];
80 printf("%d ", d[dice++]);
81 }
82 printf("\nYour total = %d\n", sides);
83 free(d); /* Make sure you free your dice after every usage!! */
84 return 0; /* Otherwise, you will leak away all your memory!!! */
85}
86
87#endif /* TEST */
88
89/*_|_| end ROLLDICE.C */

Pretty self-explanatory, with an example you can compile in by defining the compiler variable TEST.