What you need and what you will build

You need a terminal, a text editor, and Node.js 18 or newer. Check your installation by running node --version in the terminal. This project uses Node.js built-in modules, so you do not need to install a package or create a package.json file. You can work in any empty folder where you have permission to save a file.

The game will choose a whole number from 1 through 100. The player gets seven valid guesses. After each incorrect guess, the game says whether the guess was too high or too low. If the player finds the number, the game ends immediately; otherwise, it reveals the answer when the guesses run out.

Plan the game before writing code

A short plan keeps the program manageable. First, create an interface for reading lines from the terminal. Next, choose the secret number and set the number of remaining guesses. Then repeat three actions: ask for input, check whether it is a valid guess, and compare it with the secret number. Finally, close the input interface so the program can exit.

This version does not count invalid input as a guess. That means the program should validate an answer before reducing the remaining count. It should also stop asking questions as soon as the player wins. Those two decisions determine where the validation and return statements belong in the loop.

Write and run the program

Create a file named guess.js and put the following code in it. Save the file, open a terminal in the same folder, and run node guess.js. Type a number and press Enter whenever the program asks for a guess.

const readline = require('node:readline/promises'); const { randomInt } = require('node:crypto'); const { stdin, stdout } = require('node:process'); async function main() { const rl = readline.createInterface({ input: stdin, output: stdout }); const target = randomInt(1, 101); let remaining = 7; console.log('Guess the number from 1 to 100. You have seven guesses.'); try { while (remaining > 0) { const answer = (await rl.question('Your guess: ')).trim(); if (!/^[0-9]+$/.test(answer)) { console.log('Enter a whole number from 1 to 100.'); continue; } const guess = Number(answer); if (!Number.isInteger(guess) || guess < 1 || guess > 100) { console.log('Enter a whole number from 1 to 100.'); continue; } remaining -= 1; if (guess === target) { console.log('You got it!'); return; } console.log(guess < target ? 'Too low.' : 'Too high.'); console.log(`${remaining} guesses left.`); } console.log(`Out of guesses. The number was ${target}.`); } finally { rl.close(); } } main().catch((error) => { console.error('Could not finish the game:', error.message); process.exitCode = 1; });

Understand the important pieces

The readline interface handles terminal input. Its question method waits for a response, so main is declared async and uses await. The call to randomInt(1, 101) selects a number starting at 1 and below 101, giving the game its intended range. The target is chosen once, outside the loop; choosing it inside the loop would change the answer between guesses.

Terminal input arrives as text, even when someone types digits. The regular expression accepts one or more digits and rejects blank answers, minus signs, and decimal points. Number converts that text to a value, and the following check enforces the allowed range. If either check fails, continue starts another loop iteration before a guess is deducted.

For a valid guess, the program reduces remaining and compares the number with the target. A correct guess triggers return, ending main. An incorrect guess produces a hint and the number of guesses left. The finally block closes the input interface whether the loop finishes normally or the player wins.

Try edge cases and make it your own

Run the game several times and try a blank line, a word, a decimal, 0, and 101. Each should prompt you again without using an attempt. Then try valid guesses and check that the count falls by one each time. Because the answer changes on each run, you can use the high and low hints to narrow the range rather than expecting the same sequence to work twice.

For a small extension, change the range or the number of attempts. Update both the code and the welcome message so they agree. You could also add a replay option after a round ends. Keep each change small, run the program again, and check the behavior you expected before adding another feature.

Back to category ↗