Project: Number Guessing Game
Build a deterministic game engine with private state and an interactive console loop.
By the end, you’ll be able to…
- Design a factory with a clear game contract and private attempt state.
- Implement guess feedback, attempt limits, and reset behavior.
- Drive the engine from a console loop and verify it with deterministic tests.
01The contract before the code
You will build a small game engine and a console driver around it. The engine is created with makeGame(secret, maxAttempts). It returns an object with guess, reset, and read-only getters for attempts, remaining, and solved. The secret is an integer from 1 to 100, and maxAttempts defaults to 5. Keeping the secret in the factory closure means the driver cannot accidentally change it.
Each guess returns a fresh result object: { feedback, attempts, remaining }. feedback is exactly one of 'too low', 'too high', 'correct', or 'out of attempts'. Invalid input throws a specific error instead of silently corrupting the count. Build in four steps: create private state, implement guess, add reset and getters, then write a loop that reads guesses and prints feedback.
02Step 1: Build the engine
Start with validation. Number.isInteger rejects strings, decimals, NaN, and Infinity. The secret must also be between 1 and 100, while maxAttempts must be at least 1. Throw RangeError with a message that names the accepted range. These checks run once, when the game is created, so the rest of the engine can trust its inputs.
Inside the factory, declare attempts and solved with let. Return an object whose methods close over those variables. The getters expose snapshots without allowing assignment. reset sets both variables back to their starting values, which makes the engine reusable in tests and in a replay loop.
03Step 2: Understand guess and its limits
guess first validates the proposed number. It then checks whether the game has already ended. A solved game or an exhausted game returns 'out of attempts' without incrementing the count. This makes the method safe to call repeatedly: the caller cannot buy extra attempts by guessing again.
For a live guess, increment attempts before comparing, because this guess now counts. A correct guess sets solved and returns 'correct'. Otherwise compare with the secret and return 'too low' or 'too high'. remaining is maxAttempts - attempts and may be zero on the final wrong guess.
The result object is a snapshot. It is not the game state, so storing it and reading it later will not change. Use game.attempts or game.solved when you need the current truth.
04Step 3: Add the console loop
The driver generates a secret, creates the game, and opens a readline interface. The loop continues while the game is unsolved and attempts remain. Number(raw) converts the input; Number.isInteger rejects blank lines and text before the engine is called. A continue statement skips to the next prompt without wasting an attempt.
Print the attempt number and feedback after each valid guess. When the loop ends, distinguish a win from an exhausted game and reveal the secret only in the second case. Wrap the loop in try/finally so the readline interface closes even if an error occurs. Run the file with Node.js.
05Review checklist
Check the engine without the console. Create a game with a known secret and a small attempt limit, then assert each feedback string, the attempt count, and remaining. Try guessing after a win, after the limit, and after reset. Reset should restore attempts to zero and solved to false.
Then check the driver by playing a full round. Enter a non-number, a decimal, and an out-of-range value; each should be rejected without consuming an attempt. Confirm that a win stops the loop and that an exhausted game reveals the answer. Finally, read the code aloud: every function should have one job, every branch should return the same result shape, and no state should live outside the factory.
The ideas worth keeping.
- A factory can hide the secret and attempt state behind a small, predictable API.
- Every guess should return the same result shape, including the out-of-attempts case.
- A deterministic test script and a console driver exercise the same engine from different angles.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Add a hint budget
Extend the engine with a hintsRemaining getter and a useHint() method. Start with two hints, return the secret's parity as 'even' or 'odd', and return null when no hints remain. Each successful hint reduces the budget, and reset restores it.
Explore a worked solution
function makeHintGame(secret, maxAttempts = 5) { let attempts = 0; let solved = false; let hints = 2; return { guess(number) { if (solved || attempts >= maxAttempts) { return { feedback: 'out of attempts', attempts, remaining: 0 }; } attempts += 1; solved = number === secret; return { feedback: solved ? 'correct' : number < secret ? 'too low' : 'too high', attempts, remaining: maxAttempts - attempts, }; }, useHint() { if (solved || hints === 0) return null; hints -= 1; return secret % 2 === 0 ? 'even' : 'odd'; }, reset() { attempts = 0; solved = false; hints = 2; }, get hintsRemaining() { return hints; }, get attempts() { return attempts; }, };}const game = makeHintGame(42);console.log(game.useHint());console.log(game.useHint());console.log(game.useHint());console.log(game.hintsRemaining);game.reset();console.log(game.hintsRemaining);hints is another closure variable, so the budget is private. useHint returns a useful string while hints remain, then null once the budget is spent. reset restores the budget along with the attempt state. The output is even, even, null, 0, 2.
Exercise 2: Test the feedback loop deterministically
Write playScripted(game, guesses) that accepts a game object, submits each guess, collects the result objects, and stops when the feedback is 'correct' or 'out of attempts'. Do not create the game inside the function. Test it with a small test game for secret 30 and three attempts against [10, 50, 30].
Explore a worked solution
function playScripted(game, guesses) { const results = []; for (const guess of guesses) { const result = game.guess(guess); results.push(result); if (result.feedback === 'correct' || result.feedback === 'out of attempts') { break; } } return results;}function makeTestGame(secret, maxAttempts = 3) { let attempts = 0; return { guess(number) { if (attempts >= maxAttempts) { return { feedback: 'out of attempts', attempts, remaining: 0 }; } attempts += 1; return { feedback: number === secret ? 'correct' : number < secret ? 'too low' : 'too high', attempts, remaining: maxAttempts - attempts, }; }, };}console.log(playScripted(makeTestGame(30, 3), [10, 50, 30]));The driver depends on the guess contract rather than on a particular factory, so the real makeGame can replace the small test game unchanged. The script removes the randomness of input, so the results can be asserted exactly. The first guess is too low, the second is too high, and the third is correct, ending the loop after three result objects.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Add a hint budget
Extend the engine with a hintsRemaining getter and a useHint() method. Start with two hints, return the secret's parity as 'even' or 'odd', and return null when no hints remain. Each successful hint reduces the budget, and reset restores it.
even even null 0 2
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
Pause. Put the pieces together.
You’ve reached the end of Functions & Program Design. Before moving on, use this task to check what you can do independently.
Implement a deterministic number-guessing game engine and play a full round through its public functions.
Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.
Review this moduleOne lesson closer.
Reading is a start. Trying it yourself makes the connection.