Recipe ID: hsts-r3
We offer HTML5, CSS3, JavaScript,Bootstrap, Angular.JS, WordPress Node.JS, React.JS, Joomla, Drupal, Vue.JS and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced web design training, visit our Web design and development bundle page.
Overview
We will create a simple guess the number type game. It will choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player would be told if they are right or wrong — and, if they are wrong, whether the guess was too low or too high. It would 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:
Pre-Requisites
Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Learning Objective
To have a first bit of experience at writing some JavaScript, and gain at least a basic understanding of what writing a JavaScript program involves.
To begin with this recipie tutorial, we'd like you to make a local copy of the number-guessing-game-start.html file. Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.
The place where we'll be adding all our code is inside the <script> element at the bottom of the HTML:
// Your JavaScript goes here
</script>
Let's get started. First of all, add the following lines inside your <script> element:
const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');
let guessCount = 1;
let resetButton;
This section of the code sets up the variables and constants we need to store the data our program will use. Variables are basically containers for values (such as numbers, or strings of text). You create a variable with the keyword let (or var) followed by a name for your variable (you'll read more about the difference between the keywords in a future article). Constants are used to store values that you don't want to change, and are created with the keyword const. In this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the HTML elements referenced stay the same.
You can assign a value to your variable or constant with an equals sign (=) followed by the value you want to give it.
In our example:
<p class="lowOrHi"></p>
<input type="submit" value="Submit guess" class="guessSubmit">
Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article.
Next, add the following below your previous JavaScript:
Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.
When we want to run the code, we type the name of the function followed by the parentheses.
Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:
After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it.
Note: You'll learn a lot more about functions later in the course.
O
JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.
If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing Return/Enter after each one, and see what results they return. If you don't have easy access to the browser developer tools, you can always use the simple built-in console seen below:
First let's look at arithmetic operators, for example:
Operator |
Name |
Example |
+ |
Addition |
6 + 9 |
- |
Subtraction |
20 - 15 |
* |
Multiplication |
3 * 7 |
/ |
Division |
10 / 5 |
You can also use the + operator to join text strings together (in programming, this is called concatenation). Try entering the following lines, one at a time:
There are also some shortcut operators available, called augmented assignment operators. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:
This is equivalent to
When we are running true/false tests (for example inside conditionals — see below) we use comparison operators. For example:
Operator |
Name |
Example |
=== |
Strict equality (is it exactly the same?) |
5 === 2 + 4 |
!== |
Non-equality (is it not the same?) |
'Chris' !== 'Ch' + 'ris' |
< |
Less than |
10 < 6 |
> |
Greater than |
10 > 20 |
C
Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.
At this point, replace your current checkGuess() function with this version instead:
This is a lot of code — phew! Let's go through each section and explain what it does.
guessCount === 1
If it is, we make the guesses paragraph's text content equal to "Previous guesses: ". If not, we don't.
At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.
Add the following line below your checkGuess() function:
Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside addEventListener()).
Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.
Finishing the game fun
Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:
Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:
const resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:
At this point you should have a fully working (simple) game — congratulations!
All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.
One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your browser developer tools JavaScript console again, and enter the following:
What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A for loop takes three input values (arguments):
Now let's look at the loop in our number guessing game — the following can be found inside the resetGame() function:
This code creates a variable containing a list of all the paragraphs inside <div class="resultParas"> using the querySelectorAll() method, then it loops through each one, removing the text content of each.
A small discussion
Let's add one more final improvement before we get to this discussion. Add the following line just below the let resetButton; line near the top of your JavaScript, then save your file:
This line uses the focus() method to automatically put the text cursor into the <input> text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.
Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.
In this particular case, we first created a guessField constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:
To get this reference, we used the querySelector() method of the document object. querySelector() takes one piece of information — a CSS selector that selects the element you want a reference to.
Because guessField now contains a reference to an <input> element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is focus(), so we can now use this line to focus the text input:
Variables that don't contain references to form elements won't have focus() available to them. For example, the guesses constant contains a reference to a <p> element, and the guessCount variable contains a number.
Playing with browser objects
Let's play with some browser objects a bit.
guessField.value = 'Hello';
The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
guesses.value
The browser will return undefined, because paragraphs don't have the value property.
guesses.textContent = 'Where is my paragraph?';
guesses.style.boxShadow = '3px 3px 6px black';
Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
Conclusion
It is a simple guessing the number game which is fun playing too. It also increases the thinking ability of human to make a right guess.
Cross-platform Native App Development Using HTML5, CSS3 and JavaScript
Node.JS Coding with Hands-on Training
Developing Web Applications Using AngularJS
Introduction to the WordPress CMS
Introduction to the Joomla CMS
Mastering Drupal in 30 Hours
Intro to Dreamweaver with Website Development Training
Adobe Muse Training Course
PHP and MySQL Coding
Responsive Site Design with Bootstrap
jQuery Programming for Beginners
Object Oriented Programming with UML
SQL Programming and Database Management
Introduction to Python Programming
We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.