begin work on a d20 framework
This commit is contained in:
15
dice/CMakeLists.txt
Normal file
15
dice/CMakeLists.txt
Normal file
@@ -0,0 +1,15 @@
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 3.2)
|
||||
|
||||
SET(TARGET "d20-dice")
|
||||
SET(SOURCE
|
||||
"src/dice.c"
|
||||
)
|
||||
|
||||
PKG_CHECK_MODULES(DICE REQUIRED libdice)
|
||||
|
||||
INCLUDE_DIRECTORIES(${DICE_INCLUDE_DIRS})
|
||||
|
||||
ADD_EXECUTABLE(${TARGET} ${SOURCE})
|
||||
TARGET_LINK_LIBRARIES(${TARGET} ${DICE_LIBRARIES})
|
||||
|
||||
INSTALL(TARGETS ${TARGET} DESTINATION ${LIB_DIR})
|
||||
104
dice/src/dice.c
Normal file
104
dice/src/dice.c
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user