Project: Guess The Number Game

Now you've learned something about the theory of JavaScript and what you can do with it, we will give you an idea of what the process of creating a simple JavaScript application is like by guiding you through a practical tutorial. In the last practice exercise, you'll build up a simple Guess the Number game step by step. The game uses "variables", "conditionals", "functions", "events", and "loops".

It is essential to practice "reading" a lot of code and running it when learning a new language. In addition, reading well-written code helps you write well-structured code. Don't worry about knowing events and built-in objects such as Math; we'll cover them in more detail in another course. This is a practice exercise, and if you can't get the game to work, check it against the source code.

The Game

Your Task

Let's imagine your boss has given you the following brief for creating this game:

I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.

Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:

  1. Generate a random number between 1 and 100.
  2. Record the turn number the player is on. Start it on 1.
  3. Provide the player with a way to guess what the number is.
  4. Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
  5. Next, check whether it is the correct number.
  6. If it is correct:
    1. Display congratulations message.
    2. Stop the player from being able to enter more guesses (this would mess the game up).
    3. Display control allowing the player to restart the game.
  7. If it is wrong and the player has turns left:
    1. Tell the player they are wrong and whether their guess was too high or too low.
    2. Allow them to enter another guess.
    3. Increment the turn number by 1.
  8. If it is wrong and the player has no turns left:
    1. Tell the player it is game over.
    2. Stop the player from being able to enter more guesses (this would mess the game up).
    3. Display control allowing the player to restart the game.
  9. Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.

Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.