dice-gui-old/src/dice.cpp

104 lines
2.4 KiB
C++

#include "dice.h"
#include <memory.h>
static size_t activeDiceCount = 0;
static enum Dice_Die activeDice[MAX_ACTIVE_DICE];
static struct Dice_ResultType rollResult[MAX_ACTIVE_DICE];
int Dice_Roll(enum Dice_Die die) {
if (die == COIN) {
return (rand() % 2);
} else {
int const max = die;
return (rand() % max) + 1;
}
}
static
struct Dice_ResultType Dice_RollToResultType(int roll, enum Dice_Die die) {
struct Dice_ResultType result = { };
result.roll = roll;
result.die = die;
return result;
}
enum Dice_Die const *Dice_GetActiveSet(size_t *out_length) {
if (out_length != nullptr) {
*out_length = activeDiceCount;
}
return activeDice;
}
size_t Dice_AddToActiveSet(enum Dice_Die die) {
if (activeDiceCount >= MAX_ACTIVE_DICE) {
return MAX_ACTIVE_DICE;
}
activeDice[activeDiceCount] = die;
rollResult[activeDiceCount] = Dice_RollToResultType(die, die);
return activeDiceCount++;
}
void Dice_RemoveFromActiveSet(size_t index) {
if (index >= MAX_ACTIVE_DICE) {
return;
} else for (size_t i = index; i < activeDiceCount; ++i) {
rollResult[i] = rollResult[i+1];
}
--activeDiceCount;
}
void Dice_ClearActiveSet() {
activeDiceCount = 0;
}
void Dice_RollActiveSet() {
for (size_t i = 0; i < activeDiceCount; ++i) {
rollResult[i] = Dice_RollToResultType(Dice_Roll(activeDice[i]), activeDice[i]);
}
}
struct Dice_ResultType *Dice_GetLastResult(size_t *out_length) {
if (out_length != nullptr) {
*out_length = activeDiceCount;
}
return rollResult;
}
int Dice_GetLastResultTotal() {
int result = 0;
for (size_t i = 0; i < activeDiceCount; ++i) {
result += rollResult[i].roll;
}
return result;
}
Clay_String Dice_ToString(enum Dice_Die die) {
switch (die) {
case NONE: return CLAY_STRING("N/A");
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");
}
return CLAY_STRING("INVALID");
}
Clay_String Dice_ResultToString(Dice_ResultType const &result) {
static char chars[MAX_ROLL_STR_LEN];
Clay_String string = {
false, 0, chars,
};
if (result.die == COIN) {
string.length = SDL_snprintf(chars, MAX_ROLL_STR_LEN, result.roll == 1 ? "H" : "T");
} else {
string.length = SDL_snprintf(chars, MAX_ROLL_STR_LEN, "%d", result.roll);
}
string.chars = chars;
return string;
}