: a a a a
: A A A

Start Reading the Website Out Loud and control Speed and Volume using the player. You can also hover and click to speak any text on the site.
Adds a distraction Free Mask To The Screen. Block out all unneccessary content and scroll through the page line by line.
Changes the Default Cursor & Pointer to a large version allowing you easy navigation of the website.
Simplify any page on our website with 1 click. You can control Contrast, Colours and Text Size as well as print the page too.
Accessibility Menu
StephMyLife Freelancer Bootcamp

32 Counties Guessing Game

In this challenge, we are going to create a game where the user needs to guess the 32 counties in Ireland. Like the Flappy Bird game, we will specify the controls for our page in HTML, add our functionality in JavaScript, and style our page in CSS.

If you have any trouble copying the code from these instructions, you can access an online version of this file here.

Step 1: Install Visual Studio Code or Notepad++

In the first challenge, we used Notepad or TextEdit to edit our files, but for this one I recommend that you use an application that’s much better for web development: Visual Studio Code. This is a very easy to use code editor that makes writing code much quicker and easier! Alternatively you can use ‘Notepad++’

Click here to download Visual Studio Code and install it on your machine. You can install it on Mac OS, Windows, or Linux machines.

VS Code makes it much easier for you to write code, and it’s great because it can format and autocomplete your code too. This makes it much quicker to write code, and easier to see if you have made a mistake.

Step 2: Set up your project folders

The first thing to do on any new project is to get your project structure ready, and this is how we always start when creating a new website. Create a new folder on your computer for your website, you can name it anything you like and put the folder anywhere you like.

Inside this folder, create three more folders (you can use keyboard shortcuts to do this, press CTRL+Shift+N on a windows, or CMD+Shift+N on a Mac to create a new folder)

Give these folders the following names:

  • css
  • js
  • img

Go to your coding challenge folder that you downloaded, and go to the ‘project files’ folder.  Copy the irish-flag.jpg picture and put it into the img folder in your project. This is the image we will use on your game.

Using Visual Studio Code, create a new HTML file and save this empty HTML file in the location of the main project folder, with the name ‘guessing-game.html’ .

Designing our page

We will design our page using a language called HTML. HTML stands for HyperText Markup Language, and this is what tells the browser what controls should be on your page, and what they should do. CSS will style your controls. And JavaScript adds functionality to your controls which we will see later on – but HTML is the key component that defines exactly what we want to see on our page.

Every HTML file takes the same basic structure to start with:

<html> (every html file must start and end with these tags)

<head>

(the head is like the brain of your file. I’ll show you what goes here in a bit!)

</head>

<body>

              (This is where your content goes that you see on your site.)

</body>

</html>

You’ll see that all of the <tags> have a matching </tag> with a slash. These tags identify the start and /end of a block of code and tell the browser what to expect inside that block of code. Whenever you have a <tag> there must be a corresponding </tag> or your webpage won’t render correctly and you will have errors.

Type the above code structure into your guessing-game.html file (without the ‘(comments)’, and then go back to your project folder and double click your guessing-game.html file. This will open guessing-game.html in your browser and you will see a blank webpage.

 

Now, let’s put some content in here! (if you have already done the coding challenge, and are familiar with this part, skip to the next page).

 

Type the following between the <body> </body> tags.

<h1> Hello World!</h1>
<p> This is my first website! </p>

Go back to your browser and refresh guessing-game.html (or open it again if you closed it). Now you will see this!

Troubleshooting tip: If you do not see this, and you see the <tags>, this is because your file has not been saved correctly as HTML. Go back to Notepad ++  or Visual Studio Code, click ‘File’ -> ‘Save As’, and save as type HTML with the extension ‘.html’. If you are not using Visual Studio code, then this is more likely to happen.Especially if you’re using TextEdit on a Mac – TextEdit kinda sucks for writing code, so I would download Notepad ++ to make things easier for you. 

Once your webpage looks like the above, you know your page works and can be rendered by your browser.

Remove all of the content within the <body></body> tags and we can start designing your page.

How The Guessing Game Works

In this guessing game, we are asking the user to guess all 32 counties in Ireland. The user enters their guess into a textbox, and the JavaScript checks if this is a county.

If the guess is correct then the name of the counties goes into a ‘correct answers’ panel, and a message shows to tell them how many counties are left to guess.

If the counties is incorrect, nothing is added to the correct answers panel and the count of how many are left remains the same.

Let’s think about what controls we might want on the Guessing Game page

  • Text telling the user how to play the game
  • A textbox for them to type their guess
  • Another, larger text box which shows the user a list of their correct guesses.
  • A label to show the count of counties that are left to guess

Copy this code in between the <body></body> tags in your page body, and then we can go through each control

 <div>
     <h2> Can you guess all of the counties in Ireland?</h2>
     <p> Enter your guesses below to make it to the next page:</p>
     <input type="text" id="userGuess" onkeyup="guess()">
     <p>Correctly guessed:</p> 
     <textarea id="correct" disabled="true"></textarea>
     <label id="counter"></label>
</div>

As you can see, this is a very simple interface!

The first two lines show text to the user using <h2> and <p> tags.

  • A <h2> tag is a header tag, and is usually used to show important information on the page as the font is big and bold. Text within a <h2> tag is pre-styled so it’s very helpful to use the <h2> tags as you can change the size of text without having to change the css. You can also use <h1> tags for even larger text. Click here to read about Header tags.
  • A <p> tag places the content within it into its own separate paragraph. This text is not formatted, and is the default style for your website.

Below this, we have a text box with styling, type, and ID attributes. This textbox however has an extra attribute, called ‘onkeyup’ , and this is where our JavaScript function task will be kicked off.

Event Attributes

‘onkeyup’ is an event that is fired in your browser whenever someone types something into a textbox.  What we are doing here is saying:  when the ‘onkeyup’ event occurs (when the user types something), I want the browser to start the guess() function in our JavaScript file. This function will then see if the text that the user has typed matches the name of a county.

There are a lot of event attributes that you can add functions to in your HTML. The most common one is an OnClick event which is added to a button element, and controls what happens when the button is clicked. However there are many more! Here is a list of all of the event attributes. Events are a way to trigger functions in your JavaScript and make something happen. Clicking a button, checking a checkbox, choosing something from a dropdown are all events that you can attach to a JavaScript function through an event attribute.

Next we have another <p> tag with some text, and then a <textarea></textarea> where we will put the correct guesses. A text area is larger than a textbox, so it’s more suitable for this. You can see we have added the following attributes:

  • Class: So it can be styled in style.css (we can style elements by adding classes to them).
  • ID: So we can reference the control in the JavaScript to show correct guesses.
  • Disabled:  We don’t want the user typing anything in here.

Question: Finally, we have a label to show the number of guesses left. As you can see, this label has an ID called “counter”. Can you guess why this is?

Answer: It’s because we want to reference this label in the JavaScript so that we can tell it how many guesses are left and what text to display. For a label that is just for displaying static information we don’t need to give it an ID.

Refresh your page and you can see our elements here ( we will be styling them at the end, so don’t worry if they don’t look great right now!)

Adding our JavaScript

Javascript is what we use to make web pages interactive. We can add all sorts of functionality to our web pages by adding Javascript functions. HTML can just tell your browser what controls to show, but it can’t control what these controls do. You can’t add functionality to a button using HTML, so to make your pages interactive you will need to learn how to write JavaScript!

You have two options here:

  1. EASY: Copy the ‘game.js’ file from the ‘Project files’ folder and put it in the ‘js’ folder in your project
  2. HARD: Make the javascript file from scratch yourself and find out a little bit about the code!

If you choose option 1, complete the ‘Linking your Javascript & HTML files’ step below, and then  skip to the ‘Styling your Guessing Game’ section below.

If you would like to learn more about code, continue below.

Linking your JavaScript & HTML files

Once your Javascript file code is in place, you need to add a line of code to link it to your HTML file and add the Javascript functionality to your page.

You do this in the <head></head>  tags – paste this bit of code between the head tags.

    <script src="js/game.js"></script>

This tells your browser to go into the js folder, and find the game.js Javascript file when it loads our HTML page, because our HTML needs to use it to do its job.

<head>
    <script src="js/game.js"></script>
</head>

Coding the game yourself

In Notepad++, open an empty file and save it as ‘game.js’ with type ‘Javascript’, and save it in your ‘js’ folder.  Make sure you save it as type ‘JavaScript’. Within this file, we are going to write the code for the guessing game. Here are some coding concepts we will be using!

Variables, Functions, and Conditional statements

I’m going to introduce you to some new concepts here: variables, functions, and conditional statements. I’ll explain them now, and you can see how they work in the code below. Throughout the coming pages you will be learning more about these three concepts and practising how to write them

Variables

These allow us to store pieces of data in our code. We assign a value to a variable, and then we can pass this variable around our code to use it in our functions. Variable means anything that can vary, so the value of a variable can be changed anytime. A variable must have a unique name, and you can assign a value to a variable using equal to (=) operator when you declare it or before using it.

Consider this piece of JavaScript:

var x = 3;
var y =  4;
var z = x + y;

Here I am creating three variables. The first two variables are being assigned numerical values, 3 & 4. The third variable is declared next and is using the values of the previous two variables to set its own value. The value of var z will be ‘7’ when the page loads.

Functions

A function is a block of JavaScript code that performs some type of task. It’s good practise to create a different function for each different piece of functionality your page has – this makes your code easier to read and understand. A function allows you to define a block of code, give it a name and then execute it as many times as you want.

Functions often use variables to perform their tasks, as you will see in the code below. Sometimes a variable will just be used by one function, so it will be declared inside the function. However sometimes a variable will be used by many functions, so it will be declared at the top of the JavaScript file, outside of all functions.

One function can be used many times, so they can save a lot of time writing code!

A function is written like this:

function task() {
    //code to perform the task
}

Conditional Statements

Conditional statements are used within functions to specify if a block of code should be executed or not. They wrap around a piece of code, and they specify a condition which has to be met for the block of code to be executed.

Think of it like ‘If this is true, then do that’ so for our page ‘if the username and password is correct, go to the next page’. If the condition is not met, then the code within the statement will be executed! These are super helpful and are used a lot in software development

And ‘if’ statement is usually, but not always, followed by an ‘else’ statement. This contains an alternative block of code to execute if the condition is not met.

They take the following format:

if (vegetarian== true) {
    // return veggie menu
}
else {
    // return full menu
}

It’s ok if you are still not super clear on these concepts, we are going to use them to create the functionality for our page so you can see how to use them in a real example!

Arrays

Think of an array as a variable that stores a list of data. A variable can store one name

Var name = “Peter”;

But an array can store a list of names:

Var nameArray =  [“Peter”, “Mary”, “John”];

You can then access all of the items in your array by calling this array, rather than having to call multiple variables. It makes it much quicker to write code that deals with lists of data. For 32 counties we don’t need 32 variables, we just need 1 array!

Extra reading: Here is a useful article about arrays.

Putting these concepts into practice

We’re going to start by declaring our variables – copy this code into the top of your game.js file:

var numOfGuesses = 32;
var correctlyGuessed = 0;
var correctAnswersArray = [];
var countiesArray = ['antrim','armagh','carlow','cavan','clare','cork','derry','donegal','down','dublin','fermanagh','galway','kerry','kildare','kilkenny','laois','leitrim','limerick','longford','louth','mayo','meath','monaghan','offaly','roscommon','sligo','tipperary','tyrone','waterford','westmeath','wexford','wicklow'];

This  sets up the following:

  • numOfGuesses: This is the count of how many guesses that the user has.
  • correctlyGuessed: This keeps a count of how many guesses are correct. We will add 1 each time the user enters a correct guess.
  • correctAnswersArray: We are creating an empty array which will store a list of the correct guesses, which will be outputted in the ‘correctAnswers’ textarea on the web page.
  • countiesArray: This is an array which is filled with a list of the counties in Ireland.

Next, let’s create our Guess() function, which is the task that is kicked off when the user types something into our textbox.

Copy the following  code into your game.js file, just below where you created your variables.

function guess() {
    var userGuess = (document.getElementById("userGuess").value).trim().toLowerCase();
    if (countiesArray.includes(userGuess) && !correctAnswersArray.includes(userGuess)) {
        correctAnswersArray.push(userGuess);
        document.getElementById("correct").innerText = correctAnswersArray.toString();
        document.getElementById("userGuess").value = " ";
        correctlyGuessed++;
        var guessesLeft = numOfGuesses - correctlyGuessed;
        document.getElementById("counter").innerText = (guessesLeft) + " guesses left.";
        if (correctlyGuessed == numOfGuesses) {
            alert("Congratulations, you guessed every county correctly!")
        }
    }
}

The ‘Guess’ Function

As we defined in the HTML, the ‘Guess’ function is called whenever a user types something into the textbox. So each time a letter is typed in here, the function checks the entire content of the textbox and sees if it matches anything that it is in our countiesArray. 

The first thing we do in our function is get the contents of the userGuess textbox and assign this to a variable: ‘userGuess’.

After we’ve created the variable, we have a conditional ‘if’ statement, which checks if the contents of the textbox match any of the items in the list of counties (countiesArray).

Checking an array of 32 items for 1 match seems like it would require a lot of code, but luckily JavaScript provides a function for doing this in just one word: ‘includes’.

Javascript includes() is an inbuilt function that determines whether the array contains a specified element or not. It returns true or false as the output depending on whether the array contains the item or not. It’s a necessary function to know if you’re working with arrays, as it saves SO MUCH time!

Here is what our if statement is doing:

  • if( countiesArray.includes(userGuess)  – if the counties array contains a match for the userGuess variable
  • && – a double ampersand means that there is a second condition which must be true
  • !correctAnswersArray.includes(userGuess) – If the correctAnswersArray does not contain the guess variable. (Putting an exclamation point in front of this code means that we want to check that the statement is not true.)

Here, we are saying if our guess is correct (in the countiesArray) AND if it hasn’t been guessed before (is not in the correctAnswersArray), then you can proceed with the next bit of code. There is no ‘else’ statement, as we will do nothing if the guess isn’t correct.

Question: If I were to write a statement that says “if a person is male, and his name isn’t Paul, then run this task”  – how would I write that as a conditional statement? Practice and then look at the answer below to compare your code!

Answer:

if (person == "male" &&  !name == "Paul") {
    //run this piece of code
}

What to do if the guess is correct

Within the conditional statement is the code for what to do if the guess is correct. Here is what this code does:

  • Adds the guess to the correctAnswersArray.

We have an array called correctAnswersArraywhich keeps track of how many guesses are correct. We need to add the value of our variable ‘userGuess’ to this array. To do this, we use the push() function.

This takes the following syntax: arrayname.push(dataToAdd);

 

  • Adds the guess to the text area on the page.

We can set the text of the ‘correct’ text area using  document.getElementById(“correct”).innerText. 

We will do this using the ‘ToString()’  function which is another inbuilt JavaScript function that you can use on arrays.. This function turns an array of data into a list of items separated by a comma, so that it can be placed into the textbox. If you do not add the ToString() function, you won’t be able to place the array contents directly into the box as it will be treated like a JavaScript object and not a string of text.

 

  • Empties the guessing textbox.

As you can see, the code sets the value of the ‘userGuess’ textbox to be “ ” – an empty space.

 

  • Increases the correctly guessed count by 1. 

— means take one away from the existing value and ++ means add one to the existing value.

You can also say   correctlyGuessed =   correctlyGuessed + 1; but this requires more code. So we say correctlyGuessed++ instead.

 

  • Calculates the number of guesses left

Here we are creating a new variable called guessesLeft, where we are taking the value of correctlyGuessed from numOfGuesses. This gives us the number of guesses remaining so that we can show the user on the page.

 

  • Updates the webpage to show the amount of counties left to guess.

Set the innerText of your “counter” label to show your total guesses left. As you can see from this line of code, if you want to display a variable value and static text together in your label, you need to put a ‘+’ between them. So control.text = variable + “some kind of text”;

 

  • Checks if all counties have been guessed, and if they have, a popup will appear letting the user know that they have completed the game! We’re using a conditional statement here, and also an ‘alert’ which is a popup!

You can put any message in this alert to show the user – play around with a few options!

Testing your code 

Save this code, and open guessing-game.html in your browser. Type ‘cork’ into the textbox, and see that the code works as expected. Now refresh the page, and type ‘Cork’ , with a big ‘C’. Does this register as a correct guess?

The answer is no, and that is because the array.Includes() function that we used in the code is case sensitive. So what is typed into the textbox needs to be *exactly* the same as what’s in the array – uppercase and lowercase guesses won’t match. That’s not ideal, is it? People may type Cork / cork/ CORK and the game should accept all three.

Not to worry though, there is a way to fix this!

How to handle case sensitivity

When you’re building a website, case sensitivity is a really important thing to check for. You will often be performing checks on user inputted data, so you must make sure that these checks do not depend on the user using a certain case.

The easiest way to do this, is to use a JavaScript built in function called .toLowerCase() and convert the guess to be lowercase in the code before comparing them. This way you are always comparing like for like, and case sensitivity will not be a problem.

Right now you are searching your regular countiesArray for the text exactly as it is typed in by the user. We need to change the code to use the .toLowercase() function to make the userGuesses variable case insensitive?

How to do it

Update the ‘userGuess’ variable like this:

var userGuess = (document.getElementById("userGuess").value).trim().toLowerCase();

Here, we are adding two extra ‘methods’ – .trim() and .toLowerCase() to our guess:

  • .trim(): This removes any extra spaces in the text. So if the user typed “ Cork“ with that space at the start, it wouldn’t exactly match what is in the ‘countiesArray’ array and would not be taken as a correct guess.
  • .ToLowerCase(): This converts anything the user has typed into lowercase, so we are checking for the right case.

Testing

Test out the code by typing out counties in a mix of cases and see if it works! Hurrah! You did it!!!!

Styling your Guessing Game

In Notepad ++ open an empty file and save it as ‘style.css’ with type ‘Cascade Style Sheets’ and put it in your css folder.

Next, reference your ‘style.css’ between your <head></head> tags.

<head>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="js/game.js"></script>
</head>

Add the following classes to your css file at the end.

body {
    font-family: Arial, Helvetica, sans-serif;
    margin: 0;
    background-image: linear-gradient(to bottom right, #667eea, #764ba2);
}

.main {
    border: 3px solid #f1f1f1;
    background-color: white;
    margin-left: 30%;
    margin-right: 30%;
    margin-top: 10%;
    padding: 20px;
    text-align: center;
}

.guessingGameBody {
    background: url("../img/irish-flag.jpg") 50% 50% / 100% no-repeat fixed;
}

.guessingGame {
    width: 100%;
    height: 25px;
}

.correctAnswers {
    width: 100%;
    min-height: 125px;
    margin-bottom: 20px;
}

Add the class ’main’ to your div,  ‘guessingGame’ to your text box, ‘correctAnswers’ to your textarea, and ‘guessingGameBody’ to your page <body> using the class attribute. Try to do it without looking at the below code:

<body class="guessingGameBody">
<div class="main">
<input class="guessingGame" type="text" id="userGuess" onkeyup="guess()">
<textarea class="correctAnswers" id="correct" disabled="true"></textarea>

Refresh the page, and see how this changes the page. We have styled our elements, and added a flag as the page background!

Extra Tasks

I want you to practice your CSS by styling this page.

  • Using the background-color property, change the background color of the box that contains the controls.
  • Add another Irish flag above the <h2> tags
  • Make the box that the elements are within bigger, without changing how things look on the page.
  • Change the font colours to red, white, and blue.

Helpful hint: Rather than guessing all 32 guesses to see if you reach this condition, change the numOfGuesses variable to be ‘3’ instead of 32 and the condition will be reached after 3 guesses.

Answers

Styling

  • Add ‘background-color’ to the ‘main’ class if you want to add the background color here.
  • Find a new image online and replace the image reference in the <img> tag in your html.
  • Add a class to your elements which has the property ‘color’. This sets the font colour of text within the element.
  • See if you can change the list of items that are being guessed. Swap out countie for movies, presidents. See what you can do here with the knowledge and skills that you have just learned.

What we have learned so far

  • What an array is.
  • How to search an array for an item.
  • How to convert an array of data to a string of text to display on a webpage.
  • How to add an item to an array.
  • How to take an array, perform a function on the data, and add that data to a new array.
  • How to call a Javascript function on a keyboard event.
  • How to go to the next page in Javascript.

Troubleshooting

If your game is not working:

  • If you can see html tags when you open your html page then your file isn’t saved correctly. Use Notepad++ or Visual Studio Code and save the file as the right type.
  • Go through your code and make sure it’s all exactly matching what is in this document.
  • Check that your HTML file has referenced your JavaScript and CSS files in the <head> </head> section.
  • In your browser, click ‘CTRL + Shift + I’, or F12 which opens a panel at the bottom or side of the screen. This is the developer panel, and it’s where your browser will show any JavaScript errors that have occured in your code. Go to the ‘console’ tab and any red lines in here will be errors. You can see the line number that has the error and check the code on that link.
  • As a last resort, go to the completed project and compare your code with the code in this project!
Back to: 32 Counties Coding Challenge
Lesson Details
Want to love what you do?Let us show you how

Sign up to find out what's coming next at StephMyLife Freelancer Bootcamps, and how you can reignite your passion for your career!