Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Refactoring case study

Functionator: Extracting a State Model

A runnable refactoring slice of a 1,017-line RPG

IntermediateDesktop C++17 · runnable source

What you will learn

The complete source

game.cpp

game.cpp
#include "game.h"
#include <algorithm>

bool bossUnlocked(const Player& player) {
    return std::all_of(player.cores.begin(), player.cores.end(), [](bool owned) { return owned; });
}

bool buyPotion(Player& player) {
    constexpr int price = 8;
    if (player.gold < price) return false;
    player.gold -= price;
    ++player.potions;
    return true;
}

void grantCore(Player& player, Core core) {
    const auto index = static_cast<std::size_t>(core);
    player.cores.at(index) = true;
}
Source integrity

SHA-256 a7b666f811179d5c34f8ea7aae5a50da160120ba407ec98a5a3057a997f0bb08. Display, copy and approved download use the same source.

game.h

game.h
#pragma once
#include <array>
#include <string>

enum class Core { negative, zero, positive };
struct Player {
    std::string name = "Demo";
    int hp = 35;
    int potions = 2;
    int gold = 15;
    std::array<bool, 3> cores{{false, false, false}};
};

enum class BattleResult { victory, defeat, escaped };
bool bossUnlocked(const Player& player);
bool buyPotion(Player& player);
void grantCore(Player& player, Core core);
Source integrity

SHA-256 2dd2aba152232af69d45d26166213754281689ab3184c0dfbc428674be8b2f11. Display, copy and approved download use the same source.

main.cpp

main.cpp
#include "game.h"
#include <iostream>
#include <sstream>
#include <string>

// This is a reconstructed state-transition slice, not the complete archived RPG.
int main() {
    Player player;
    std::string line;
    while (std::cout << "1 potion, 2/3/4 record core, 5 status, 0 exit: " && std::getline(std::cin, line)) {
        std::istringstream input(line);
        int choice = -1;
        char extra = '\0';
        if (!(input >> choice) || input >> extra || choice < 0 || choice > 5) {
            std::cout << "Invalid menu choice.\n";
            continue;
        }
        if (choice == 0) break;
        if (choice == 1) std::cout << (buyPotion(player) ? "Potion purchased." : "Insufficient gold.") << '\n';
        else if (choice >= 2 && choice <= 4) grantCore(player, static_cast<Core>(choice - 2));
        else std::cout << "Gold: " << player.gold << ", potions: " << player.potions
                       << ", boss: " << (bossUnlocked(player) ? "unlocked" : "locked") << '\n';
    }
    std::cout << "Session ended.\n";
}
Source integrity

SHA-256 0281b4e79655d7c84f6da587362f16965fdec3f75a6eca3e09ab78d655cf31da. Display, copy and approved download use the same source.

What it does and why it was selected

Functionator is selected as a REFACTORING_CASE_STUDY, not as a pristine full-game capstone. It has genuine functions, state ownership and tested menu behavior, but its input helpers spin at EOF and its shared state conflates several progression concepts. A small reconstructed slice can teach architecture without pretending that rewriting all 1017 lines is necessary or complete.

Actual execution

The modern main creates one Player owner and repeatedly reads complete menu lines. A valid purchase calls buyPotion with a mutable reference, so its gold and potion changes persist in main’s object. Choices 2..4 record possession of one corresponding Core enum. status calls bossUnlocked with a const reference; it derives readiness from all three core flags rather than maintaining a second mutable flag. Zero choice or EOF ends the loop cleanly. The actual sample buys one potion, refuses a second purchase, records three cores, and displays gold 7, potions 3 and unlocked boss state.

Mathematical or state model

This is a deliberately reconstructed state-transition demonstration. Selecting a core does not simulate defeating a guardian. Combat, random loot, story prose, arena and the shop’s full upgrade inventory are outside the slice. The Player struct groups hp, potions, gold and core possession. buyPotion has an affordability precondition and an all-or-nothing transition: it refuses without changing either field or subtracts 8 gold and adds one potion. bossUnlocked is a derived predicate whose truth follows from possession rather than an independently mutable switch.

Design and C++ mechanics

