Learn / Worked program
Rock Paper Scissors
Explicit moves, invalid input and testable state
What you will learn
- Branch order, validated domains and early returnsLearn conceptDecisions and repetition
- Parameters, cohesive calculation functions and return valuesLearn conceptFunctions as interfaces
- Finite iteration domains and termination conditionsDecisions and repetitionProgram-local teaching concept
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Owned strings, byte normalization and complete linesLearn conceptArrays and strings
- Scoped finite value domainsLearn conceptRecords, enumerations, and classes
- Parse success or failure as distinct statesProgram-local teaching concept
- Engines, distributions, seeding and deterministic test modesProgram-local teaching concept
- Persistent values and explicit state transitionsState, edges, and debouncingProgram-local teaching concept
The complete source
main.cpp
#include <array>
#include <cctype>
#include <iostream>
#include <optional>
#include <random>
#include <string>
enum class Move { rock, paper, scissors };
std::string lower(std::string text) {
for (char& letter : text) letter = static_cast<char>(std::tolower(static_cast<unsigned char>(letter)));
return text;
}
std::optional<Move> parseMove(const std::string& text) {
if (text == "rock") return Move::rock;
if (text == "paper") return Move::paper;
if (text == "scissors") return Move::scissors;
return std::nullopt;
}
int outcome(Move player, Move computer) {
if (player == computer) return 0;
if ((player == Move::rock && computer == Move::scissors)
|| (player == Move::paper && computer == Move::rock)
|| (player == Move::scissors && computer == Move::paper)) return 1;
return -1;
}
int main(int argc, char* argv[]) {
bool demo = false;
if (argc == 2 && std::string(argv[1]) == "--demo") demo = true;
else if (argc != 1) { std::cerr << "Usage: program [--demo]\n"; return 1; }
const std::array<std::string, 3> names{{"rock", "paper", "scissors"}};
std::mt19937 generator(12345); // demo bypasses randomness entirely
if (!demo) generator.seed(std::random_device{}());
std::uniform_int_distribution<int> pick(0, 2);
int wins = 0, losses = 0, ties = 0, rounds = 0;
std::string line;
while (std::cout << "rock/paper/scissors (quit to finish): " && std::getline(std::cin, line)) {
line = lower(line);
if (line == "quit") break;
const auto player = parseMove(line);
if (!player) { std::cout << "Invalid move; no round counted.\n"; continue; }
if (rounds == 10000) { std::cerr << "Round limit reached.\n"; return 1; }
const int computerIndex = demo ? rounds % 3 : pick(generator);
const Move computer = static_cast<Move>(computerIndex);
const int result = outcome(*player, computer);
++rounds;
if (result > 0) ++wins;
else if (result < 0) ++losses;
else ++ties;
std::cout << "Computer: " << names.at(static_cast<std::size_t>(computerIndex)) << '\n'
<< "Result: " << (result > 0 ? "win" : result < 0 ? "loss" : "tie") << '\n';
}
std::cout << "Score wins/losses/ties: " << wins << '/' << losses << '/' << ties << '\n';
}
Source integrity
SHA-256 eae5a74ea842a2ac9edb0c3cc6dcf12f6b1de0c85e368702f63d42c1b1793aba. Display, copy and approved download use the same source.
What it does and why it was selected
Three archived versions reveal a useful progression from scoreboard logic to normalization and input validation. The canonical program combines their useful behavior while fixing invalid moves counted as losses, fragile EOF paths and ambiguous string state. It also makes all three outcomes reproducible without relying on a platform-specific random distribution sequence.
Actual execution
main first accepts either no argument or --demo. Normal play seeds mt19937 from random_device once. Demo mode bypasses the random distribution and cycles rock, paper, scissors using the completed-round count. Each full input line is lowercased. quit stops the session; parseMove returns either a typed Move or an empty optional. Invalid input prints a message and continues without incrementing any score or consuming a demo opponent move. outcome returns zero for tie, positive one for win and negative one for loss. Exactly one counter is incremented for every accepted move.
Mathematical or state model
The three moves form a directed cycle: rock beats scissors, scissors beats paper, paper beats rock. Equal moves tie; after explicit winning pairs are excluded, the remaining valid pairs are losses. That last conclusion depends on both moves being members of the enum’s three-value domain. It would be incorrect to feed an unknown string into the final loss branch. The scoreboard invariant is wins+losses+ties=rounds.
Design and C++ mechanics
std::optional makes parse failure a separate state instead of inventing a sentinel Move. The dereference *player occurs only after testing the optional. enum class gives scoped move names and blocks implicit conversion from random integers; the conversion for the computer follows a proven 0..2 range and declared enum order. lower casts through unsigned char before std::tolower so negative signed-char bytes do not violate the library’s argument domain. This is byte-oriented case normalization, not Unicode case folding.
Historical differences and limits
A fixed mt19937 seed does not guarantee an identical uniform_int_distribution sequence across every standard-library implementation. Demo cycling gives a stable transcript and truth-table tests instead. random_device quality depends on the platform and is not a cryptographic guarantee; cryptography is irrelevant to this game. Full-line input means surrounding spaces are currently rejected rather than silently trimmed. EOF is a normal session end that prints the scoreboard. The 10000-round cap prevents unbounded int score growth in the supported interface.
Useful extensions
Move Score into a record if adding multiple sessions or persistence. Add a best-of match rule only after defining ties and early termination. Keep outcome independently testable across all nine move pairs, and keep opponent generation separate so a strategy can be replaced without changing the rule logic.
Mechanism diagrams
- Read line→quit or EOF?
- quit or EOF?yes→Final score
- quit or EOF?no→Valid move?
- Valid move?no→Read line
- Valid move?yes→Choose opponent
- Choose opponent→Compare moves
- Compare moves→Increment wins
- Compare moves→Increment losses
- Compare moves→Increment ties
- Increment wins→Read line
- Increment losses→Read line
- Increment ties→Read line
Inspect the supplied Mermaid specification
flowchart TD
Input["Read line"] --> Quit{"quit or EOF?"}
Quit -->|yes| Score["Final score"]
Quit -->|no| Parse{"Valid move?"}
Parse -->|no| Input
Parse -->|yes| Opponent["Choose opponent"]
Opponent --> Result{"Compare moves"}
Result --> Win["Increment wins"]
Result --> Loss["Increment losses"]
Result --> Tie["Increment ties"]
Win --> Input
Loss --> Input
Tie --> InputSource-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.
A finite move vocabulary
main.cpp, lines 8–8 →Scoped enumerators separate Move::rock from arbitrary strings or integers.
- Technical explanation
- Scoped enumerators separate Move::rock from arbitrary strings or integers. The computer conversion assumes this declaration order is 0,1,2, a dependency documented in the source. The enum represents accepted semantic choices after parsing, not raw input.
- Syntax
- The enum represents accepted semantic choices after parsing, not raw input.
- Effect on the program
- The enum represents accepted semantic choices after parsing, not raw input.
- Common mistake
- Adding or reordering enumerators requires updating the integer-to-Move mapping used by opponent selection.
- Deeper connection
- Read the program’s mathematical or state model
Respect the cctype argument domain
main.cpp, lines 10–13 →The function receives a string copy, mutates each character through a reference, and returns the normalized value.
- Technical explanation
- The function receives a string copy, mutates each character through a reference, and returns the normalized value. Casting letter through unsigned char converts negative signed-char byte values into a valid domain for tolower. The result is cast back to char for string storage.
- Syntax
- The result is cast back to char for string storage.
- Effect on the program
- The result is cast back to char for string storage.
- Common mistake
- Passing a possibly negative signed char directly to std::tolower can be undefined. This byte normalization is not full Unicode text processing.
- Deeper connection
- Read the program’s mathematical or state model
Parse failure is a real state
main.cpp, lines 15–20 →Recognized strings return a Move value inside the optional.
- Technical explanation
- Recognized strings return a Move value inside the optional. Unrecognized strings return nullopt, which has no Move. The caller’s if(!player) check branches before dereferencing. This prevents an invalid spelling from becoming an automatic computer win.
- Syntax
- This prevents an invalid spelling from becoming an automatic computer win.
- Effect on the program
- This prevents an invalid spelling from becoming an automatic computer win.
- Common mistake
- Choosing a default rock value on parse failure would consume a round and conceal the invalid input.
- Deeper connection
- Read the program’s mathematical or state model
Enumerate ties and winning pairs
main.cpp, lines 22–28 →Equality covers the three tie pairs.
- Technical explanation
- Equality covers the three tie pairs. The disjunction covers the three player-winning ordered pairs. Only after both cases fail does -1 mean loss, because the inputs are already valid Moves. Score updates belong to main, keeping rule evaluation free of state mutation.
- Syntax
- Score updates belong to main, keeping rule evaluation free of state mutation.
- Effect on the program
- Score updates belong to main, keeping rule evaluation free of state mutation.
- Common mistake
- A final else means loss only for a validated domain. The historical files let lizard reach a loss branch.
- Deeper connection
- Read the program’s mathematical or state model
Demo and random generation share one rule engine
main.cpp, lines 46–54 →Demo uses completed-round count modulo three.
- Technical explanation
- Demo uses completed-round count modulo three. Normal play uses the bounded distribution. Both produce 0..2 and are interpreted by the same outcome function. Only an accepted move increments rounds and exactly one score counter. Invalid input therefore leaves the demo sequence and scoreboard unchanged.
- Syntax
- Invalid input therefore leaves the demo sequence and scoreboard unchanged.
- Effect on the program
- Invalid input therefore leaves the demo sequence and scoreboard unchanged.
- Common mistake
- A fixed random seed alone does not guarantee uniform_int_distribution outputs match across standard-library implementations.
- Deeper connection
- Read the program’s mathematical or state model
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
--demo- Recorded exit status
- 0
Program input
rock rock rock quit
Program output
rock/paper/scissors (quit to finish): Computer: rock Result: tie rock/paper/scissors (quit to finish): Computer: paper Result: loss rock/paper/scissors (quit to finish): Computer: scissors Result: win rock/paper/scissors (quit to finish): Score wins/losses/ties: 1/1/1
5 more recorded behavior and error cases
bad choice
- Arguments
--demo- Recorded exit status
- 0
Program input
lizard ROCK quit
Program output
rock/paper/scissors (quit to finish): Invalid move; no round counted. rock/paper/scissors (quit to finish): Computer: rock Result: tie rock/paper/scissors (quit to finish): Score wins/losses/ties: 0/0/1
all nine pairs
- Arguments
--demo- Recorded exit status
- 0
Program input
rock rock rock paper paper paper scissors scissors scissors quit
Program output
rock/paper/scissors (quit to finish): Computer: rock Result: tie rock/paper/scissors (quit to finish): Computer: paper Result: loss rock/paper/scissors (quit to finish): Computer: scissors Result: win rock/paper/scissors (quit to finish): Computer: rock Result: win rock/paper/scissors (quit to finish): Computer: paper Result: tie rock/paper/scissors (quit to finish): Computer: scissors Result: loss rock/paper/scissors (quit to finish): Computer: rock Result: loss rock/paper/scissors (quit to finish): Computer: paper Result: win rock/paper/scissors (quit to finish): Computer: scissors Result: tie rock/paper/scissors (quit to finish): Score wins/losses/ties: 3/3/3
normal random round
- Arguments
None- Recorded exit status
- 0
Program input
rock quit
Program output
rock/paper/scissors (quit to finish): Computer: paper Result: loss rock/paper/scissors (quit to finish): Score wins/losses/ties: 0/1/0
eof
- Arguments
--demo- Recorded exit status
- 0
Program input
No standard input.
Program output
rock/paper/scissors (quit to finish): Score wins/losses/ties: 0/0/0
invalid argument
- Arguments
--unknown- Recorded exit status
- 1
Program input
No standard input.
Program output
No standard output.
Error output
Usage: program [--demo]
Build and run
From this folder, with a configured C++17 compiler:
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program --demoOn Windows GCC, build with -o program.exe and use .\program.exe --demo. 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 --demo.
Desktop compiler setup and platform limits. How headers and translation units fit together.
Verification and provenance
- Source inspected
- Compile verified
- Warning reviewed
- Behavior verified
- Sanitizer checked
Supplied evidence: 6 recorded behavior/error cases and 6 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.
Source origin and publication treatment
Modernized user supplied source
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.