Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Last active December 30, 2015 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nixpulvis/7763152 to your computer and use it in GitHub Desktop.
Save nixpulvis/7763152 to your computer and use it in GitHub Desktop.
d&d dice rolling.
#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;
}
@nixpulvis
Copy link
Author

nixpulvis at snowcone in ~ 
$ roll 2d6 5d8
6 (1 5)
31 (6 5 8 5 7)
37 in total.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment