Number Guessing Game
Number Guessing Game — purpose and prerequisites
A guessing game compares a user guess to a hidden target and reports too high, too low, or correct. Keep the comparison pure, so it can be tested deterministically. An interactive CLI can then generate a secret and read input using node:readline/promises.
What you’ll learn
- Explain the purpose of number guessing game.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
Each guess is compared with a fixed target. A real game would choose a random number once and repeat a prompt until success or a maximum attempt count.
Do not regenerate the secret on every turn or the target can change while someone is guessing.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
type Feedback = "too low" | "too high" | "correct";
function guess(target: number, value: number): Feedback {
if (value < target) return "too low";
if (value > target) return "too high";
return "correct";
}
const secret = 7;
for (const n of [3, 10, 7]) console.log(`${n}: ${guess(secret, n)}`);Verified output
3: too low
10: too high
7: correctCompile: npx tsc --strict --target es2022 --module commonjs number-guessing-game.ts; run: node number-guessing-game.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
Each guess is compared with a fixed target. A real game would choose a random number once and repeat a prompt until success or a maximum attempt count.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
Do not regenerate the secret on every turn or the target can change while someone is guessing.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Add an attempts counter and prevent values outside the chosen range of 1–10.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
Each guess is compared with a fixed target. A real game would choose a random number once and repeat a prompt until success or a maximum attempt count.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.