Guess the number game
To demonstrate how to use 'if' statements in practice, here's a simple 'Guess the number' game implemented in JavaScript. The computer generates a random number from 0-100, and when you make a guess, it will tell you if the number is higher, lower, or equal to your guess. This lets the player make a series of guesses and eventually identify the number. Open the project in Construct and make sure you're viewing the Event sheet 1 tab.
You should see a GuessButton: On clicked trigger, with a script block to run as an action. This means the JavaScript code snippet will run every time the player clicks the 'Guess' button.
Try previewing the project and making a series of guesses until you can find the number. The code that runs when you click the 'Guess' button is the following:
// This is the number the player must guess.
let theNumber = getTheNumber();
// This is the number the player just guessed.
let guessedNumber = getEnteredNumber();
let message;
// Set the message to display.
if (guessedNumber < theNumber)
{
message = "Higher!";
}
else if (guessedNumber > theNumber)
{
message = "Lower!";
}
else
{
message = "That's it!";
}
// Show the message.
showResultMessage(message);
This code block uses some functions that are declared elsewhere in the project: getTheNumber(), getEnteredNumber() and showResultMessage(). Don't worry about these for now (this guide will cover functions later on). For now all you need to know is there are three variables:
theNumber
, which is the random number the player must guess
guessedNumber
, which is the number the player entered when they clicked 'Guess'
message
, which is a string that will be displayed on-screen
The code block uses 'if' statements to compare the player's entered number with the number they need to guess. If the guessed number is lower, it sets the message to "Higher!", indicating they need to guess a higher number; if the guessed number is higher, it sets the message to "Lower!", indicating they need to guess a lower number; and if they got it right it sets the message to "That's it!".
This is a simple example but it demonstrates how you can use 'if' statements to display different results to the user depending on the inputs, and make a little game out of it!