Fix stat lookups

This commit is contained in:
Dane Johnson 2022-01-02 14:42:19 -06:00
parent bf55252b9a
commit 67aebee24d
2 changed files with 42 additions and 25 deletions

View File

@ -8,18 +8,20 @@ Storybook::Storybook(FILE* fin) {
pages = CyoaParse(fin);
}
void Storybook::UpdateStat(const char *key, int rel) {
void Storybook::UpdateStat(const char *ckey, int rel) {
std::string key(ckey);
auto it = stats.find(key);
if (it == stats.end()) {
// Key not present
stats[key] = 0;
stats[key] = rel;
} else {
// Key present, add the rel
stats[key] = it->second + rel;
}
}
int Storybook::LookupStat(const char *key) {
int Storybook::LookupStat(const char *ckey) {
std::string key(ckey);
auto it = stats.find(key);
if (it == stats.end()){
stats[key] = 0;
@ -54,36 +56,48 @@ void Storybook::Advance() {
}
}
void Storybook::Advance(int choice_key) {
void Storybook::Advance(int choice_option) {
// TODO throw an exception if the ending type is not choices.
Choice* choice = (*current->footer.choices)[choice_key];
if (!choice) {
if (!IsChoiceAvailable(choice_option)) {
// TODO throw exception?
}
if (auto ck = choice->statcheck) {
int val = LookupStat(ck->stat);
if (ck->rel == STATCHECK_GT && val < ck->value ||
ck->rel == STATCHECK_LT && val > ck->value) {
// TODO throw different exception?
}
}
if (auto cg = choice->statchange) {
Choice* choice = (*current->footer.choices)[choice_option];
if (statchange_t *cg = choice->statchange)
UpdateStat(cg->stat, cg->addend);
}
Find(choice->id);
}
void print_choice(Choice* c) {
printf("%d) %s", c->option, c->flavor);
if (c->statcheck) {
printf("(%s %d%c)",
c->statcheck->stat,
c->statcheck->value,
c->statcheck->rel == STATCHECK_GT ? '+' : '-');
bool Storybook::IsChoiceAvailable(int choice_option) {
Choice* choice = (*current->footer.choices)[choice_option];
if (!choice)
return false;
statcheck_t *ck = choice->statcheck;
if (ck) {
int val = LookupStat(ck->stat);
if (ck->rel == STATCHECK_GT && val < ck->value ||
ck->rel == STATCHECK_LT && val > ck->value)
return false;
}
return true;
}
void Storybook::print_choice(Choice* c) {
if (!IsChoiceAvailable(c->option))
printf("\033[;31m"); // Red background
printf("%d) %s", c->option, c->flavor);
if (c->statchange) {
printf("(%s %+d)",
c->statchange->stat,
c->statchange->addend);
}
if (!IsChoiceAvailable(c->option))
printf("\033[;0m");
printf("\n");
}

View File

@ -10,8 +10,10 @@
class Storybook {
private:
std::vector<Page*> pages;
std::unordered_map<const char*, int> stats;
std::unordered_map<std::string, int> stats;
Page *current;
void print_choice(Choice *c);
public:
Storybook(FILE* fin);
@ -24,6 +26,7 @@ public:
void Find(const char*);
void Advance(); // For Goto and End cases
void Advance(int); // For Choices
bool IsChoiceAvailable(int);
bool IsEnded = false;
// This will probably be moved to the cli driver