DEV Community

Cover image for How to Build a Guess-the-Number Game in Node.js (Step by Step)
Razvan
Razvan

Posted on • Edited on • Originally published at learnbackend.dev

How to Build a Guess-the-Number Game in Node.js (Step by Step)

Welcome to Code in Action, a series where I walk you through coding a small project in Node.js.

Today’s project is a simple but powerful one: a Guess-the-Number game in the terminal.

Here’s what it does:

  1. Asks the user to guess a random number between 1 and 100.
  2. Tells the user if their guess is too high or too low.
  3. Outputs the number of attempts it took to guess correctly.

Here’s a preview:

Guess the Number Game GIF Preview

Ready? Let’s build it.

Step 1: Create the script

Let’s start by creating a new file named guess_the_number.js and opening it in your code editor:

$ touch guess_the_number.js
Enter fullscreen mode Exit fullscreen mode

Step 2: Generate a random number

Inside this file, let’s create a helper function called generateRandomNumber() that returns a random integer between 1 and 100:

function generateRandomNumber() {
  const MIN = 1;
  const MAX = 100;

  return Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Set up the game

Now, let’s define a runGame() function that will generate the secret number, track the number of attempts made by the player, and print a “Welcome” message:

function runGame() {
  const number = generateRandomNumber();
  let attempts = 0;

  process.stdout.write('Welcome to Guess-the-Number!\n');
  process.stdout.write('\nGuess a number: ');
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Capture user input

Let’s set up an event listener that will fire every time the standard input stream receives a 'data' event:

function runGame() {
  const number = generateRandomNumber();
  let attempts = 0;

  process.stdout.write('Welcome to Guess-the-Number!\n');
  process.stdout.write('\nGuess a number: ');

  process.stdin.on('data', function (input) {
    //
  });
}
Enter fullscreen mode Exit fullscreen mode

Then, let’s convert the user input into an integer and increment the attempts counter:

function runGame() {
  // ...
  process.stdin.on('data', function (input) {
    input = parseInt(input.toString().trim());
    attempts++;
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Handle errors and winning condition

Let’s add a first condition that checks if the input is invalid and outputs an error message:

function runGame() {
  // ...
  process.stdin.on('data', function (input) {
    input = parseInt(input.toString().trim());
    attempts++;

    if (isNaN(input)) {
      process.stdout.write('\nError: Please enter a valid number\n');
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Let’s add a second condition that checks if the input equals the secret number, output a “game over” message, and immediately terminate the script’s execution:

function runGame() {
  // ...
  process.stdin.on('data', function (input) {
    input = parseInt(input.toString().trim());
    attempts++;

    if (isNaN(input)) {
      process.stdout.write('\nError: Please enter a valid number\n');
    }
    else if (input === number) {
      process.stdout.write(`\n🏆 You win!\n📈 Attempts: ${attempts}\n`);
      process.exit(0);
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Handle wrong guesses

Let’s add two more conditions that check if the input is higher or lower than the secret number, and output an indicative message accordingly:

function runGame() {
  // ...
  process.stdin.on('data', function (input) {
    input = parseInt(input.toString().trim());
    attempts++;

    if (isNaN(input)) {
      process.stdout.write('\nError: Please enter a valid number\n');
    }
    else if (input === number) {
      process.stdout.write(`\n🏆 You win!\n📈 Attempts: ${attempts}\n`);
      process.exit(0);
    }
    else if (input > number) {
      process.stdout.write('🔺 Too high!\n');
    }
    else {
      process.stdout.write('🔻 Too low!\n');
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Wrap up the script

Let’s output a new prompt at the end of the callback to invite the user to enter a new number and execute the runGame() function at the end of the script:

function runGame() {
  // ...
  process.stdin.on('data', function (input) {
    // ...
    process.stdout.write('\nGuess a number: ');
  });
}

runGame();
Enter fullscreen mode Exit fullscreen mode

Step 8: Put it together

Here’s the complete script for this project:

function generateRandomNumber() {
  const MIN = 1;
  const MAX = 100;

  return Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;
}

function runGame() {
  const number = generateRandomNumber();
  let attempts = 0;

  process.stdout.write('Welcome to Guess-The-Number!\n');
  process.stdout.write('\nGuess the number: ');

  process.stdin.on('data', function(input) {
    input = parseInt(input.toString().trim());
    attempts++;

    if (isNaN(input)) {
      process.stdout.write('\nError: Please enter a valid number\n');
    }
    else if (input === number) {
      process.stdout.write(`\n🏆 You win!\n📈 Attempts: ${attempts}\n`);
      process.exit(0);
    }
    else if (input > number) {
      process.stdout.write('🔺 Too high!\n');
    }
    else {
      process.stdout.write('🔻 Too low!\n');
    }

    process.stdout.write('\nGuess a number: ');
  });
}

runGame();
Enter fullscreen mode Exit fullscreen mode

Step 9: Run the game

Open a new terminal window and run your script with node:

$ node guess_the_number.js 
Welcome to Guess-The-Number!

Guess the number: 10
🔺 Too high!

Guess a number: 1
🔻 Too low!

Guess a number: 5
🔻 Too low!

Guess a number: 7
🔻 Too low!

Guess a number: 9

🏆 You win!
📈 Attempts: 5
Enter fullscreen mode Exit fullscreen mode

You’ll be prompted to start guessing. Keep trying until you hit the right number!

Wrapping up

That’s it — you’ve built a complete CLI game in Node.js!

Along the way, you practiced:

  1. Generating random numbers
  2. Reading and validating user input
  3. Using conditionals to branch logic
  4. Tracking attempts with variables

What’s next?

👉 Want to run this project on your machine?
Download the source code for free at https://learnbackend.dev/code-in-action/guess-the-number

👉 Ready to go pro with backend development?
Join the Learn Backend Mastery Program today — a zero-to-hero roadmap to become a professional Node.js backend developer and land your first job in 12 months.

Top comments (0)