Number Guessing
Time to build games. The five console games in this section are deliberately small: no graphics, no engine, just state, rules and input. They teach the program structure every game needs, and you can run and change all of them in the browser.
The first one is the classic: the computer picks a secret number, the player guesses, and the game answers "higher" or "lower" until the guess is right.
Randomness you can replay
Games need random numbers, but unrepeatable randomness makes bugs impossible to reproduce. The fix is a seeded random number generator: the same seed always produces the same sequence. Games use this everywhere: procedural levels ("share your seed"), replays, speedrun categories and deterministic multiplayer.
using System;
foreach (int seed in new[] { 7, 7, 42 })
{
var rng = new Random(seed);
Console.Write(quot;seed {seed,2}: ");
for (int i = 0; i < 5; i++) Console.Write(quot;{rng.Next(1, 101),3} ");
Console.WriteLine();
}seed 7: 39 88 67 6 37
seed 7: 39 88 67 6 37
seed 42: 67 15 13 53 17
The two seed-7 rows are identical. rng.Next(1, 101) returns a number from 1 to 100: the lower bound is inclusive, the upper bound exclusive.
Note:
new Random()without a seed picks a different sequence each run, which is what a shipped game usually wants for a new round. Log the seed you used, and a player's bug report can be replayed exactly. Also note that .NET doesn't promise the same sequence for a seed across .NET versions; for saves or multiplayer that must match forever, use your own small generator.
The game
A real console game reads guesses with Console.ReadLine():
Console.Write("Your guess: ");
string? line = Console.ReadLine();The examples on this site can't read from the keyboard, so the player's input comes from a script: an array of lines that stands in for what a player would type. Everything else is exactly what the real game does, including handling bad input:
using System;
var rng = new Random(2026);
int secret = rng.Next(1, 101);
string[] typed = { "50", "abc", "25", "150", "12", "18", "15", "16" }; // what the player types
const int maxTries = 7;
int tries = 0;
bool won = false;
Console.WriteLine("I'm thinking of a number from 1 to 100.");
foreach (string line in typed)
{
Console.Write(quot;Guess #{tries + 1}: {line,-4} ");
if (!int.TryParse(line, out int guess) || guess < 1 || guess > 100)
{
Console.WriteLine("-> please type a number from 1 to 100 (doesn't count)");
continue;
}
tries++;
if (guess == secret) { Console.WriteLine(quot;-> correct in {tries} tries!"); won = true; break; }
Console.WriteLine(guess < secret ? "-> higher" : "-> lower");
if (tries == maxTries) break;
}
if (!won) Console.WriteLine(quot;Out of tries. It was {secret}.");I'm thinking of a number from 1 to 100.
Guess #1: 50 -> lower
Guess #2: abc -> please type a number from 1 to 100 (doesn't count)
Guess #2: 25 -> lower
Guess #3: 150 -> please type a number from 1 to 100 (doesn't count)
Guess #3: 12 -> higher
Guess #4: 18 -> lower
Guess #5: 15 -> higher
Guess #6: 16 -> correct in 6 tries!
Three habits from this tiny game carry into every larger one:
- Validate every input.
int.TryParseinstead ofint.Parse: a player typing "abc" must never crash the game. Out-of-range values get a friendly message and don't cost a try. - Keep the rules in one place. The win check, the try limit and the hint all live in the loop body; nothing else changes
triesorsecret. - End states are explicit. The game ends by winning or by running out of tries, and each prints its own message.
A computer player
Because the input is just data, a program can play the game. The best strategy is binary search: always guess the middle of the range that is still possible. This bot plays three rounds with different seeds:
using System;
foreach (int seed in new[] { 1, 2, 3 })
{
var rng = new Random(seed);
int secret = rng.Next(1, 101);
int low = 1, high = 100, tries = 0;
string trace = "";
while (true)
{
int guess = (low + high) / 2;
tries++;
trace += guess + " ";
if (guess == secret) break;
if (guess < secret) low = guess + 1; else high = guess - 1;
}
Console.WriteLine(quot;seed {seed}: secret {secret,3}, found in {tries} tries: {trace.TrimEnd()}");
}seed 1: secret 25, found in 2 tries: 50 25
seed 2: secret 78, found in 5 tries: 50 75 88 81 78
seed 3: secret 30, found in 7 tries: 50 25 37 31 28 29 30
Binary search never needs more than 7 guesses for 100 numbers, because 2⁷ = 128 ≥ 100. That's why the game above allows exactly 7 tries: a perfect player always wins, a careless one doesn't. Balancing a game often comes down to arithmetic like this.
Make it yours
- Add difficulty levels: 1–50 with 6 tries, 1–1000 with 10 tries. (How many tries does binary search need for 1000?)
- Print "warmer"/"colder" by comparing the distance to the previous guess.
- Keep a best score across rounds.
Test yourself
Why use a seeded random number generator during development?
- It is faster
- The same seed reproduces the same sequence, so bugs and levels can be replayed
- It makes numbers more random
- Unseeded generators are deprecated
What range does rng.Next(1, 101) return?
- 0 to 100
- 1 to 101
- 1 to 100
- 0 to 101
Why does the game use int.TryParse instead of int.Parse?
- It is shorter
- Invalid text returns false instead of throwing, so bad input can't crash the game
- It rounds decimals
- It reads from the keyboard