✏ Exercise 1—Guess-what-number Game with jQuery
In this exercise, we create a guess-what-number game. The following steps list the requirement of the game.
- The computer generated a random number between 1 and 100.
- The web page shows an input, waiting for the player to guess a number.
- After the player guesses, the computer tells the player if the number is correct. Otherwise, the computer tells if the guessed number is too larger or too small.
- If the guessed number is correct, the web page shows a “Congratulations” wording and allow the player to restart the game.
Suggested action steps to implement the game
- Create a new CodePen page
- Write the HTML for the following parts:
- number input
- “guess” button
- Messages for larger or smaller number
- Congratulations message.
- “Restart Game” button.
- Use jQuery to hide non-current elements.
- Define a function to generate a random number, and store it as variable.
- Handle click event on the “Guess” button.
- Determine if the input number is <=> with the generated number.
- Show the message of the comparing result.
- Show Congratulations wording (and the “Restart” button) if player is correct.
- Restart the game on “Restart” button click.
What you need to know to make the game
Loading jQuery:
<script src='http://code.jquery.com/jquery.min.js'></script>
Loading jQuery, CodePen way:
In the pen setting > Javascript tab > Quick Add > jQuery.
jQuery selector examples:
$('a')
$('.notice')
$('#number-input')
$('[href="#guess"]')
jQuery Show/Hide elements:
$(selector).show();
$(selector).hide();
jQuery detect click event:
$(selector).click(function(){
// code to handle the click
});
Generating random number
Math.random(); // 0–0.999999
Math.floor(Math.random() * 100) // 0–99
Math.floor(Math.random() * 100) + 1; // 1–100
Taking the code further
There are several ways to improve the game.
- Styling. You can use CSS to make the game looks nicer. Try to style it to have a modern look.
- Mobile Friendly. By using the viewport meta tag, you can make the game displays nicer in small screen. Moreover, you can handle touch event for the “guess” and “restart” button clicking.