Introduction
Games are a great way to practise loops and conditions. This one also teaches something many tutorials skip: how pseudo-random numbers work. Instead of relying only on rand(), it implements a tiny linear congruential generator, which means a chosen seed always produces the same game — perfect for testing.
Problem statement
Objectives
- Write nested loops for rounds and attempts
- Implement a linear congruential pseudo-random generator
- Track game statistics across rounds
- Read single-character answers safely with
" %c"
Features
- Seeded (reproducible) or time-based random games
- Seven attempts with higher/lower hints
- Out-of-range guesses are rejected without using an attempt
- Statistics: rounds played, rounds won and best score
Concepts demonstrated
- Loops
- Pseudo-random numbers
- static global state
- Input with scanf
System architecture
next_random advances a 32-bit LCG state (state = 1664525 × state + 1013904223 mod 2³²); random_between maps it to a range. play_round runs one round and returns the attempts used (0 for a loss, −1 if input ended). main reads the seed, loops over rounds and keeps the statistics.
Folder structure
Complete source code
Makefile
What each file does
- src/main.c
- The random generator, the round logic in
play_round, and the round loop with statistics inmain. - 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.
42 25 75 150 50 y 50 75 88 94 91 93 n
Testing
tests/sample-input.txtuses seed 42, whose first two secrets are 50 and 93; compare the output withtests/expected-output.txt.- Enter 0 as the seed to get a different game each run.
- Guess 150 or 0 and check that the attempt counter does not advance.
Common errors
The same number every game
You entered a fixed seed. Use 0 to seed from the clock.
"Play again" is skipped
Read the answer with scanf(" %c", &again) — the space skips the newline left by the previous number.
Possible improvements
- Difficulty levels that change the range and number of attempts
- Save the best score to a file
- Let the computer guess the player's number using binary search
Additional challenges
- 1Prove that binary search always finds the number in at most 7 guesses for 1–100.
- 2Replace the LCG with xorshift32 and compare the sequences.
- 3Add a two-player mode where one player sets the number.
Built and tested it yourself? Mark it to update your dashboard.