Computer Programming 1 (JavaScript) • Problem Solving & Mini-Projects

Building Guessing Game — I can build a guessing game using random numbers, loops, and clear feedback.

Combine random number generation, loops, and conditionals to create an interactive number-guessing game in JavaScript.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Long before sophisticated graphics engines and massive multiplayer worlds, some of the earliest computer programs were text-based games. These simple interactive programs helped pioneer the concepts of user input, random events, and feedback loops that still power every game you play today. The guessing game — where the computer picks a secret number and the player tries to find it — is one of the most iconic beginner programming projects in history.

Understanding how to build a guessing game isn't just about making a fun toy. It teaches you how to combine random number generation, loops, conditionals, and user feedback into a cohesive program — skills that transfer directly to real-world software development.

1956 • Early Computer Games

Early mainframe computers at universities ran simple number-guessing and tic-tac-toe programs, demonstrating that computers could respond interactively to human input.

1975 • BASIC and Home Computing

The BASIC programming language brought guessing games to personal computers. Books like 101 BASIC Computer Games by David Ahl popularized coding through simple game projects.

1995 • JavaScript Is Born

Brendan Eich created JavaScript in just ten days, enabling interactive programs to run directly in web browsers. Guessing games became a popular first project for web developers.

2020s • Modern Interactive Learning

Today, building a guessing game remains a standard introductory project in computer science courses worldwide, teaching foundational programming patterns used in AI, web apps, and game engines.

The core question this lesson addresses is: how do you take individual programming concepts — variables, randomness, loops, conditionals — and combine them into a working, interactive program? By the end, you'll have built a complete guessing game and understood the design thinking behind it.

SECTION 2

Core Principles & Definitions

Before writing any code, let's identify the key building blocks you'll use. Every guessing game relies on a small set of programming concepts working together. Think of these as ingredients in a recipe — each one is simple on its own, but combining them correctly produces something much more interesting.

1

Random Number Generation

JavaScript's Math.random() function produces a decimal between 0 (inclusive) and 1 (exclusive). We scale and round it with Math.floor() to get a whole number in our desired range.
2

Loops (while)

A while loop repeats a block of code as long as a condition is true. This lets the player keep guessing until they find the answer or run out of attempts.
3

Conditionals (if / else if / else)

Conditional statements let your program make decisions. After each guess, the program checks: is the guess too high, too low, or exactly right? Each path triggers different feedback.
4

User Input

The prompt() function displays a dialog box where the user types a value. We convert the string result to a number using Number() or parseInt().
5

Feedback Messages

Clear feedback tells the player what happened and what to do next. Using alert() or console.log(), you guide the player with messages like "Too high!" or "You got it!"
✦

KEY TAKEAWAY

Think of building a guessing game like being a game-show host. You (the computer) pick a secret number backstage (random generation), invite the contestant to guess again and again (loop), tell them "higher" or "lower" after each guess (conditionals and feedback), and celebrate when they finally nail it.

SECTION 3

Visual Explanation — Game Flow Diagram

Before you start coding, it helps to see the overall structure of the program as a flowchart. The diagram below shows every decision point and action in our guessing game, from generating the secret number all the way to the final victory message.

Guessing Game — Program FlowSTARTsecretNumber = random(1–100)Generate secret numberattempts = 0, maxAttempts = 7Initialize countersattempts < max?No"Game Over!"Reveal answerYesguess = prompt("Enter guess")guess == secret?YesWIN!NoPrint "Too high" or "Too low"Loop back ↑
The flowchart shows how the game begins by generating a secret number, then enters a loop where the player guesses repeatedly. Each guess triggers a conditional check: if correct, the player wins; if wrong, the game prints "Too high" or "Too low" and loops back for another attempt.

Notice the diamond-shaped boxes — these represent decision points (conditionals). The rectangular boxes are actions the program takes. The arrow that loops from the feedback box back up to the condition check represents the while loop. This visual pattern — action, decision, loop — appears in almost every interactive program you'll ever build.

SECTION 4

How It Works — Key Code Patterns

Let's break down the three essential code patterns that power the guessing game. Each pattern is a reusable technique you'll use in many future projects.

