Back

Activity 2.6 Number Guessing Game

divider

Introduction

Adding simple selection and iteration to our code allows us to build a variety of fun programs. For this activity, we'll apply these concepts to create a classic number guessing game.

Objectives

  • icon Implementing game logic if statements and loops
divider

Activity Tasks

  • icon Create a new project named 2-6-number-game.js.
  • icon Complete each task individually.

Task 1: Initalize Game Data

2-6-number-game.js
let secretNumber = Math.floor(Math.random() * 10) + 1
let guess = 0;
let tries = 0;

Task 2: Implement Core Game Logic

2-6-number-game.js
let secretNumber = Math.floor(Math.random() * 10) + 1
let guess = 0;
let tries = 0;
while (guess != secretNumber) {
guess = parseInt(prompt("Guess the number (1-10):"));
tries++;
if (guess == secretNumber) {
console.log(`Correct! It took you ${tries} tries!`);
}
else if (guess > secretNumber) {
console.log("Wrong! Your guess was too high.");
}
else if (guess < secretNumber) {
console.log("Wrong! Your guess was too low.");
}
}

Task 3: Add Data Validation

  • icon Notify the user if they either enter a number that's out of range or an invalid input.
2-6-number-game.js
let secretNumber = Math.floor(Math.random() * 10) + 1
let guess = 0;
let tries = 0;
while (guess != secretNumber) {
guess = parseInt(prompt("Guess the number (1-10):"));
tries++;
if (guess == secretNumber) {
console.log(`Correct! It took you ${tries} tries!`);
}
else if (guess < 1 || guess > 10) {
console.log("Your guess was out of range.");
}
else if (guess > secretNumber) {
console.log("Wrong! Your guess was too high.");
}
else if (guess < secretNumber) {
console.log("Wrong! Your guess was too low.");
}
else {
console.log("Invalid input."); // NaN
}
}

Task 4: Bonus - Set Difficulty

  • icon Before the core game logic begins, ask the user to choose a difficulty: easy, medium, or hard.
  • icon Based on the difficulty chosen, set an appropriate number range that the user needs to guess.
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Guess the number (1-10): 6
Wrong! Your guess was too high.
Guess the number (1-10): 3
Wrong! Your guess was too low.
Guess the number (1-10): 5
Wrong! Your guess was too high.
Guess the number (1-10): 4
Correct! It took you 4 tries!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. How was the while loop essential for making the game playable more than once.
  2. Where did you use if/else if/else statements to guide the player?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete