Part 4 mini-project: Number Guessing Game
This project combines every idea from Parts 3 and 4: variables, input, comparisons, branching, looping. The result is a small but truly interactive game.
What to build
A program that, when run:
- Picks a random whole number from 1 to 100 (the target), hidden from the user.
- Repeatedly:
- Prompts the user for a guess.
- Reads the guess.
- Prints
Too low.,Too high., orCorrect!based on how the guess compares to the target. - Counts attempts.
- When the guess matches, prints how many attempts it took, then stops.
A typical session:
I am thinking of a number between 1 and 100.
Guess: 50
Too high.
Guess: 25
Too low.
Guess: 37
Too high.
Guess: 31
Too low.
Guess: 34
Correct! You got it in 5 attempts.
Files
Starter and finished versions are in
projects/03-number-guess/:
starter.lua— scaffolding with TODO comments.finished.lua— a working version. Compare yours afterwards.
Run with:
lua projects/03-number-guess/starter.lua
Hints
math.random(1, 100)picks the target. Call it once, before the loop. Inside the loop, the target stays the same.- A
repeat ... untilloop fits well: the body asks once, then theuntilline checks if the guess equalled the target. - An attempts counter is a variable set to
0before the loop and bumped by1inside the body. - The guess arrives as text. Run it through
tonumberbefore comparing.
What you cannot use yet
- Tables. No need to store a guess history.
- Functions of your own. The game fits in one straight script.
- Roblox-specific calls. This is still a terminal program.
A bigger challenge (optional)
If the basic version works, try one of these:
- After three wrong guesses, print a hint saying whether the target is even or odd.
- Track the highest and lowest guess so far, and print the bracket
each round, like
(known range: 32 to 49).
Neither is required to consider the project finished.
Done?
When the game runs cleanly start to finish — chooses a target, takes guesses, gives feedback, ends with the attempts count — Part 4 is done. Move on to Chapter 21 — Functions.