Pattern 1: Generating a Random Integer

RANDOM INTEGER FORMULA

Math.floor(Math.random()×(max−min+1))+minMath.floor(Math.random() × (max − min + 1)) + min

Math.random() returns a decimal in [0, 1). Math.floor() rounds down to the nearest integer. For a range of 1–100: Math.floor(Math.random() * 100) + 1.

Pattern 2: The While Loop

A while loop checks its condition before each repetition. In our game, the loop continues as long as the player hasn't guessed correctly and hasn't exceeded the maximum number of attempts. The general structure is:

WHILE LOOP STRUCTURE

while(condition)//bodyexecutesrepeatedlywhile (condition) { // body executes repeatedly }

The condition is evaluated before every iteration. When it becomes false, the loop ends and the program continues to the next line after the closing brace.

Pattern 3: Conditional Feedback

Inside the loop, an if / else if / else chain compares the player's guess to the secret number. There are exactly three possible outcomes: the guess is too low, too high, or correct. Each branch provides specific, actionable feedback so the player can adjust their strategy.

CONDITIONAL CHAIN

if(guess<secret)→"Toolow!"∣elseif(guess>secret)→"Toohigh!"∣else→"Correct!"if (guess < secret) → "Too low!" | else if (guess > secret) → "Too high!" | else → "Correct!"

The comparison operators < and > compare numeric values. The final else catches the only remaining case: equality.

⚠

Important: Type Conversion

The prompt() function always returns a string. If a player types "42", JavaScript receives the string "42", not the number 42. Always convert input with Number() or parseInt() before comparing. Otherwise, your comparisons may produce unexpected results!

SECTION 5

Detailed Breakdown — Anatomy of the Complete Program

Now let's look at every section of the complete guessing game program. The diagram below maps each line of code to its purpose, showing how the three patterns — random generation, looping, and conditionals — fit together.

Complete Guessing Game — Code Anatomy// ---- SETUP ----const secret = Math.floor( Math.random() * 100) + 1;let attempts = 0;const maxAttempts = 7;let hasWon = false;// ---- GAME LOOP ----while (attempts < maxAttempts && !hasWon) { // ---- GET INPUT ---- let guess = Number( prompt("Guess 1-100:")); attempts++; // ---- CHECK & FEEDBACK ---- if (guess < secret) { alert("Too low! ⬆"); } else if (guess > secret) { alert("Too high! ⬇"); } else { alert("🎉 You got it in " + attempts + " tries!"); hasWon = true; }}// ---- GAME OVER ---- if (!hasWon) alert("Game over! It was " + secret + ".");🎲 Random GenerationPick secret between 1–100📋 VariablesTrack attempts and win state🔄 While LoopRepeat until win or max tries⌨️ User Inputprompt() + Number conversion🔀 Conditionalsif / else if / else feedback🏁 Game Over CheckShow answer if player lost
The code on the left is color-coded to match the annotation cards on the right. Cyan lines handle random generation, violet handles variable setup, gold marks the while loop boundaries, green marks user input, pink shows the conditional feedback chain, and red handles the game-over message.
Code SectionPurposeKey Concept
const secret = ...Generate a random integer between 1 and 100Math.random(), Math.floor()
let attempts = 0Track how many guesses the player has usedVariable declaration, counter
while (...) { }Repeat the guessing process until win or max triesWhile loop, compound condition
Number(prompt(...))Get user input and convert from string to numberInput, type conversion
if / else if / elseCompare guess to secret and give directional feedbackConditional branching

Each code section maps to a core programming concept

SECTION 6

Worked Example — Tracing a Full Game

Let's trace through a complete game session to see exactly how the code executes. Suppose the secret number is 73 and the player gets 7 maximum attempts. We'll follow the program's logic step by step.

