Introduction
A simple game that hides two interesting ideas. First, enum class makes moves and outcomes type-safe. Second, the opponent can adapt: it counts your moves and plays whatever beats your most common one. A seeded linear congruential generator makes every game reproducible, which is what lets the test compare exact output.
Problem statement
Objectives
- Model fixed choices with enum class and switch
- Write a tiny pseudo-random number generator
- Keep opponent state in a class
- Implement a simple frequency-based strategy
Features
- Random or adaptive opponent
- Best-of-N matches (even numbers are rounded up to odd)
- Invalid moves are rejected without consuming a round
- Reproducible games from a seed
Concepts demonstrated
- enum class
- switch
- Pseudo-random numbers
- Object state
- Game loop
System architecture
Move and Outcome are enum classes; beats(m) returns the move that beats m and judge compares two moves using it. Random is a 32-bit LCG. Opponent holds a Random, a mode flag and counts of the player's moves; in adaptive mode, after three observations, it plays beats(most_frequent) unless there is a tie for most frequent, in which case it falls back to random. The game loop in main reads moves until either side reaches best_of / 2 + 1 wins.
Folder structure
Complete source code
Makefile
What each file does
- src/main.cpp
- Enums and helpers (
name,parse_move,beats,judge), theRandomandOpponentclasses, and the match loop. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
7 adaptive 7 rock r lizard r p r s r p s r p
Testing
- The scripted game uses seed 7 and the adaptive opponent; compare with
tests/expected-output.txt. - Because the player keeps choosing rock, the opponent starts playing paper from round 4.
- Use seed 0 to get a different game every run.
Common errors
warning: control reaches end of non-void function
Some compilers can't tell a switch over an enum class is exhaustive; add a return after the switch, as name does.
The opponent is predictable
That is the point of adaptive mode — vary your moves, or try random mode.
Possible improvements
- Add Rock-Paper-Scissors-Lizard-Spock
- Let the adaptive opponent look at your last two moves (pattern matching)
- Keep statistics across matches in a file
Additional challenges
- 1Write a strategy that beats the adaptive opponent most of the time.
- 2Replace the LCG with std::mt19937 and compare.
- 3Add a two-player hot-seat mode.
Built and tested it yourself? Mark it to update your dashboard.