≡ Menu

JavaScript Assignment #1: Number Guessing Game

Functionality

Welcome to your first JavaScript assignment. Your job in this assignment will be to create a game where you’ll need to guess a number between 1 and 100 (inclusive) within 6 attempts.

With JavaScript, in order to get an input from a user, you’ll need to make use of the prompt function.

Here’s an example of how you would prompt someone for information using the prompt function.

var aNumber = prompt("Please guess a number between 1 and 100");

This will show a dialog box on the screen allowing the user to enter some input. The result of what the user types in will (in this case) be stored in the variable aNumber.

The program should first randomly pick a number between 1 and 100 and then prompt the user to guess the number. It should also show the user how many guesses they have left:

javascript assignment 1 screenshot 1

When you guess a number, the application should do some validation on the input. It should:

  1. Validate that the inputted value is indeed a number (please see appendix for an explanation of how to do this)
  2. Validate that the inputted value is between 1 and 100 (inclusive). This means that the number 0 is an invalid input, but the value 1 is valid. Also the value 101 would be invalid, but the number 100 would be valid.


If the value entered into the prompt is invalid, then you should prompt them again asking to input a valid number like so:

javascript assignment 1 screenshot 2

Once the inputted value is deemed valid, the application should compare your guessed number to the one originally picked.

If your number is larger, then the program will alert you with a message saying “You need to guess a smaller number.

If your number is smaller, then the program will alert you with a message saying “You need to guess a larger number.

And if you are able to guess the number, then the program will say “Congrats! You got it! My number was: [randomly generated number]

Note: be sure to replace the [randomly generated number] placeholder with the actual number that was chosen by the computer at the beginning.

If after 6 attempts the user was NOT able to guess the number correctly, you should display an alert like so:

javascript assignment 1 screenshot 3

Note: be sure to show the actual number that was randomly generated by the program, the number 21 displayed above was just the number that was picked when I ran my program.

Appendix

Validating that a value is a number

In order to validate that a value is indeed numeric, you can use a function called isNaN(aVariable). This function takes a single parameter. This parameter will be checked by the function to see if it is a number or not.

If the variable is a number, it will return false. If the variable is NOT a number, it will return true.

For example:
isNaN("test") returns true
isNaN(10) returns false

{ 0 comments… add one }

Leave a Comment