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.

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.

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.

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.

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.

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)) + 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) { // 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) → "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!

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.

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.
Each code section maps to a core programming concept
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

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
Step 1 — SetupThe 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
Step 2 — First Guess: 50The 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
Step 3 — Second Guess: 85Condition 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
Step 4 — Third Guess: 70The 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
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.

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.

Evaluating the basic guessing game
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
✦ 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.

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.

From guessing game patterns to professional-level concepts
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))

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.

Practice Problems

PROBLEM 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()?
PROBLEM 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).
PROBLEM 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!"); }
PROBLEM 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.
PROBLEM 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?

Lesson 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