Tracing a Guessing Game (Secret = 73)

  1. 1

    Step 1 — Setup

    The program runs Math.floor(Math.random() * 100) + 1 and gets 73. It sets attempts = 0, maxAttempts = 7, and hasWon = false.
    secret = 73, attempts = 0, hasWon = false
  2. 2

    Step 2 — First Guess: 50

    The while condition 0 < 7 && !false is true, so the loop body executes. The player enters 50. Since 50 < 73, the program displays "Too low! ⬆". The attempt counter increments to 1.
    Output: "Too low! ⬆" — attempts = 1
  3. 3

    Step 3 — Second Guess: 85

    Condition check: 1 < 7 && !false → true. Player enters 85. Since 85 > 73, the program says "Too high! ⬇". Attempts is now 2.
    Output: "Too high! ⬇" — attempts = 2
  4. 4

    Step 4 — Third Guess: 70

    The player narrows the range using the feedback. They guess 70. Since 70 < 73, the output is "Too low! ⬆". The player now knows the answer is between 70 and 85. Attempts = 3.
    Output: "Too low! ⬆" — attempts = 3
  5. 5

    Step 5 — Fourth Guess: 73 — WIN!

    The player guesses 73. The condition guess < secret is false, and guess > secret is also false, so the else branch executes. The program displays the victory message and sets hasWon = true. On the next loop check, the condition !hasWon is false, so the loop ends.
    Output: "🎉 You got it in 4 tries!" — Game Over (WIN)
💡

Binary Search Strategy

Notice how the player used "halving" to narrow the range — guessing roughly in the middle each time. This is actually a famous algorithm called binary search. With this strategy, you can always find any number between 1 and 100 in at most 7 guesses, because log2(100) ≈ 6.64, which rounds up to 7.

SECTION 7

Strengths, Limitations & Enhancements

The basic guessing game works, but like any first draft of a program, there's room for improvement. Understanding the strengths and limitations of your code is a crucial developer skill. Let's evaluate what we've built and explore ways to make it better.

StrengthLimitationPossible Enhancement
Simple, readable code structureNo input validation — crashes on non-numeric inputAdd isNaN() check before comparing
Clear directional feedback (high/low)Uses alert/prompt — blocks the browser UIBuild an HTML form with DOM manipulation
Tracks attempt countNo difficulty levels or adjustable rangeLet user pick easy (1–50), medium (1–100), hard (1–500)
Win/loss conditions are clearNo replay option after the game endsWrap entire game in a function; use confirm() to replay
Uses fundamental concepts applicable everywhereNo score tracking across gamesStore best scores in a variable or localStorage

Evaluating the basic guessing game

✦

KEY TAKEAWAY

Software development is iterative. Your first working version is a minimum viable product (MVP) — a simple version that proves your concept works. Once the MVP is solid, you improve it one feature at a time. This is how professional developers build real applications, from social media platforms to video games.

SECTION 8

Connection to Advanced Concepts

The guessing game may seem simple, but the patterns you've learned here are building blocks for much more sophisticated programs. Let's see how each concept scales up in real-world software development.

Guessing Game ConceptAdvanced Application
Math.random() for secret numberProcedural generation in games (random maps, loot drops); cryptographic random number generation for security
while loop for repeated guessingEvent loops in Node.js servers; game loops that run 60 frames per second; database polling
if/else for feedbackForm validation, routing in web apps, AI decision trees, state machines
User input with prompt()HTML forms, REST API endpoints, voice command processing, chatbot input handling
Binary search guessing strategyDatabase index searching, debugging with bisection, binary search algorithm (O(log n))

From guessing game patterns to professional-level concepts

As you advance in programming, you'll also learn about functions (to organize your game into reusable pieces), DOM manipulation (to replace alert/prompt with real web page elements), and event-driven programming (to respond to button clicks instead of blocking prompts). Each of these builds directly on the loop-and-conditional thinking you've practiced in this lesson.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain why we need to use Math.floor() in combination with Math.random() when generating the secret number. What would happen if we only used Math.random() * 100 without Math.floor()?
Show answer
Math.random() returns a decimal like 0.7364829..., so Math.random() * 100 would give something like 73.64829, not a clean whole number. If the secret number were 73.64829, the player could never guess it by typing whole numbers. Math.floor() rounds down to the nearest integer (73 in this case), ensuring the secret is always a whole number the player can actually guess. Without Math.floor(), the game would be essentially unwinnable.

Question 2: BASIC CALCULATION

