LESSON 16 · BEGINNER4 min read

Project: Number Guessing Game

Build a deterministic game engine with private state and an interactive console loop.

ES2024 / Node.js 20+Free to readModule 3 of 19
YOUR NEXT SMALL WINS

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.

engine-check.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

number-game.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

limit-check.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

play.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

review.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

02

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].

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why is the secret stored in a closure instead of as a property of the returned object?
02What should guess return after a correct guess has already ended the game?
03Why does the console driver wrap the input loop in try/finally?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

EXPECTED OUTPUT
even
even
null
0
2
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

MODULE 03 · PRACTICAL SELF-CHECK

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 module

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.