Lesson 1.14: Project: guess the number
A whole game with everything from this stage: variables, conditions, loops and functions.
The idea
The computer picks a number from 1 to 100. You try to guess it, and it tells you whether it's higher or lower. When you get it, it tells you how many attempts you needed.
It's built like any program: think first, then write.
The plan, in pseudocode
Algorithm Guess
secret ← a random number from 1 to 100
attempts ← 0
attempt ← 0
While attempt ≠ secret Do
Read attempt
attempts ← attempts + 1
If attempt < secret Then
Write "Higher"
Else
If attempt > secret Then
Write "Lower"
EndIf
EndIf
EndWhile
Write "Got it in ", attempts, " attempts"
EndAlgorithm
It's almost the loop from 1.5. Only one piece is missing: the random number.
A random number
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Math.random()gives a decimal between 0 and 1, never reaching 1.Math.floor()drops the decimals.- Together they give a whole number between
minandmax.
You don't need to understand all of it: it's one of those functions you copy.
The game
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const secret = random(1, 100);
let attempts = 0;
let attempt = 0;
while (attempt !== secret) {
attempt = Number(prompt("Guess the number (1-100):"));
attempts = attempts + 1;
if (attempt < secret) {
alert("Higher");
} else if (attempt > secret) {
alert("Lower");
}
}
alert("You got it in " + attempts + " attempts!");
alert() shows a message in a window. Paste the whole game into the console and play. To play again, reload the page before pasting it.
Every line is something you already know: a function (1.10), variables (1.8), a while and an if (1.9) and Number() to convert what prompt() returns.
Try it
If you press Cancel, the game keeps asking forever. Make it stop.
Hints:
- When you cancel,
prompt()returnsnull. breakleaves a loop at once.- The final message should only show if you guessed it.
Show the solution
while (attempt !== secret) {
const answer = prompt("Guess the number (1-100):");
if (answer === null) {
break;
}
attempt = Number(answer);
attempts = attempts + 1;
if (attempt < secret) {
alert("Higher");
} else if (attempt > secret) {
alert("Lower");
}
}
if (attempt === secret) {
alert("You got it in " + attempts + " attempts!");
}
The answer is kept before converting it: Number(null) is 0, and you could no longer tell that the player cancelled.
Summary
- First the plan in pseudocode; then the code.
- A whole program is small pieces added up: variables, conditions, loops and functions.
Math.random()gives chance;alert()shows a message;breakleaves a loop.