game.h declares the state types and callable interface. game.cpp defines domain operations and includes the header so declarations and definitions are checked together. main.cpp owns the console loop and invokes those operations. Both cpp files must be compiled and linked; including the header alone does not supply compiled function definitions. const Player& permits read-only observation without copying the string and array. Player& permits deliberate mutation. Core conversion happens only after choices 2..4 are validated. An enum BattleResult sketches a preferable victory/defeat/escaped result for future combat extraction; this slice does not implement combat or use that enum yet.

Historical differences and limits

Original-source tests used fresh builds. The untouched interactive game passed decline, a hub tour through diagnostics/shop/rest/locked content, and malformed-token recovery. EOF at the hub repeatedly emitted prompts until the output cap terminated it. A separate harness renamed original main and supplied controlled Player values to verify purchases, insufficient funds, revival, each core, boss unlock/defeat, arena access and idempotent secret rewards. High attack/defense were injected to make those component tests deterministic; that is not evidence of balanced original gameplay or an original starting-state full playthrough. The biology variant is mostly a narrative reskin and inherits the same input architecture.

Useful extensions

Extract combat only after replacing bool survived with a result type that distinguishes victory, escape and defeat. Arena currently compensates by checking enemy.hp<=0 before awarding a reward; preserve that distinction at the interface. Avoid adding save files until input failure, invalid transitions and ownership are explicit. Keep the original giant file in the user’s archive; publish only carefully selected historical excerpts and the explained reconstruction.

Original design

The program first prints its piecewise-function table, then optionally enters a turn-based RPG. Player groups HP, attack, defense, potion counts, gold, arena wins, keys/cores and unlock/upgrade flags. Rooms and battles mutate the same player through references. Enemy records carry combat state. Menu helpers, shop/rest, guardian realms, arena, secret room and boss gating show a real increase in program structure compared with the seed lab.

The three cores control access to the boss, so readiness is a proposition about possession rather than an unrelated mutable fact. Shop actions combine affordability checks and mutations. Secret upgrades have one-time flags. Those are useful state invariants to explain. Much of the original narrative and menu wiring is omitted from the new slice because it is not necessary to teach those invariants.

Actually exercised original paths

Fresh original builds compile. Declining game mode, a hub tour, shop purchase, rest, locked boss, secret denial, arena leave and ordinary quit were run with dummy input. A malformed menu token and an out-of-range menu selection recover in the tested helper. EOF at the hub does not recover: the helper clears failure and retries a permanently exhausted stream, repeating output until the operating-system output cap stops it. The biology variant has the same reproduced EOF failure.

The additional component harness uses the original functions and controlled input but injects strong player stats and relevant flags. It verifies core/key grants, three-core gating, boss defeat, shop price/refusal, rest, defeat revival, escape, one-time secret upgrades and the arena-three threshold. ASan/UBSan pass. Because combat/state were deliberately arranged, this proves those component transitions under test conditions, not ordinary starting-state reachability, balance or a full playthrough. The captured component evidence states the scope explicitly.

Design findings

battleEnemy returns true for both victory and successful escape. Existing callers often compensate with an enemy-health check before rewards, so the ambiguous bool is not proof that every escape grants rewards. It does make contracts harder to follow. A scoped result such as victory/escaped/defeated would make later callers explicit. The new header includes that type as a future extension sketch; its combat behavior is not implemented or claimed.

rewardVictory updates arenaWins, so the identity of callers matters; a variable name alone is insufficient to conclude it measures arena-only victories. Ending text that checks secret access can report unlock rather than actual secret-loot completion. Question answers alter dialogue while guardians still appear; whether answers should gate combat is a design decision. EOF handling and cctype normalization need the same repair as smaller programs: stop on exhausted input and cast bytes to unsigned char before case conversion.

What the new runnable slice preserves

main owns one Player. The header shares its definition and declares operations; game.cpp implements query/mutation functions. bossUnlocked uses all_of on the three possession flags, so readiness cannot go stale in a second mutable field. buyPotion checks funds before subtracting the fixed cost and incrementing count. grantCore accepts a validated scoped enum and sets its corresponding flag, making repeated grants idempotent. The menu parses complete lines and ends cleanly on EOF.

The Player struct is public for visibility. It does not enforce every invariant against arbitrary external writes; the interface assumes the nonnegative state maintained by this slice. An encapsulated class would be useful when the larger application needs stronger guarantees. The separate measurement example demonstrates encapsulation without introducing it merely to make this game look more advanced.

Tests show two purchases with insufficient funds correctly refused, all three core flags unlock the boss, repeated core choice does not duplicate possession, malformed choices recover, status queries reflect current state, and EOF terminates. No battle, story completion, audio, role selector or complete original save-state system is present. The detailed source walkthrough and exact annotations reside in programs/functionator-refactor/README.md.

Mechanism diagrams

functionator state · directed transitions
  1. Start / end→Hub
  2. Hubchoice 1→Purchase
  3. Purchaseupdate or refuse→Hub
  4. Hubchoices 2..4→Core
  5. Corepossession true→Hub
  6. Hubchoice 5→Status
  7. Statusderive readiness→Hub
  8. Hubzero or EOF→Start / end
Inspect the supplied Mermaid specification
text
stateDiagram-v2
    [*] --> Hub
    Hub --> Purchase: choice 1
    Purchase --> Hub: update or refuse
    Hub --> Core: choices 2..4
    Core --> Hub: possession true
    Hub --> Status: choice 5
    Status --> Hub: derive readiness
    Hub --> [*]: zero or EOF

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Compile against the declared interface

main.cpp, lines 1–3 →

main.cpp includes the shared declarations rather than copying a second Player definition.

Technical explanation
main.cpp includes the shared declarations rather than copying a second Player definition. game.cpp includes the same header before defining operations. A declaration lets a translation unit type-check calls, but the linker still needs game.cpp’s compiled definitions.
Syntax
A declaration lets a translation unit type-check calls, but the linker still needs game.cpp’s compiled definitions.
Effect on the program
A declaration lets a translation unit type-check calls, but the linker still needs game.cpp’s compiled definitions.
Common mistake
Building main.cpp alone produces unresolved references. A header is not an instruction to compile another cpp file.

multi file buildsfunctions

EOF is a termination condition

main.cpp, lines 10–19 →

The while condition requires getline to succeed.

Technical explanation
The while condition requires getline to succeed. A failed or exhausted input stream ends the loop instead of being cleared and retried indefinitely. A new istringstream consumes one menu line, so malformed conversion cannot poison std::cin for the following line.
Syntax
A new istringstream consumes one menu line, so malformed conversion cannot poison std::cin for the following line.
Effect on the program
A new istringstream consumes one menu line, so malformed conversion cannot poison std::cin for the following line.
Common mistake
The historical helper clears failbit even at permanent EOF, repeatedly requesting input that can never arrive.

input validationloops

Console decisions call domain operations

main.cpp, lines 19–23 →

A purchase is delegated to buyPotion, while record-core choices map validated menu values 2..4 to enum indices 0..2.

Technical explanation
A purchase is delegated to buyPotion, while record-core choices map validated menu values 2..4 to enum indices 0..2. Status uses bossUnlocked to derive readiness from current possession. The interface separates choosing an operation from implementing its state change.
Syntax
The interface separates choosing an operation from implementing its state change.
Effect on the program
The interface separates choosing an operation from implementing its state change.
Common mistake
Recording a core here is a teaching command, not evidence that combat happened. Do not label this slice a fully repaired RPG.

stateenum typesfunctions

State ownership

game.h, lines 6–13 →

The header defines the value type shared by the two translation units.

Technical explanation
The header defines the value type shared by the two translation units. main owns one Player. Its array records three core flags and begins entirely false. The state struct remains public for teaching; it is not an invariant-enforcing class.
Syntax
The state struct remains public for teaching; it is not an invariant-enforcing class.
Effect on the program
The state struct remains public for teaching; it is not an invariant-enforcing class.
Common mistake
Preserve the state preconditions when expanding this interface; the public struct alone does not enforce them.

structsarraysmulti file builds

Derive readiness instead of storing it

game.cpp, lines 4–6 →

std::all_of evaluates the predicate on each possession flag.

Technical explanation
std::all_of evaluates the predicate on each possession flag. It returns true only if every flag is true. const Player& expresses a query, and avoids copying name and array. The caller cannot accidentally make a separate bossUnlocked field disagree with core possession.
Syntax
The caller cannot accidentally make a separate bossUnlocked field disagree with core possession.
Effect on the program
The caller cannot accidentally make a separate bossUnlocked field disagree with core possession.
Common mistake
Preserve the state preconditions when expanding this interface; the public struct alone does not enforce them.

algorithmsreferencesstate

Guard an atomic purchase

game.cpp, lines 8–14 →

The insufficient-funds return happens before either mutation.

Technical explanation
The insufficient-funds return happens before either mutation. A successful path subtracts the constant price and increments potions. Player& aliases main’s existing state, so changes remain visible after the function returns. This public interface assumes the nonnegative state maintained by the slice.
Syntax
This public interface assumes the nonnegative state maintained by the slice.
Effect on the program
This public interface assumes the nonnegative state maintained by the slice.
Common mistake
Preserve the state preconditions when expanding this interface; the public struct alone does not enforce them.

referencesstateconditionals

Idempotent possession

game.cpp, lines 16–19 →

The validated Core enum is converted to the array index.

Technical explanation
The validated Core enum is converted to the array index. Assigning true twice has the same possession effect as assigning it once. This slice does not grant gold or scores for repeat calls, avoiding accidental duplicate reward semantics.
Syntax
This slice does not grant gold or scores for repeat calls, avoiding accidental duplicate reward semantics.
Effect on the program
This slice does not grant gold or scores for repeat calls, avoiding accidental duplicate reward semantics.
Common mistake
Preserve the state preconditions when expanding this interface; the public struct alone does not enforce them.

enum typesarraysstate

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
None
Recorded exit status
0

Program input

1
1
2
3
4
5
0

Program output

1 potion, 2/3/4 record core, 5 status, 0 exit: Potion purchased.
1 potion, 2/3/4 record core, 5 status, 0 exit: Insufficient gold.
1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: Gold: 7, potions: 3, boss: unlocked
1 potion, 2/3/4 record core, 5 status, 0 exit: Session ended.
3 more recorded behavior and error cases
eof
Arguments
None
Recorded exit status
0

Program input

No standard input.

Program output

1 potion, 2/3/4 record core, 5 status, 0 exit: Session ended.
invalid recover
Arguments
None
Recorded exit status
0

Program input

oops
7
5
0

Program output

1 potion, 2/3/4 record core, 5 status, 0 exit: Invalid menu choice.
1 potion, 2/3/4 record core, 5 status, 0 exit: Invalid menu choice.
1 potion, 2/3/4 record core, 5 status, 0 exit: Gold: 15, potions: 2, boss: locked
1 potion, 2/3/4 record core, 5 status, 0 exit: Session ended.
idempotent cores
Arguments
None
Recorded exit status
0

Program input

2
2
3
4
5
0

Program output

1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: 1 potion, 2/3/4 record core, 5 status, 0 exit: Gold: 15, potions: 2, boss: unlocked
1 potion, 2/3/4 record core, 5 status, 0 exit: Session ended.

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp game.cpp -o program
./program

On Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Supporting material

Historical EOF defect — explanatory excerpt, do not execute

Broken historical excerpt for diagnosis. Study the corrected runnable source above; this excerpt is not an execution exercise.

functionator-input-excerpt.cpp.txt
// SANITIZED HISTORICAL EXCERPT, t_functionator.cpp lines 111-129.
// This helper handles malformed tokens but not an exhausted stream.
int getIntInRange(int minValue, int maxValue) {
    int value;
    while (true) {
        cin >> value;
        if (cin.fail()) {
            clearInput();
            cout << "Enter a whole number between " << minValue << " and " << maxValue << ": ";
        } else if (value < minValue || value > maxValue) {
            clearInput();
            cout << "Enter a number between " << minValue << " and " << maxValue << ": ";
        } else {
            clearInput();
            return value;
        }
    }
}
Source integrity

SHA-256 fcb6443a0f1f553839bc4c73f1cedab13743edfa22f341c4e2d0363eff64ae0b. Display, copy and approved download use the same source.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 4 recorded behavior/error cases and 4 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Functionator’s optional CMake configuration was inspected but not executed in the supplied package.

Source origin and publication treatment

Reconstructed user source slice

User-supplied origin; no independent authorship or license determination. Instructor code is not included.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.