dice-gui/src/dice.c
2025-09-18 12:11:13 +02:00

82 lines
2.2 KiB
C

#include "dice.h"
#include <memory.h>
int Die_Roll(enum Die_Dice die) {
int const max = die;
return (rand() % max) + 1;
}
static int current_active_count = 0;
static enum Die_Dice active_dice_set[MAX_ACTIVE_DICE];
static struct Die_ResultType roll_results[MAX_ACTIVE_DICE];
static struct Die_ResultType roll_total = {
.roll = 0, .string_len = 0
};
static
struct Die_ResultType Die_RollToResultType(int roll, enum Die_Dice die) {
struct Die_ResultType result = { };
result.roll = roll;
if (die == COIN) {
result.string_len = SDL_snprintf(result.string, MAX_ROLL_STR_LEN, roll == 1 ? "H" : "T");
} else {
result.string_len = SDL_snprintf(result.string, MAX_ROLL_STR_LEN, "%d", roll);
}
result.clay_string = (Clay_String) {
.chars = result.string,
.length = result.string_len,
.isStaticallyAllocated = false
};
return result;
}
enum Die_Dice const *Die_GetActiveSet(size_t *out_length) {
if (out_length != nullptr) {
*out_length = current_active_count;
}
return active_dice_set;
}
size_t Die_AddToActiveSet(enum Die_Dice die) {
if (current_active_count >= MAX_ACTIVE_DICE) {
return MAX_ACTIVE_DICE;
}
active_dice_set[current_active_count] = die;
roll_results[current_active_count] = Die_RollToResultType(die, die);
return current_active_count++;
}
void Die_RemoveFromActiveSet(size_t index) {
memcpy(active_dice_set + index, active_dice_set + index + 1, MAX_ACTIVE_DICE - index - 1);
--current_active_count;
}
void Die_RollActiveSet() {
for (size_t i = 0; i < current_active_count; ++i) {
roll_results[i] = Die_RollToResultType(Die_Roll(active_dice_set[i]), active_dice_set[i]);
roll_total.roll += roll_results[i].roll;
}
roll_total.string_len = SDL_snprintf(roll_total.string, MAX_ROLL_STR_LEN, "%d", roll_total.roll);
}
struct Die_ResultType *Die_GetLastResult(size_t *out_length) {
if (out_length != nullptr) {
*out_length = current_active_count;
}
return roll_results;
}
Clay_String Die_ToString(enum Die_Dice die) {
switch (die) {
case COIN: return CLAY_STRING("C");
case D4: return CLAY_STRING("4");
case D6: return CLAY_STRING("6");
case D8: return CLAY_STRING("8");
case D10: return CLAY_STRING("10");
case D12: return CLAY_STRING("12");
case D20: return CLAY_STRING("20");
case D100: return CLAY_STRING("100");
}
}