So far I have learned some basic JavaScript language such as conditional keywords, logical operators, and built-in methods.
Today, we will build a simple guessing number game by applying those JS basic language.
Basically, the game is ask user to guess a number, if the number is match to the secret number, they win the game. If not, they will have to try again.
Step One: Create a simple HTML page and Link to the JS file
I start to build a simple HTML page and give a title “Guessing Game” for it. Then, I create a separate JS file named “game.js”, and link to the HTML page.
Step Two: Create Secret Number and Prompt Question
In the JS file, I start to create a secretNumber which is 6. Six is a lucky number in China which means everything goes well as you wish.
Then I ask a prompt question:”Guess A Number”, so user will enter a number.
Step Three: If users enter the right number, they will receive a message
It is conditional, so I use if keyword. Since the variable “guess” is a string type value, it won’t equal to the number value “secretNumber”. Therefore, we need to convert the string to number by writing Number(guess) === secretNumber.
Then, I create a alert message to tell the users that they guess right.
Step Four: If the number is too high or too low, guess again.
I use a else if keyword to set the Number (guess) is greater than secretNumber. And I also write the else keyword which set any number lower than secret number condition.
If a user guesses a higher number, it will alert him to try again.
If a user guesses a lower number, it will alert him to try again.
网友评论