begin work on a d20 framework

This commit is contained in:
2019-08-25 15:11:36 +02:00
commit 8c77114c01
5 changed files with 207 additions and 0 deletions

104
dice/src/dice.c Normal file
View File

@@ -0,0 +1,104 @@
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <getopt.h>
#include <dice.h>
static bool evaluate_expression(char const *s)
{
dice_expression_t e = dice_expression_new();
int error = 0;
int64_t result = 0;
bool ret = false;
if (e == NULL) {
fprintf(stderr, "oom\n");
goto error;
}
if (!dice_expression_parse(e, s, &error)) {
fprintf(stderr, "failed to parse expression `%s` around column %d\n",
s, error
);
goto error;
}
if (!dice_expression_roll(e, &result)) {
fprintf(stderr, "failed to evaluate expression `%s`", s);
goto error;
}
printf("%ld\n", result);
ret = true;
error:
dice_expression_free(e);
return ret;
}
int main(int ac, char **av)
{
static char const *optstr = "e:";
static struct option opts[] = {
{ "expression", required_argument, NULL, 'e' },
{ NULL, 0, NULL, 0}
};
int c = 0, i = 0;
FILE *f = NULL;
char *buf = NULL;
size_t buflen = 0;
bool ret = false;
while ((c = getopt_long(ac, av, optstr, opts, NULL)) != -1) {
switch (c) {
case 'e':
{
if (!evaluate_expression(optarg)) {
exit(3);
}
} break;
default:
{
fprintf(stderr, "invalid option specified\n");
exit(3);
} break;
}
}
/* parse remainderes
*/
if (optind < ac) {
f = open_memstream(&buf, &buflen);
if (f == NULL) {
exit(3);
}
for (i = optind; i < ac; i++) {
fprintf(f, "%s", av[i]);
if (i < ac) {
fputc(' ', f);
}
}
fclose(f);
ret = evaluate_expression(buf);
free(buf);
buf = NULL;
buflen = 0;
if (!ret) {
exit(3);
}
}
return 0;
}