Last active
December 30, 2015 02:29
-
-
Save nixpulvis/7763152 to your computer and use it in GitHub Desktop.
d&d dice rolling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fcntl.h> | |
#include <sys/types.h> | |
#include <sys/uio.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
int roll_dice(int, int); | |
int main(int argc, char const *argv[]) { | |
// Open the random file. | |
int dev_urandom; | |
if ((dev_urandom = open("/dev/urandom", O_RDONLY)) < 0) { | |
perror("opening /dev/urandom"); | |
exit(1); | |
} | |
int grand_total = 0; | |
for (int i = 1; i < argc; i++) { | |
int num_dice = 0; | |
int sides = 0; | |
sscanf(argv[i], "%dd%d", &num_dice, &sides); | |
if (num_dice == 0 || sides == 0) { | |
fprintf(stderr, "Bad dice roll string.\n"); | |
continue; | |
} | |
int total = 0; | |
int rolls[num_dice]; | |
for (int j = 0; j < num_dice; j++) { | |
rolls[j] = roll_dice(dev_urandom, sides); | |
total += rolls[j]; | |
grand_total += rolls[j]; | |
} | |
if (num_dice > 1) { | |
printf("%d (", total); | |
for (int j = 0; j < num_dice; j++) { | |
if (j == num_dice - 1) { | |
printf("%d", rolls[j]); | |
} else { | |
printf("%d ", rolls[j]); | |
} | |
} | |
printf(")\n"); | |
} else { | |
printf("%d\n", total); | |
} | |
} | |
if (argc > 2) { | |
printf("%d in total.\n", grand_total); | |
} | |
// Close the files. | |
close(dev_urandom); | |
} | |
int roll_dice(int file, int sides) { | |
unsigned char random; | |
read(file, &random, sizeof(random)); | |
return random % sides + 1; | |
} |
Author
nixpulvis
commented
Dec 3, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment