JavaScript Number Guessing Game Tutorial
JavaScript Number Guessing Game Tutorial
Now that you have learned how to make a loop, lets create a number guessing game using JavaScript. I will begin by showing you how to make an easier guessing game from 1 - 10 with unlimited guesses and then a harder one that will be 1 - 100 but with a limited amount of guesses. Let us begin with the easier games code. The HTML code is the same as the other tutorials. Here is the JavaScript code.
As you can see there are both while and if statements in this code. The variables are created first. The num variable generates a random number between 1 and 10 using the math.floor and math.random code. We use a while loop to let the user guess an unlimited amount of times. The user is then prompted to guess a number with the guess being checked by the if statement and if it is correct then an alert is sent with a message and the loop stops. Here is the end result.
Experiment with the code by changing the values to guess between. Lets move onto the harder game which is between 1 and 100 and has limited guesses.
We begin once again by generating the random number only this time it is between 1 and 100. We again create our variables and prompt the user to guess the number in the while loop which we will set count to 5 which means the user has 5 guesses. This code tells the user to guess higher or lower depending on if their guess is higher or lower than the random number. After the 5 guesses, if the user has not got the number right they will receive the alert to inform them they failed and the game is over.
Comments
Post a Comment