Write the JavaScript expression to generate a random integer between 1 and 50 (inclusive). Then write the expression for a random integer between 20 and 80 (inclusive).
Show answer
For 1 to 50: Math.floor(Math.random() * 50) + 1. Here, Math.random() * 50 gives a range of [0, 50), Math.floor() produces integers 0–49, and adding 1 shifts the range to 1–50. For 20 to 80: Math.floor(Math.random() * 61) + 20. The range size is 80 − 20 + 1 = 61 possible values. Math.floor(Math.random() * 61) gives 0–60, and adding 20 shifts to 20–80.

Question 3: INTERMEDIATE

A student writes the following loop for their guessing game but it has a bug. Identify the problem and fix it: let guess = 0; while (guess !== secret) { guess = Number(prompt("Enter your guess:")); if (guess < secret) alert("Too low!"); else if (guess > secret) alert("Too high!"); else alert("Correct!"); }
Show answer
The code has no limit on the number of attempts, so the loop will run forever until the player guesses correctly — or closes the browser. There is also no protection against the player clicking 'Cancel' on the prompt, which returns null and converts to NaN, causing an infinite loop. To fix it, add an attempt counter and a maximum: let attempts = 0; const max = 7; and change the condition to while (guess !== secret && attempts < max). Inside the loop, increment attempts++ each iteration. This ensures the game always terminates.

Question 4: APPLIED

You want to add a difficulty feature: Easy (1–25, 8 guesses), Medium (1–100, 7 guesses), Hard (1–500, 9 guesses). Write the setup portion of the code that asks the user to choose a difficulty and then sets maxNumber and maxAttempts accordingly. Use an if/else if/else chain.
Show answer
Here is one solution: let difficulty = prompt("Choose difficulty: easy, medium, or hard").toLowerCase(); Then use conditionals: let maxNumber, maxAttempts; if (difficulty === "easy") { maxNumber = 25; maxAttempts = 8; } else if (difficulty === "hard") { maxNumber = 500; maxAttempts = 9; } else { maxNumber = 100; maxAttempts = 7; } Notice we use .toLowerCase() so that "Easy", "EASY", or "easy" all work. The else block serves as a default (medium), which is good defensive programming — if the user types something unexpected, they still get a playable game.

Question 5: CRITICAL THINKING

Using the binary search strategy (always guessing the midpoint of the remaining range), what is the maximum number of guesses needed to guarantee finding any number between 1 and 1000? Explain your reasoning. Then, if you wanted to give the player exactly enough guesses to always be able to win using this strategy, how would you calculate maxAttempts from maxNumber in JavaScript?
Show answer
With binary search, each guess eliminates half the remaining possibilities. Starting with 1000 numbers: after 1 guess you have ≤ 500, after 2 ≤ 250, after 3 ≤ 125, after 4 ≤ 63, after 5 ≤ 32, after 6 ≤ 16, after 7 ≤ 8, after 8 ≤ 4, after 9 ≤ 2, after 10 ≤ 1. So you need at most 10 guesses. Mathematically, the answer is ⌈log₂(1000)⌉ = ⌈9.97⌉ = 10. In JavaScript, you can calculate this dynamically: let maxAttempts = Math.ceil(Math.log2(maxNumber)); This uses Math.log2() for base-2 logarithm and Math.ceil() to round up, ensuring the player always has enough attempts if they play optimally.

SUMMARY

Lesson Summary

Summary

In this lesson, you learned how to build a complete number guessing game in JavaScript by combining four core programming concepts. You used Math.random() and Math.floor() to generate a secret random integer within a specific range. You employed a while loop to let the player guess repeatedly until they win or exhaust their attempts. Conditional statements (if / else if / else) provided targeted feedback — "too high," "too low," or "correct" — after each guess. And you handled user input with prompt() and type conversion to safely accept and process player guesses.

Beyond the mechanics, you explored how the binary search strategy connects to real algorithms, how to evaluate your code's strengths and limitations, and how to enhance it with features like input validation, difficulty levels, and replay functionality. These patterns — generating randomness, looping until a condition is met, and branching based on comparisons — are foundational to virtually all interactive software.

Varsity Tutors • Computer Programming 1 (JavaScript) • Building Guessing Game