What Is An Algorithm?

What Is An Algorithm?

Welcome back! This is the third post in an introductory series about learning programming. In the last post I covered how we can represent data and operate on it in the context of a computer program. That makes for a natural bridge to today’s topic: algorithms. So, what is an algorithm?

Al Gore Rhythm Pun
No, it’s not this. This is an Al Gore Rhythm.

You might have an idea of what an algorithm is based on things you’ve heard other people say. I’ve watched friends scroll through their Facebook news feed and complain about how the “the algorithm” is always showing them the same posts or the same people. While this is true, algorithms affect our lives in many other places besides social media. Every time we play a video game, search Google, or swipe a credit card we are relying on algorithms to produce the results we desire. Software and algorithms go hand in hand.

Simply put, algorithms are precise, deterministic instructions for performing a specific task with data.

The key words here are instructions and data. An algorithm must use data that a computer can represent. We talked about what that data looks like and what operations are available to a computer for manipulating it in the previous post. Now we need to discuss how to build a complex set of instructions for the computer to carry out. We will cover three fundamental building blocks for creating algorithms: variables, input/output, and control flow.

Variables

One thing we neglected to cover when we were talking about data is the concept of variables. In a computer program, a variable is a placeholder for data. It represents a location in memory where a value can be stored. We can define variables by giving them a name and, depending on the programming language, possibly a data type.

Storing data in variables is a key component of creating useful algorithms. We often need to save off pieces of data to be used in a later step in the algorithm, and variables provide us a method of doing that.

Variables are powerful because they allow us to store the state of previous calculations, but they are a double-edged sword. As the number and scope of variables grows, so does the complexity of the program. It’s best to be judicious about their use in order to write programs that are understandable and maintainable.

Input and Output

It’s great to be able to store data in variables, but where does that data come from? And where does it ultimately end up? This is where input and output comes in. You might see it abbreviated as “I/O”, and hear people say it like, “Eye Oh”. You could make fun of these people, but that wouldn’t be very nice.

I/O is an extremely important feature for allowing programs to be useful to humans. If I didn’t input my personal data into Facebook, they wouldn’t be able to sell it, err I mean, I wouldn’t have a personalized profile to connect with friends and family.

If computers couldn’t output data to the screen, my enemies would have no way of knowing when I’m dancing over their lifeless corpses in Fortnite. This is all very important stuff.

Input

Input comes in lots of different forms. One example is data that users enter manually, like their name and email address when subscribing to my blog. Input could be arrow key presses and mouse movement when playing a first person shooter. It could even be a credit card number when swiping one’s credit card at a fast food restaurant.

Output

Likewise, output can come in many forms. It could be the computer graphics displayed on your monitor when playing a video game or watching Netflix, an Excel file, or it could even be a web page, like the one you are currently reading.

At the most basic level, input and output could even be as simple as a single piece of data. A large part of programming useful algorithms is figuring out how to chain together numerous smaller components using their inputs and outputs.

Control Flow

The last building block we need to cover is control flow. Here we are dealing with determining the order in which instructions are carried out. While there are many ways to give instructions, not all of them are good.

When programming it’s important to keep in mind who your audience is. The compiler/interpreter is one member of that audience, but yourself and other programmers are arguably more important to cater to. If programs are difficult to comprehend they will be difficult to modify and improve. That’s why we use something called structured programming.

Before the idea of structured programming came along it was like the wild west out there in Nerd Land. People used GoTo statements in their code to just jump around to wherever they wanted. Sounds awesome, right? No restrictions, unlimited freedom. What could go wrong?

Well, it turns out this was a pretty terrible idea. People wrote spaghetti code that was unmaintainable. It got so bad that a dude named Edgar Dijkstra came along and said, “Hey! Stop this madness! It’s harmful!“. And just like that, structured programming was born.

Edsger Dijkstra calls goto statements harmful.
Here we see Edsger complaining about having his yearbook photo taken.

Structured programming is the concept of restricting which kinds of control patterns are acceptable when giving the computer instructions. Most modern programming languages force these restrictions upon you, and for good reason. There are two main advantages to doing this. Both of these advantages are to help make programmers’ lives easier:

  1. Structured programming makes it easier to avoid mistakes.
  2. Structured programming makes it easier for you or somebody else to understand your program.

There are only a few different patterns used in structured programming, but they are sufficient for expressing any kind of algorithm you would like to implement. We will refer to these patterns as sequence, choice, and repetition, and we will use flow charts to help describe their behavior. The rectangles represent actions, and the diamonds represent decisions.

Sequence

What Is An Algorithm? An example demonstrating the sequence pattern.
Sequence Pattern

The sequence pattern is the simplest of the three. It simply involves executing one task after another in succession.

To the right is an example demonstrating an algorithm for finding more joy, losing weight, and making chicks dig you, using only the sequence pattern.

Choice

Choice represents a fork in the road. We ask a question, and then one of two things will occur depending on the answer. The answer is expressed as a piece of Boolean data, that is, either true or false. There are two basic variants of this pattern. The one-way branch either does something or nothing at all, while the two-way branch chooses between two options.

Below is an algorithm for selecting the greatest quarterback of all-time, using only the choice pattern. Both the one-way and two-way branches are demonstrated.

What Is An Algorithm? An example demonstrating the choice pattern.
One-Way and Two-Way Choice Patterns

Repetition

With repetition, a set of instructions are repeated until some condition is met. “Loop” is another term people will use to describe this pattern.

There are two basic variants here as well, the pre-test loop and the post-test loop. The difference between them is when the condition is checked. Here is an example illustration demonstrating the algorithm used by the New England Patriots.

What Is An Algorithm? An example demonstrating the repetition pattern.
Pre-Test and Post-Test Repetition Patterns

Unfortunately, this particular example appears to be an infinite loop, which we will try to avoid in our programs if we don’t want them to crash. We can avoid such scenarios by combining these three patterns into more complicated ones that allow us to create more complicated logic. Let’s put everything we’ve learned together and take a look at how to do that with a full example algorithm.

Example Algorithm: Fizz Buzz

Fizz Buzz Algorithm

Fizz Buzz is a good example algorithm to demonstrate these concepts. Our goal is to print out every number from 1 to 100. However, we need to replace each multiple of three with the word “fizz”, and each multiple of five with the word “buzz”. If the number is a multiple of both three and five, then we need to replace it with the word “fizzbuzz“.

To the left is an example flowchart demonstrating an algorithm for Fizz Buzz. If you examine it closely, you’ll realize that we are using all three of the building blocks covered in this post: variables, input/output, and control flow. We are also using data operations we learned about in the previous post.

We start by creating the “number” variable and setting its value to 1. Then we create a pre-test loop where we check if the number variable is less than or equal to 100.

Inside this loop are various decisions for determining when to output “fizz”, “buzz”, the contents of the number variable, or a new line. We use concepts like the modulo operator, the AND operator, and equality checks to make these decisions.

We continue performing these calculations until the value of the number variable causes the initial pre-test condition to return false.

After this program completes, the screen would have output that looks like this, with the pattern continuing all the way up to 100 (or in this case, “buzz”):

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
... 

Summary

We started this post by posing a simple question: what is an algorithm? We learned that an algorithm is a set of instructions for performing a task with data, and we talked about the three building blocks for creating them: variables, input/output, and control flow. In our final example, we learned how to combine these building blocks to create complicated algorithms and model them with flow charts.

In the next post we will start learning about what we use to turn flow charts into code that computers can understand: programming languages. Until then, make sure to subscribe to stay up to date with the latest content.

Representing Data in Computer Programs

Representing Data in Computer Programs

Welcome to the second post in my introduction to computer programming series. In the first post we learned about basic computer literacy and wrote our first “Hello World!” program. We also talked about how computers need information, which we usually refer to as data, to operate on. This post will cover the topic of representing data in further detail. We will be working with data often, so it’s important to know what it looks like.

Now, seasoned programmers may accuse me of oversimplification on this topic. They have a valid point, but my goal is to help newbies learn the craft, not to bog them down in the details. In due time your programming journey will fill in many of the gaps I am intentionally leaving blank.

Data Types

Let’s start talking about representing data by discussing the three main types of data: Numbers, Text, and Booleans (true/false). While there are variations on these, these three types serve as a useful place to begin our discussion.

Numbers

Number pad for entering data

Numbers could be integers, but they could also have decimal points in them. Or they could be negative. Different types of numbers are not always represented in memory the same way, but we can save those details for a later discussion.

Text

Text just refers to a series of characters. In the “Hello World!” example we covered in the previous post, “Hello World!” was a piece of text data. We usually call a piece of text data a string because it is a string of ASCII or Unicode characters. These are just standards for mapping characters to numbers so we can represent them as binary numbers. From now on we will refer to any piece of text data as a string.

Booleans

Booleans are the simplest of the three data types. Much like a transistor, they can only be found in one of two states, in this case true or false.

The best thing about a boolean is even if you are wrong, you are only off by a bit. 😜

Operating On Data

We’ve now seen that there are three main ways of representing data. There are also three main operations that a computer can perform on data. Let’s refer to these three operations as Math, Comparison, and Boolean. These three operations are ways of using the data we already have to create new pieces of data.

Math

Data: Math is a wonderful thing
Get off your ath, let’s do some math!

We can use math to create new numerical data from the data we already have. For example, adding the numbers 5 and 2 gets us a new piece of numerical data, 7. Here are some mathematical operations we can perform:

  • Addition, often represented in code by the + symbol.
  • Subtraction, often represented in code by the symbol.
  • Multiplication, often represented in code by the * symbol.
  • Division, often represented in code by the / symbol.
  • Modulo, often represented in code by the % symbol.

Modulo might be a foreign term to you. It simply means performing division and returning the remainder.

Comparison

Comparing data car analogy
The car on the right is greater than the car on the left.

We can compare multiple pieces of data to create new boolean data. For example, asking if 2 is less than 7 gets us a new piece of boolean data, true. Here are some comparisons we can perform:

  • Less than, often represented in code as <
  • Less than or equal to, often represented in code as <=
  • Equals, often represented in code as ==
  • Greater than, often represented in code as >
  • Greater than or equal to, often represented in code as >=

Boolean

We can use boolean logic to create new boolean data. For example, it is true that 2 is less than 7, and it is false that 2 is less than 1. Asking if either of these values are true gets us a new piece of boolean data, true. However, asking if both of these values are true gets us a different answer, false. For further study on this, read up on boolean logic and De Morgan’s laws. Here are the three ways of combining boolean data:

  • AND, often represented in code as &&
  • OR, often represented in code as ||
  • NOT, often represented in code as !

The AND operation checks if both values are true, while the OR operation checks if any of the values are true. The NOT operation returns the opposite value of the original piece of boolean data.

Why Representing Data Matters

Wow, we covered a lot of ground! But it feels a bit academic, doesn’t it? The point of all of this is not to bore you to tears, but to show you that the amazing and wonderful computer programs that you use on a daily basis are just doing basic operations like these on the data you provide them. From your favorite websites to your favorite games, there is nothing magical going on.

However, combining these operations so that something useful happens can be a challenging task. This activity is called creating algorithms. Simply put, an algorithm is a set of instructions for the computer to follow. When we write code, we are really just writing algorithms that the computer can understand. We will talk much more about algorithms in the next post.

If you had trouble with any of this, leave a comment so myself or somebody else can help you out. And remember to subscribe so that you can stay up to date with this series and the rest of the content I publish.

Basic Computer Literacy

Basic Computer Literacy

Do you ever hear people discussing computers or technology and think to yourself, “Wow, I have no idea what these nerds are talking about, but they sure do sound smart.”? Or maybe even, “Wow, I wish these nerds were socially aware enough to change the subject.”? If you’ve ever found yourself in those shoes, you might benefit by developing some basic computer literacy.

The computer is incredibly fast, accurate, and stupid. Man is incredibly slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation.

Leo Cherne

I hope to make this post the beginning of a longer series about learning how to write computer programs. I’m starting out by covering basic computer literacy because it is important to have that foundation in place first. After all, how can we write programs for computers if we don’t really know what they are? Let’s start by tackling a few key terms.

Hardware vs Software

The first important distinction we need to make is the difference between hardware and software. To put it simply, hardware has physical form. You can hold it in your hand and tinker with it. Some examples of hardware include a keyboard, a mouse, a screen or monitor, a graphics card, or a CPU (Central Processing Unit).

Hardware vs software comparison
Some hardware running some software.

Software, by contrast, does not have a physical form. It exists only as information stored inside the computer. Some examples of software include Facebook, Twitter, Gmail, Microsoft Excel, your web browser, my silly JavaScript games, and of course Flappy Bird. As budding computer programmers, our goal is to learn how to produce robust, useful software.

What Is A Computer?

A computer is a device composed of hardware that is powered by electricity. Its purpose is to store, retrieve, and process data. Data is just another word for information. Without data, a computer would just sit there with nothing to do. A computer could be many things, including your smart phone, your laptop, or a web server.

Programmable

One unique aspect of a computer is that it is programmable. This is the property of the computer that we are the most interested in because we want to control how data gets operated on through the programs we write.

A computer displaying code.
We want to write programs, like this one! Except we will be putting our leading curly braces on the next line because we are not barbarians.

Most modern computers are designed based on the von Neumann architecture. Why am I telling you this? Mainly to look smart, but also because this architecture is what allows us to store both data and the instructions for operating on it (programs) in the same memory. This flexibility is what allows for so many awesome programs to run on the same computer. It would be a real shame if computers had to be totally rewired each time you wanted to switch between programs. Before our boy von Neumann came along, that’s what we had to do.

Digital

Computers are digital. What this means is that the data is stored in memory via a very large number of switches. These switches are more formally known as transistors. Each of these transistors represents something called a bit, and can be found in only one of two states, on or off. These bits are then gathered into groups of 8, which we call a byte. Computer memory is just a big pile of bytes. As the number of bytes grows we start using bigger units to measure them, like kilobytes, megabytes, gigabytes, and terabytes.

A light switch representing a transistor.
It would take 10 of these light switches to represent the decimal number 1000 in binary. Luckily, transistors are much smaller than light switches.

The two different states of a bit are represented by a 1 and a 0 respectively. You may have heard people refer to “ones and zeroes” when talking about computers. This digital aspect of computers is what they are referring to. Thus, understanding how binary numbers work can be helpful, especially when writing programs at lower levels of abstraction. Every piece of data we deal with, from personal demographic data to the colors you see on the screen, is ultimately represented by a series of ones and zeroes stored in memory. Fortunately, this design detail is usually hidden from us when we are programming with higher level programming languages.

Programming Hello World

That about wraps things up, but first I want to give you a small taste of things to come if you decide to learn more about programming. You are going to write your first program, and you don’t even have to leave this page!

When learning to program in a new language or environment, computer programmers often write a program called “Hello World!”. This is the simplest program you can write. It simply prints out the text, “Hello World!” to the screen. You are going to write your first “Hello World” program directly in your web browser.

If you are reading this on mobile, now would be a good time to switch to your laptop or desktop computer. Once you have done so press the F12 key on your keyboard. This will launch the developer tools for your browser. In the example I used Mozilla Firefox, but this keyboard shortcut should work in whichever browser you are using. You can also get there by right clicking on your browser window and choosing the appropriate option. Next, navigate to the console tab of the developer tools and type in the following: alert(“Hello World!”).

In this case, alert tells the browser to alert the user of something via a dialog box. We are passing it some data, in this case the text, “Hello World!”. This data is what we are going to show to the user.

Basic Computer Literacy: Alerting "Hello World!" in the console.

Once you have that typed out, press the Enter key on your keyboard. You should see something pop up that looks similar to this, minus my shameless plug:

Basic Computer Literacy: Hello World alert dialog appears on the screen.

Summary

Congratulations! You have gained some basic computer literacy and you have written your first program in a language called JavaScript. JavaScript is one of the most popular languages in the world, and it is running on almost every website you visit. It’s also a language I have used extensively in my game tutorials.

Leave a comment below if you had trouble with any of this so myself or somebody else can help you out. And remember to subscribe so that you can stay notified of new content and move on from basic computer literacy to an even deeper understanding of how they work. Continue on to the next post in the series to start learning more about data.

Mitigating Climate Change: Thoughts From A Conservative Perspective

Mitigating Climate Change

For reasonable people, few topics are more nauseating to listen to these days than debates about mitigating climate change. The two “solutions” discussed most often by politicians and activists are different in approach, yet similar in terms of their detachment from reality.

On one hand, you have those who deny the existence of the problem entirely. On the other hand, you have those who suggest we will all be doomed within a decade without extreme levels of government intervention and an immediate demolition and rebuilding of the economy from the ground up. I’d like to suggest the radical idea that there are options for mitigating climate change lying between these two extremes.

My Biases

As somebody who harbors political views that are mostly right of center, I have to admit that I was slower than some to hop aboard the “we ought to do something about climate change” train. For me the reasons were two-fold, and I suspect many conservatives can relate:

  1. I hadn’t researched the topic enough. There are lots of problems worth thinking about, and nobody has the time to be an expert on everything.
  2. I didn’t trust or like the messenger. It all seemed a little too convenient as I watched politicians gleefully propose big government, top-down control as a way to reduce climate change. They are constantly in search of a problem to fit this solution, so it was no surprise that they latched onto the existential threat of climate change.

Eventually I realized that despite how annoying and generally wrong about everything Bernie Sanders is, I ought to take climate change more seriously than I had been. We have burned lots of fossil fuels over the past century, and have improved the standard of living all around the world as a result of it. Unfortunately, these actions have had some unintended side effects. Evidence suggests that the increased use of fossil fuels over the past century is directly related to the increased levels of carbon dioxide in the atmosphere and the warming temperatures we have seen.

We don’t know exactly how this trend will play out over the next 100 years. Conditions might get really bad, or they might turn out to be pretty manageable. Politically motivated actors will tell you they know exactly what will happen, but they do not. Different models show a range of potential outcomes.

What we do know is that climate change poses potential risks to the well-being of humanity, and we ought to take some steps to mitigate against it. We also know that the use of fossil fuels has enabled millions of people to live better and longer lives.

So what can we do? Well, planting a whole bunch of trees seems like an uncontroversial, easy win and should help soak up some of that carbon dioxide, but some people think that will only get us so far. Attacking the problem on multiple fronts will be the best approach. There are three areas for mitigating climate change that seem promising to me.

Technological Innovation

One area that has promise is emerging technological innovations. An example from the recent past is fracking, which ironically, many Democratic politicians love to demonize. The fracking revolution has led to an increase in natural gas use and a decrease in coal consumption. Natural gas is a much cleaner source of energy than coal, and is a big reason why the United States has been consistently reducing their emissions in recent years. Like most technologies, we have made it better and safer over time.

Mitigating Climate Change: Chart showing how coal use has gone down and natural gas use has gone up.
Coal-generated electricity is declining as natural gas and renewable energy sources are expanding.

There are still potential concerns, like methane leaks not being properly prevented. It’s not a perfect solution, but perfect is often the enemy of good. We ought to celebrate these short-term wins while striving towards doing even better.

Future Developments

Lots of companies are doing just that. Tesla is doing work that has the potential to make a big difference in the amount of fossil fuels we use. Their electric vehicles consistently receive rave reviews from drivers, and Tesla’s success has inspired other car manufacturers to develop their own electric vehicles. If these vehicles become widely adopted at large scales that would be a big step in solving a small part of the problem.

Mitigating Climate Change: Elon Musk,  the  co-founder and CEO of Tesla.
Elon Musk, the co-founder and CEO of Tesla.

Companies like Beyond Meat and Impossible Foods are attacking the problem from a different angle. They have created plant-based burgers that imitate the taste of beef. Fast food chains have already started partnering with them. These developments have the potential to reduce some of the negative environmental effects caused by current agriculture practices.

Another often overlooked technological innovation is the increased capability for people to work remotely. Solutions have been developed that allow us to collaborate with people living on the other side of the world, all from the comfort of our own home. More and more companies and people are taking advantage of this, leading to less time spent making long commutes. Less people on the road every day means decreased emissions and decreased traffic. That sounds like a win to me.

There are other companies attacking this problem too. Many of them are experimenting with ideas I’ve never even heard of. There is a lot of promise to be found in the the innovative spirit of entrepreneurs. The free market is an amazing engine that has solved many of our problems over the years. However, putting hope in future technology alone seems like a bit of a gamble. Maybe it will be enough, but maybe it won’t. Or maybe we won’t develop the solutions quickly enough.

That leads me to the second area of promise for mitigating climate change. It involves technology that is already here right now.

A Nuclear Renaissance

What if we discovered an energy source that:

  1. Is extremely energy dense, even more so than fossil fuels.
  2. Has zero emissions.
  3. Produces little waste.
  4. Wasn’t dependent on external conditions (sun shining, wind blowing).

Wouldn’t we be jumping all over this opportunity to mitigate climate change? It turns out, no, because that’s what we have with nuclear fission. While countries like France have shown how big of an impact this technology can have on reducing emissions, most of the world hasn’t taken notice. Despite its many advantages, humanity has failed to harness the power of nuclear energy to the fullest extent that it should. This is due to many reasons, some legitimate, and some political.

Safety

Most concerns revolve around the safety of the plants and the disposal of nuclear waste. For many, events like Chernobyl come to mind. While we shouldn’t dismiss safety concerns out of hand, it is worth comparing these scenarios to the alternative. Research shows that many lives have been saved by nuclear energy that would have been lost due to air pollution. Most accidents are preventable by following proper procedures. While we have made nuclear energy pretty safe already, more investments in nuclear technology will inevitably lead to better, cheaper, and safer outcomes.

Waste Disposal

When it comes to waste disposal, nuclear energy might actually have an advantage over renewables. Due its density, nuclear energy produces very little waste. The waste is radioactive, but we can just bury it deep underground, and can do so for quite a long time. In contrast there is no good plan to deal with solar panels and wind turbines, which cover very large surface areas, after their 20 year lifespans are up. From a holistic perspective, this should be a concern to environmentalists. For more information about this issue, check out this article.

What are we gonna do with all of these?

If the climate change situation is as dire as many claim it to be, shouldn’t we be willing to accept the risks associated with nuclear energy?

I think the proper application of technology might be enough to get us where we need to be. However, some people think we need to act now. I haven’t heard many good ideas when it comes to government intervention, but there is one I’ve heard that shows some promise.

Revenue Neutral Carbon Tax Combined With Decreased EPA Regulatory Authority

The name for my plan doesn’t exactly inspire as many warm and fuzzy feelings as, “The Green New Deal“, does it? Well that’s okay because while it doesn’t sound as cool, my plan is actually a reasonable policy proposal. Also, I lied. This isn’t really my plan. It has been proposed by people who have been doing a lot of thinking on the subject.

Currently, greenhouse gas emmisisons are regulated by the Environmental Protection Agency. Their task is to decrease emissions by telling businesses what to do. They make rules about how much emitting cars and trucks are allowed to do. So instead of adjusting price signals through taxes, we are currently using command-and-control policies to achieve the desired decreases in emissions. One problem with this is that the companies using fossil fuels are only incentivized to meet the bare minimum requirements.

Another problem is that the decisions about how to reduce emissions are left up to regulators instead of the businesses themselves, and the federal government has a less than stellar track record at running efficient and profitable enterprises.

Rethinking Incentive Structures

A replacement tax on fossil fuel production solves both of these problems. It prices in the negative externality of polluting our common resource, the atmosphere. It incentivizes companies to work to eliminate emissions entirely and thus avoid paying the tax. And unlike regulations, taxes produce revenue. We can use this additional revenue to cut taxes somewhere else. This additional revenue will allow us to compensate the poorest people in our communities who would be most affected by the increased cost of fossil fuels.

Summary

Climate change is a divisive topic these days, but there are reasonable actions that we can take that have the potential to help mitigate it. By creating a business environment that encourages innovation, reviving the nuclear industry, and making a few changes to incentives we can start steering humanity towards a better and more sustainable future. Thanks for reading, and let me know your thoughts in the comments. This topic is huge, and I’m sure there is much more information out there I am unaware of. And don’t forget to subscribe!

How To Build Hangman With JavaScript

How To Build Hangman With JavaScript

In my last tutorial I described the snake game I built using JavaScript, and before that I built a version of minesweeper. For this week’s post I decided to show you guys how to build hangman with JavaScript. I’m sure there are plenty of coding choices I’ve made that can be criticized, but hopefully I’ve still accomplished my goals. Namely, to have fun making little games and teach people a little bit about JavaScript and programming.

Click here to play movie hangman!

Here are the three files necessary for creating the hangman game:

I already know what you’re thinking. How did I afford such an outstanding artist? Believe it or not, I actually created that condemned bandit artwork all on my own. Like most professional programmers, I can wear multiple hats.

I loved playing hangman when I was growing up as a kid. It’s one of those rare games that teaches you important concepts without you even realizing it. In order to become good at hangman, you have to become proficient with language. Another thing I loved as a kid (and still do) was watching movies. So naturally, I decided to combine these two passions and create “Movie Hangman”.

Unlike my previous game tutorials, I decided to build hangman with mobile users foremost in mind. To accomplish this I used something called CSS media queries. We use these to apply different CSS rules for different screen sizes. Be sure to check it out in the CSS file if you’re interested, as the bulk of this post covers the JavaScript game logic.

Alright, let’s start learning how to build hangman with JavaScript.

Rules of Hangman

  1. A word or phrase is chosen for the player to guess.
  2. Initially, the player can only see how many letters and words make up the full word or phrase.
  3. The player begins by guessing letters. Each correct guess reveals every location where the letter exists in the word or phrase. Each incorrect guess results in another piece of the man getting added to the gallows.
  4. If he thinks he knows it, the player is also allowed to guess the entire word or phrase.
  5. The player wins if he successfully guess the word or phrase. He loses if he completes the picture of the condemned man, resulting in his grim demise.

Game Object

JavaScript code for creating our hangman game object 1/3.
JavaScript code for creating our hangman game object 2/3.
JavaScript code for creating our hangman game object 3/3.
JavaScript code for creating our hangman game object.

The Game function is responsible for creating our game object. This object will be responsible for holding the data about the current state of the game and the methods for acting upon that data. The game object will have 7 internal variables for handling state: word, guessedLetters, maskedWord, incorrectGuesses, possibleGuesses, won, and lost.

The word variable stores the word that the player is trying to guess. We assign it a random movie from our list of movies when we initialize the game object.

The word in the hangman game.
Word.

The guessedLetters variable is an array. We use it to store letters as the player guesses them.

The maskedWord variable is the word or phrase as it is displayed to the player. It starts out as a bunch of underscores with spaces separating the words, and it slowly gets filled in as the player makes more correct guesses. We initialize it via a for-loop.

The masked word in the hangman game.
Masked word.

The incorrectGuesses variable is a counter for storing the number of times the player has guessed incorrectly. Too many wrong guesses and the player will lose the game. Naturally, this counter starts at zero.

The possibleGuesses variable is a string containing all of the letters in the alphabet. Letters are removed as they are guessed. These are displayed to the player so he doesn’t have to remember what he has already guessed.

Possible guesses in our hangman game.
Possible guesses.

The won and lost variables keep track of whether the player has won or lost the game. These are displayed to the player when the game is over.

Public Methods of the Game Object
  • getWord: A simple getter for the word variable.
  • getMaskedWord: A simple getter for the maskedWord variable.
  • guess: We call this function whenever a player guesses a letter. After capitalizing the letter for consistency we make sure it hasn’t already been guessed. Then we add it to the the array of guessed letters and remove it from our list of possible guesses. If the word contains the guessed letter we determine what the indexes of those matches are. Then, we reveal those letters in the masked word that is displayed to the player. If the word does not contain the guessed letter we call the private handleIncorrectGuess function to increment the number of incorrect guesses and check for a loss.
  • getPossibleGuesses: The possibleGuesses variable returned as an array using the spread syntax.
  • getIncorrectGuesses: A simple getter for the incorrectGuesses variable.
  • guessWord: We call this function whenever the player wants to take a guess at the entire word or phrase.
  • isWon: A simple getter for the won variable.
  • isLost: A simple getter for the lost variable.
Private Methods of the Game Object
  • guessAllLetters: This function loops through all of the letters in the word and calls guess on them. Its purpose is to display the movie title after the player guesses it correctly, or alternatively when the player has lost the game.
  • handleIncorrectGuess: This function takes care of a few things whenever a player guesses wrongly. It updates the number of incorrect guesses and checks for a loss. If a loss has a occurred, it calls guessAllLetters.

There is one more function worth talking about in this section called replace. It doesn’t really belong in our game object because it has utility outside of that context. We are gonna keep it on its own in case we ever decide to use it later.

JavaScript function for replacing a character in a string at the specified index.
JavaScript function for replacing a character in a string at the specified index.

The function takes a string, an index, and a replacement string as parameters. It substitutes the replacement string for the character at the specified index. We use it to replace underscores with characters in our masked word.

That wraps up our discussion about the game object. Let’s move on and talk about how we handle player input.

Handling Player Input

JavaScript code for handling player input (1/2).
JavaScript code for handling player input (2/2).
JavaScript code for handling player input.

Our goal is to make this game a fun experience on a desktop computer as well as a mobile phone. In order to do that we need to offer a few different ways to play.

One way to play involves using the keyboard to enter letters. This works great on a full-fledged hardware setup, but not so great on a mobile phone. For mobile users we ought to offer a way to use the touchscreen to make guesses.

Guessing a letter

Both of these input methods resolve down to the same basic action: sending a letter to our game object as a guess. This is a pretty good indicator that we should have a common function for handling this logic.

We will call this function guessLetter. It resides inside the listenForInput function which will be used for setting up our input handling logic. When called, and as long as the game is still going on, this function calls guess on our game object and then calls render to update the screen. We’ll talk more about the render function momentarily.

For both the keyboard and touchscreen input we attach event listeners to the document body.

Handling Touchscreen Input

When the player touches a letter (or clicks on it with his mouse), the handleClick function is called. This function checks the class list of the HTML element that was clicked. If the class list contains the “guess” class, that letter is passed to the guessLetter function.

Handling Keyboard Input

Handling keyboard input is a bit more complicated because there are more features to implement and more validation is necessary. The function that takes care of all this is called handleKeyPress.

The first thing we do is calculate some values that will help us take appropriate action. One of the first things we do is determine if the key that was pressed is a letter. Then, we grab HTML elements representing the guess word button, the new game button, and the guess box. We also check to see if the guess box is already populated with a win/loss message.

Finally, we take action. If the cursor is not in the guess box and player pressed a letter, we make a guess. If the game is over and the player pressed enter, we start a new game. And if the player pressed enter, the game is still going on, and there is content inside the guess box, we take a guess at the full movie title.

Guessing the Word

JavaScript code for making a guess at the full word in our hangman game.
JavaScript code for making a guess at the full word in our hangman game.

The player can take a guess at the full word by clicking the guess word button. He can also do so by pressing enter, as we saw in the previous section. When this occurs, the guessWord function is called.

This function first checks if the game is still going on. If it is, the guessWord function of the game object is called, and then render is called to update the screen.

Rendering the Graphics

JavaScript code for rendering updates to the screen.
JavaScript code for rendering updates to the screen.

Let’s discuss how to update the screen after changes are made to the game object. This is handled by the render function, and it is called after every guess that the player makes.

Overall it’s a pretty simple function. We set the innerHTML of the different elements that correspond to the data in our game object. We also set the image by using a neat little naming convention hack.

The trickiest part of this function is how we render the possible remaining guesses to the screen. We have to clear out the div and then loop through the possible guesses variable, appending the appropriate span as we go along.

Starting a New Game of Hangman

JavaScript code for starting a new game of hangman.
JavaScript code for starting a new game of hangman.

Okay, we’re almost done building hangman. Soon you’ll have all of the pieces needed for learning how to build hangman with JavaScript. The last thing to cover is kicking off a new game!

When the page loads, we call the Game function to create a new game object. Then we call render to display the game data to the screen, and call listenForInput to, well, start listening for input from the player.

We also have a function called newGame. If you observe the HTML, you’ll see that this function is attached to the new game button. Instead of going to the trouble of resetting our game object and event listeners, we use a neat little trick to go back to the most recent URL in the browser history. This should redirect the player to the URL of the hangman game, and reinitialize all of the JavaScript.

Conclusion

Congrats on learning how to build hangman with JavaScript! Hopefully it makes sense after breaking it up into modules like this. If you have questions or see ways to improve the code, I’d love to hear from you in the comments!

For your next steps, you could try adding some more features, like different, selectable word categories or supporting characters besides just letters.

Let me know in the comments what other simple games like this you would like to see, and don’t forget to drop me your email so you don’t miss the next one that comes out. You will also receive my free checklist for writing great functions.

Take care, and God bless!

On Andrew Luck’s Retirement

On Andrew Luck's Retirement

In the prime of his career, at a mere 29 years of age, Andrew Luck stepped away from the game of football. As a life-long Colts fan, I had to write a post on Andrew Luck’s retirement. Like everyone else, I was shocked when I heard the news. The more I thought about it, however, the more it made sense.

From the perspective of a fan I’m saddened by the loss of such a special talent at such an inopportune time, and I’m angry at an incompetent front office that didn’t do enough to protect him early in his career.

From the perspective of a human being, I’m happy that Andrew Luck has chosen to live the kind of life that makes him happy. And I’m happy that he will be able to fully heal from the painful injuries that have plagued so much of his career.

The Career

Andrew Luck was drafted number one overall by the Indianapolis Colts in the 2012 NFL Draft. He joined a decimated roster severely lacking in talent, yet manged to drag the team to the playoffs with an 11-5 record. It was an impressive feat for any quarterback, let alone a rookie.

Filling the Big Shoes of the big forehead

He built on that success in the following seasons, eventually leading the Colts to the AFC Conference Championship game in 2014. Colts fans were accustomed to to heroic play from the quarterback position, yet Andrew Luck still managed to dazzle us with his comebacks and ability to mask over so many of the team’s weaknesses. His play reminded us of the legend whose shoes he was trying to fill.

Yet he had a persona and style all his own. He started a team book club, made awkward jokes at press conferences, and never totally fit the stereotypical franchise QB mold. He seemed to get more energized by big hits, and even complimented defenders after taking a big shot from them.

The COnstant Injuries

And he wasn’t short on opportunities. He was consistently near the top of the league in number of knockdowns (sacks + hits). His playing style combined with poor coaching and talent acquisition led to him taking more shots than he should have.

Eventually, those hits took their toll. Over six NFL seasons he suffered torn cartilage in his ribs, a partially torn abdomen, a lacerated kidney, a concussion, and a torn labrum in his throwing shoulder. Many thought that the shoulder injury would end his career for good. Amazingly, he managed to fully recover from it and lead the Colts to the playoffs once again, winning the Comeback Player of the Year Award in the process.

Unfortunately, that wasn’t the end of the long train of injuries. He suffered another one, this time a calf/ankle issue. He ultimately decided that the rehab cycle was no longer worth it. On August 24th, 2019 he announced his retirement from the NFL, two weeks before the start of the 2019 season.

The Retirement

The news broke to the world in a very unfortunate way. It was leaked on social media by Adam Schefter at the end of a Colts preseason game.

Adam Schefter tweet about Andrew Luck's retirement.
The Reaction

Luck walked off the field to a chorus of boos reigning down from the stands. Part of me understands where they are coming from. They didn’t know the circumstances surrounding the decision, and had such high expectations for the season. It’s also worth pointing out that anybody who stays for an entire preseason game is more likely than most to have a little too much alcohol in their system.

The Colts were a team on their way to the top, and now the fans had the rug pulled out from under them. Finding a franchise quarterback is no easy feat, and the Colts now find themselves searching for a new one. I think the boos were more of an emotional reaction to the situation than a judgement on Andrew Luck. Time and clarity softened most peoples’ reactions quite a bit.

Still, it was an ugly moment, and not a good look for Colts fans. They should have treated him better. Andrew Luck gave too much to Colts fans to warrant such a lousy send off.

The Reasoning

In the press conference after the game, Andrew Luck talked about the toll the unceasing stream of injuries and rehab had taken on his body and mind. It was sad to see our star player who once played the game with contagious energy talk about how his joy for playing football was gone. He said he promised himself that he would put his body first. He seemed at peace with his decision, and ready to move on with his life.

Colts fans aren’t quite there yet. Many hold out hope of a comeback. I’m pretty skeptical about that. He didn’t make this decision lightly, and I don’t think a course reversal is very likely. I’ve suffered some major injuries and surgeries myself, and I can tell you that the rehab process can be very isolating, even when you’re not a pro-athlete. It makes you really think about what your priorities are.

The Future of the Colts

There is a lot of uncertainty surrounding the future of the Colts. We just lost our most important player. Jacoby Brissett will be stepping into the starting role. He played the whole 2017 season in Lucks’ absence, and only recorded 13 touchdowns with 7 interceptions. Not exactly MVP material.

The Quarterback Position
Jacoby Brissett playing quarterback for the Indianapolis Colts.
The new quarterback of the Colts.

However, I find a lot of room for optimism. In 2017 the Colts suffered a severe lack of talent and poor coaching. Jacoby Brissett joined the Colts only eight days before the season started. He had to learn a brand new playbook, yet still managed to beat out the other quarterbacks on the roster for the starting job. Now, after years of experience and learning from Luck, he takes the helm of a team with much better talent and coaching. He could surprise some people.

Good Coaching

Frank Reich was able to win a Super Bowl as the coach of the Eagles with a backup quarterback. Maybe he still has some of that magic left. I think he will be able to design plays that showcase Jacoby’s strengths.

It also doesn’t hurt that the Colts play in a pretty weak division and have a solid defense. I think they still have a good shot at winning their division.

In Ballard We Trust

We also have somebody who I think is one of the best general managers in the league in Chris Ballard. This team will be okay as long as he keeps finding talent. I just wish he could have arrived here sooner before Luck had to suffer so much.

Conclusion

Andrew Luck’s retirement was a reminder that nothing lasts forever. It will always be a “what could have been” story in the minds of Colts fans. He will also be remembered as an amazing player and all-around class act. I wish he could have played longer, but I’m grateful for the time he spent in Indianapolis.

TLDR:

Thanks for reading and don’t forget to subscribe!

How To Build Snake With JavaScript

How To Build Snake With JavaScript

In my last post I showed you guys the minesweeper game I built using JavaScript, and before that I built tic tac toe. For this week’s post I decided to show you guys how to build snake with JavaScript.

Click here to play Snake!

Here are the three files necessary for creating the snake game:

Now, the DOM was not originally designed for quickly updating graphics. There are better mediums to work in, but I wanted build something using basic web technologies. Still, I wanted it to be a little more dynamic than the games featured in my last tutorials. The snake game seemed to strike that balance well.

I also wanted to incorporate some of the feedback I received on my last post. I tried to use more of the modern features that JavaScript provides us, and I left jQuery behind.

With that out of the way, let’s get started. If you want to learn how to build snake with JavaScript, the first step is understanding how the game works. Let’s jump right in and talk about the rules.

Rules of the Game

  1. The board is grid of cells through which the snake can traverse.
  2. The player controls the head of the snake. It can only move in four directions: left, right, up, or down.
  3. The snake is always moving, and the body follows the path set by the head.
  4. Running into a wall or the tail of the snake causes the player to lose the game.
  5. The goal of the game is to eat as much food as possible.
  6. The snake grows by one in length whenever it eats a piece of food. Then, the game places a new piece of food in a random cell of the board.

Enums

JavaScript doesn’t really have the concept of an enum built in, but we can make our own version that will suffice. We are going to create two of them. They will prove themselves useful throughout the rest of our programming task.

Cell Type
JavaScript code for creating our cell type enum.
JavaScript code for creating our cell type enum.

The first enum to discuss is the CELL_TYPE. This an object containing three possible values: EMPTY, FOOD, and SNAKE. These are the only three values that can be assigned to a cell of the game board.

We declare it using the const keyword, which means we can’t assign the CELL_TYPE variable a different value. We also freeze the object to further lock it down. Our aim here is to create an immutable object. If the purpose of an object is to provide constant values we might as well try to prevent somebody else from changing it. This implementation gets us pretty far down that road while still being readable.

Direction
JavaScript code for creating our direction enum.
JavaScript code for creating our direction enum.

The second enum to discuss is the DIRECTION. This an object containing five possible values: NONE, LEFT, RIGHT, UP, and DOWN. These represent the directions in which the snake can be traveling. Its structure is very similar to the CELL_TYPE enum.

Objects

Our game consists of four main objects: the cell, the board, the snake, and the game. We have many cell objects that make up our board, but we only have one board, snake, and game object. Let’s discuss the functions we will use to create these objects.

Cell

JavaScript code representing a cell on our grid.
JavaScript code representing a cell on our grid.

We call the Cell function to create a very simple object representing one cell of our game board. The board consists of a grid of cells, and each cell has a few properties:

  • row: An integer representing which row on the board the cell belongs to.
  • column: An integer representing which column on the board the cell belongs to.
  • cellType: The value associated with the cell. This could be one of three values: EMPTY, SNAKE, or FOOD. These values come from the CELL_TYPE enum we discussed earlier.

Board

JavaScript code representing the game board (part 1).
JavaScript code representing the game board (part 2).
JavaScript code representing the game board.

Okay now let’s talk about the board. The Board function is a blueprint for creating our board object. The board object we create should contain all of the logic for representing and modifying our game board.

The function takes two parameters: rowCount and columnCount. We use these two parameters to specify the size of the game board. We initialize our lone internal variable using these parameters, and end up with a two dimensional array named cells. Then we loop through our cells variable and create a cell object for each slot in the array. When starting out, each cell should be EMPTY.

That takes care of the board initialization. Now let’s talk about the methods and data that we publicly expose.

Public Methods of the Board
  • cells: Our two dimensional array of cells. We just talked about how to initialize the cells variable, and now we need to allow other parts of our program to access it.
  • render: This method handles the graphics of our game. It updates the HTML document on every iteration of the game loop. Each cell has the appropriate CSS class added or removed based on its cell type.
  • placeFood: This method randomly places food on the board. It leverages a private function we created, called getAvailableCells. This private function grabs a list of currently empty cells. Then, we place food in a randomly chosen one. We call placeFood as soon as the snake has enjoyed a nice warm meal.
  • getColumnCount: A simple method that returns the number of columns. You may be wondering why we don’t just expose the variable itself, like we did with our cells array. The reason is because we pass this number by value, not reference. When we return the cells object, we are passing by value as well, but the value happens to be a reference to the object. For further details about this topic, see this post and this other post.
  • getRowCount: A simple method that returns the number of rows.

Now let’s talk about our snake object.

Snake

JavaScript code representing the snake object (part 1).
JavaScript code representing the snake object (part 2).
JavaScript code representing the snake object.

The Snake function is a blueprint for creating our snake object. The snake object we create should contain all of the logic for representing and modifying our snake.

We pass three arguments to our Snake function: cell, startingLength, and board. The cell is the starting Cell of the head of the snake, the startingLength is the initial size of the snake, and the board is the game board object that we have created by calling the Board function.

We use these three arguments to initialize two internal variables of our snake object: its head cell and its snakeParts array. We simply assign the head variable to the cell that we passed in, and then set its cell type to SNAKE.

For the snakeParts, we first push the head of the snake onto the array. Then, using a for loop, we grab the cell from the next row of the board, set its cell type to SNAKE, and push it onto the array. We do this until the length of our snake matches the startingLength. This results in a vertical snake whose head is closest to the top of the game board. Of course, we are free to change this to suit our preferences.

Before moving on to talk about the publicly exposed methods of our snake, I’d like to point something out explicitly. We have designed the board and snake objects to share the same cell objects. This is an important detail to grasp if you want to understand how these objects work together.

Public Methods of the Snake
  • grow: This method simply pushes the internal head variable onto the internal snakeParts array. We call it after the snake eats a piece of delicious food.
  • move: This method is the snake’s most complicated one. First, it removes the tail of our snake and sets its cell type to EMPTY. Next, it sets the head of the snake to the cell being moved into, and sets that cell’s type to SNAKE. Finally, it loops through all of the snakeParts and sets the cell type to SNAKE for each. This last step handles the situation where the snake is moving right after growing in size. We call the move method once per iteration of our game loop.
  • checkCrash: This method checks if our snake has crashed into a wall or itself. If the cell is undefined then we know the snake has stepped out of the bounds of the game board and crashed. If the cell is not undefined then we check if the snake has collided with itself.
  • getHead: A simple getter for our head variable.

Now let’s talk about our game object.

Game

JavaScript code representing the snake game (part 1).
JavaScript code representing the snake game (part 2).
JavaScript code representing the snake game (part 3).
JavaScript code representing the snake game.

The Game function is a blueprint for creating our game object, and the game object we create should contain all of the logic for handling the interactions between the snake and the game board. We pass the snake and board objects to the Game function as arguments.

While the publicly exposed methods of our game object are quite complex, the initialization of the object is very simple. We have four internal variables: directions, direction, gameOver, and score.

The directions array starts out empty. We use it to queue up directions that the player has pressed. The queue helps us avoid frustrating behavior when a player inputs multiple directions before the game is able to update. We do not want to punish the player for quick fingers! Using a single variable to store the direction would result in a pretty annoying control scheme.

We set the initial direction of the snake to NONE. This makes the snake motionless at the start of a new game. The directions array will be used to feed in new values to this variable.

We initialize the gameOver variable to false. We don’t want to end the game before it has begun.

Finally, we initialize the score variable to zero. We will increase the score as the snake eats food.

Public Methods of the Game
  • update: This method puts all of the pieces together. We call it once per iteration of the game loop, and it contains the bulk of the logic needed for the snake and the board to work together. After checking to make sure the game is still going on, this method calls the private getNextCell function. This function figures out which direction the snake is headed, removes that direction from the queue, and returns the cell that the snake is about to enter. Then, the method checks if the snake has crashed. If the snake has crashed, we end the game and display the final score. Otherwise, the snake moves to the next cell. If there was food there, the snake eats it and grows and we place another piece of food on the board.
  • addDirection: This method takes a direction as an argument and pushes it onto the directions queue.
  • getLastDirection: This method returns the value of the last direction in the directions queue.
  • exceededMaxDirections: We set the maximum number of directions allowed in the queue to three. This prevents the player from spamming the arrow keys a huge number of times and building up a list of directions that are no longer relevant.

Snake Game Initialization

So far we have covered the building blocks necessary for putting together a game of snake with JavaScript. However, we still have a few more pieces to talk about that revolve around initializing a new game. These pieces include initializing the HTML, initializing the input handler, and starting a new game.

One thing to keep in mind while reading this code is that we want to be able create a fresh game state with ease. Modifying our objects directly seems cumbersome and error prone if we make more changes later. Instead, we are going to throw away our old objects and create new ones.

Initializing the HTML

JavaScript code for adding a class and ids to the cells of our snake game board.
JavaScript code for adding a class and ids to the cells of our snake game board.

The purpose of this function is to initialize the HTML elements that represent our snake game board. We start by grabbing all of the elements containing the “cell” CSS class. This should get us all of the cells. Then, we loop through each one of them.

Each cell has its id set to a value that represents its row and column number. Also, we remove the CSS classes from each cell and then add the “cell” class back. This ensures that we remove any classes that were added by the previous run of the game.

Initializing the Input Handler

JavaScript code for handling user input.
JavaScript code for handling user input.

The purpose of the listenForInput function is to handle the keyboard input provided by the player. For our game, the controls are the arrow keys. This function takes the game object as an argument.

The bulk of the logic takes place inside the changeDirection function. This function is responsible for determining when to add a direction to the directions queue of the game object. We add an event listener to our document that executes the changeDirection function on every keydown event. We clear and reset it each time we call the listenForInput function.

The first time changeDirection is triggered we add the UP direction to the queue. This helps us ensure that the player will not die on the first move. On subsequent calls to the function we listen for arrow key presses.

When the snake is moving vertically we do not allow the player to add vertical directions, and when the snake is moving horizontally we do not allow the player to add horizontal directions. This prevents the player from building up a queue of redundant directions or killing the snake inadvertently. We also prevent adding directions to the queue if it is already full. The movingHorizontally and movingVertically helper functions handle these checks, and make use of the publicly exposed methods of the game object to do so.

Starting A New Game

JavaScript code for starting a new game of Snake.
JavaScript code for starting a new game of Snake.

Alright we are getting close now. Just a few more steps and you will have all of the pieces for learning how to build snake with JavaScript! Let’s talk about how to start a new game using all of the building blocks we have constructed thus far.

We have a function called newGame that we call to start a new game. Inside this function we need to set up some constants for the row and column count of our board, as well as for the starting length of our snake. We will use the constants to initialize our game objects.

Once we have our constants, the first thing we do is initialize our board by calling the Board function and passing in our row and column counts as arguments. Then, we use those counts to calculate a good starting position for the head of our snake. We could hard-code this value, but I chose to programmatically place the snake’s head in the center of the board. We pass in this center cell, the board, and the starting length value to the Snake function to create our snake object. Finally, we use the board and snake objects to create our game object using the Game function.

Next, we call initializeCells to assign ids and CSS classes to our HTML cells (represented by div tags). Then we placeFood on the board and call render to show it to the player. After that we call listenForInput to start handling the player’s keyboard input. Finally, we start our game loop. On every iteration we update the board and then render the results on the screen.

The last bit of code attaches a click handler to a button in our pop up modal. We use this click handler for starting another game once the last one has ended. It hides the modal, stops the game loop, and calls the newGame function. We call the newGame function as the first thing we do, and then again every time the player clicks the play again button in the modal.

Conclusion

Congrats on learning how to build snake with JavaScript! That was a lot of code, but hopefully it makes sense after breaking it up into modules like this. If you have questions or see ways to improve the code, I’d love to hear from you in the comments!

I hope you guys enjoyed learning about how to build snake with JavaScript. Let me know what other simple games like this you would like to see, and don’t forget to drop me your email so you don’t miss the next one that comes out.

Take care, and God bless!

How To Build Minesweeper With JavaScript

Revisit Minesweeper

In my last post I showed you guys a tic tac toe game I built using JavaScript, and before that I built a matching game. For this week’s post I decided to ramp up the complexity a bit. You guys are going to learn how to build minesweeper with JavaScript. I also used jQuery, a JavaScript library that is helpful for interacting with html. Whenever you see a function call with a leading dollar sign, that is jQuery at work. If you want to learn more about it, the documentation for it is very good.

Click here to play minesweeper! You will want to play it on your desktop computer because of the control scheme.

Click here to view the source code on GitHub.

Also, the long-awaited Part 2 is now available!

If you want to learn how to build minesweeper with JavaScript, the first step is understanding how the game works. Let’s jump right in and talk about the rules.

Ultimate Guitar PDFs

Rules of the Game

  1. The minesweeper board is a 10 x 10 square. We could make it other sizes, like the classic Windows version, but for demonstration purposes we will stick to the smaller, “beginner” version of the game.
  2. The board has a predetermined number of randomly placed mines. The player cannot see them.
  3. Cells can exist in one of two states: opened or closed. Clicking on a cell opens it. If a mine was lurking there, the game ends in failure. If there is no mine in the cell, but there are mines in one or more of its neighboring cells, then the opened cell shows the neighboring mine count. When none of the cell’s neighbors are mined, each one of those cells is opened automatically.
  4. Right clicking on a cell marks it with a flag. The flag indicates that the player knows there is a mine lurking there.
  5. Holding down the ctrl button while clicking on an opened cell has some slightly complicated rules. If the number of flags surrounding the cell match its neighbor mine count, and each flagged cell actually contains a mine, then all closed, unflagged neighboring cells are opened automatically. However, if even one of these flags was placed on the wrong cell, the game ends in failure.
  6. The player wins the game if he/she opens all cells without mines.

Data Structures

Cell

JavaScript code for a minesweeper cell
JavaScript code representing a minesweeper cell.

Each cell is an object that has several properties:

  • id: A string containing the row and column. This unique identifier makes it easier to find cells quickly when needed. If you pay close attention you will notice that there are some shortcuts I take related to the ids. I can get away with these shortcuts because of the small board size, but these techniques will not scale to larger boards. See if you can spot them. If you do, point them out in the comments!
  • row: An integer representing the horizontal position of the cell within the board.
  • column: An integer representing the vertical position of the cell within the board.
  • opened: This is a boolean property indicating whether the cell has been opened.
  • flagged: Another boolean property indicating whether a flag has been placed on the cell.
  • mined: Yet another boolean property indicating whether the cell has been mined.
  • neighborMineCount: An integer indicating the number of neighboring cells containing a mine.

Board

JavaScript code for the minesweeper board
JavaScript code representing our game board.

Much like in the snake game I made, our board is a collection of cells. We could represent our board data in many different ways. I chose to represent it as an object with key value pairs. As we saw earlier, each cell has an id. The board is just a mapping between these unique keys and their corresponding cells.

After creating the board we have to do two more tasks: randomly assign the mines and calculate the neighboring mine counts. We’ll talk more about these algorithms in the next section.

Algorithms

Randomly Assign Mines

JavaScript code for randomly assigning mines
JavaScript code for randomly assigning mines to cells.

One of the first things we have to do before a game of minesweeper can be played is assign mines to cells. For this, I created a function that takes the board and the desired mine count as parameters.

One of the first things we have to do before a game of minesweeper can be played is assign mines to cells. For this, I created a function that takes the board and the desired mine count as parameters.

For every mine we place, we must generate a random row and column. Furthermore, the same row and column combination should never appear more than once. Otherwise we would end up with less than our desired number of mines. We must repeat the random number generation if a duplicate appears.

As each random cell coordinate is generated we set the mined property to true of the corresponding cell in our board.

I created a helper function in order to help with the task of generating random numbers within our desired range. See below:

JavaScript code for random integer generator.
Helper function for generating random integers.

Calculate Neighbor Mine Count

JavaScript code for calculating the neighboring mine count of each cell.

Now let’s look at what it takes to calculate the neighboring mine count of each cell in our board.

You’ll notice that we start by looping through each row and column on the board, a very common pattern. This will allow us to execute the same code on each of our cells.

We first check if each cell is mined. If it is, there is no need to check the neighboring mine count. After all, if the player clicks on it he/she will lose the game!

If the cell is not mined then we need to see how many mines are surrounding it. The first thing we do is call our getNeighbors helper function, which returns a list of ids of the neighboring cells. Then we loop through this list, add up the number of mines, and update the cell’s neighborMineCount property appropriately.

Won’t you be my neighbor?

Let’s take a closer look at that getNeighbors function, as it will be used several more times throughout the code. I mentioned earlier that some of my design choices won’t scale to larger board sizes. Now would be a good time to try and spot them.

JavaScript code for getting all of the neighboring ids of a minesweeper cell.

The function takes a cell id as a parameter. Then we immediately split it into two pieces so that we have variables for the row and the column. We use the parseInt function, which is built into the JavaScript language, to turn these variables into integers. Now we can perform math operations on them.

Next, we use the row and column to calculate potential ids of each neighboring cell and push them onto a list. Our list should have eight ids in it before cleaning it up to handle special scenarios.

A minesweeper cell and its neighbors.

While this is fine for the general case, there are some special cases we have to worry about. Namely, cells along the borders of our game board. These cells will have less than eight neighbors.

In order to take care of this, we loop through our list of neighbor ids and remove any id that is greater than 2 in length. All invalid neighbors will either be -1 or 10, so this little check solves the problem nicely.

We also have to decrement our index variable whenever we remove an id from our list in order to keep it in sync.

Is it mined?

Okay, we have one last function to talk about in this section: isMined.

JavaScript function that checks if a cell is mined.
JavaScript function that checks if a cell is mined.

The isMined function is pretty simple. It just checks if the cell is mined or not. The function returns a 1 if it is mined, and a 0 if it is not mined. This feature allows us to sum up the function’s return values as we call it repeatedly in the loop.

That wraps up the algorithms for getting our minesweeper game board set up. Let’s move on to the actual game play.

Opening A Cell

JavaScript code that executes when a minesweeper cell is opened.
JavaScript code that executes when a minesweeper cell is opened.

Alright let’s dive right into this bad boy. We execute this function whenever a player clicks on a cell. It does a lot of work, and it also uses something called recursion. If you are unfamiliar with the concept, see the definition below:

Recursion: See recursion.

Ah, computer science jokes. They always go over so well at bars and coffee shops. You really ought to try them out on that cutie you’ve been crushing on.

Anyways, a recursive function is just a function that calls itself. Sounds like a stack overflow waiting to happen, right? That’s why you need a base case that returns a value without making any subsequent recursive calls. Our function will eventually stop calling itself because there will be no more cells that need to be opened.

Recursion is rarely the right choice in a real world project, but it is a useful tool to have in your toolbox. We could have written this code without recursion, but I thought you all might want to see an example of it in action.

Handle Click Explained

The handleClick function takes a cell id as a parameter. We need to handle the case where the player pressed the ctrl button while clicking on the cell, but we will talk about that in a later section.

Assuming the game isn’t over and we are handling a basic left click event, there are a few checks we need to make. We want to ignore the click if the player already opened or flagged the cell. It would be frustrating for the player if an inaccurate click on an already flagged cell ended the game.

If neither of those are true then we will proceed. If a mine is present in the cell we need to initiate the game over logic and display the exploded mine in red. Otherwise, we will open the cell.

If the opened cell has mines surrounding it we will display the neighboring mine count to the player in the appropriate font color. If there are no mines surrounding the cell, then it is time for our recursion to kick in. After setting the background color of the cell to a slightly darker shade of gray, we call handleClick on each unopened neighboring cell without a flag.

Helper Functions

Let’s take a look at the helper functions we are using inside the handleClick function. We’ve already talked about getNeighbors, so we’ll skip that one. Let’s start with the loss function.

JavaScript code that gets called whenever the player has lost at minesweeper.
JavaScript code that gets called whenever the player has lost the game.

When a loss occurs, we set the variable that tracks this and then display a message letting the player know that the game is over. We also loop through each cell and display the mine locations. Then we stop the clock.

Second, we have the getNumberColor function. This function is responsible for giving us the color corresponding to the neighboring mine count.

JavaScript code that gets passed a number and returns a color.
JavaScript code that gets passed a number and returns a color.

I tried to match up the colors just like the classic Windows version of minesweeper does it. Maybe I should have used a switch statement here, but I already took the screen shot, and it’s not really a big deal. Let’s move on to what the code looks like for putting a flag on a cell.

Flagging A Cell

JavaScript code for putting a flag on a minesweeper cell.
JavaScript code for putting a flag on a minesweeper cell.

Right clicking on a cell will place a flag on it. If the player right clicks on an empty cell and we have more mines that need to be flagged we will display the red flag on the cell, update its flagged property to true, and decrement the number of mines remaining. We do the opposite if the cell already had a flag. Finally, we update the GUI to display the number of mines remaining.

Opening Neighboring Cells

JavaScript code for handling ctrl + left click
JavaScript code for handling ctrl + left click

We have covered the actions of opening cells and marking them with flags, so let’s talk about the last action a player can take: opening an already opened cell’s neighboring cells. The handleCtrlClick function contains the logic for this. This player can perform this action by holding ctrl and left clicking on an opened cell that contains neighboring mines.

The first thing we do after checking those conditions is build up a list of the neighboring flagged cells. If the number of flagged cells matches the actual number of surrounding mines then we can proceed. Otherwise, we do nothing and exit the function.

If we were able to proceed, the next thing we do is check if any of the flagged cells did not contain a mine. If this is true, we know that the player predicted the mine locations incorrectly, and clicking on all of the non-flagged, neighboring cells will end in a loss. We will need to set the local lost variable and call the loss function. We talked about the loss function earlier in the article.

If the player did not lose, then we will need to open up the non-flagged neighboring cells. We simply need to loop through them and call the handleClick function on each. However, we must first set the ctrlIsPressed variable to false to prevent falling into the handleCtrlClick function by mistake.

Starting A New Game

We are almost done analyzing all of the JavaScript necessary to build minesweeper! All that we have left to cover are the initialization steps necessary for starting a new game.

JavaScript code for initializing minesweeper
JavaScript code for initializing minesweeper

The first thing we do is initialize a few variables. We need some constants for storing the html codes for the flag and mine icons. We also need some constants for storing the board size, the number of mines, the timer value, and the number of mines remaining.

Additionally, we need a variable for storing if the player is pushing the ctrl button. We utilize jQuery to add the event handlers to the document, and these handlers are responsible for setting the ctrlIsPressed variable.

Finally, we call the newGame function and also bind this function to the new game button.

Helper Functions

JavaScript code for starting a new game of minesweeper.
JavaScript code for starting a new game of minesweeper.

Th newGame function is responsible for resetting our variables so that our game is in a ready-to-play state. This includes resetting the values that are displayed to the player, calling initializeCells, and creating a new random board. It also includes resetting the clock, which gets updated every second.

Let’s wrap things up by looking at initializeCells.

JavaScript code for attaching click handlers to minesweeper cells.
JavaScript code for attaching click handlers to cells and checking for the victory condition.

The main purpose of this function is to add additional properties to our html game cells. Each cell needs the appropriate id added so that we can access it easily from the game logic. Every cell also needs a background image applied for stylistic reasons.

We also need to attach a click handler to every cell so that we can detect left and right clicks.

The function that handles left clicks calls handleClick, passing in the appropriate id. Then it checks to see if every cell without a mine has been opened. If this is true then the player has won the game and we can congratulate him/her appropriately.

The function that handles right clicks calls handleRightClick, passing in the appropriate id. Then it simply returns false. This causes the context menu not to pop up, which is the default behavior of a right click on a web page. You wouldn’t want to do this sort of thing for a standard business CRUD application, but for minesweeper it is appropriate.

Conclusion

Congrats on learning how to build minesweeper with JavaScript! That was a lot of code, but hopefully it makes sense after breaking it up into modules like this. We could definitely make more improvements to this program’s reusability, extensibility, and readability. We also did not cover the HTML or CSS in detail. If you have questions or see ways to improve the code, I’d love to hear from you in the comments!

I hope you guys enjoyed learning about how to build minesweeper with JavaScript. Let me know what other simple games like this you would like to see, and don’t forget to drop me your email so you don’t miss the next one that comes out.

You can also follow me on Twitter if you’d like to keep up with what I’m up to.

Take care, and God bless!

Update (7/13/2019): This post became more popular than I thought it would, which is awesome! I’ve received a lot of great feedback from readers about areas that could be improved. I work daily in a code base that until recently was stuck in Internet Explorer quirks mode. Many of my daily habits there transferred to my work on minesweeper, resulting in some code that doesn’t take advantage of the bleeding edge of JavaScript technology. At some point I would like to do another post where I refactor the code. I plan to remove jQuery entirely and use the ES6 syntax instead of the ES5 syntax where appropriate. But you don’t have to wait for me! See if you can make these changes yourself! And let me know how it goes in the comments.

Update (10/13/2020): I finally got around to making some improvements! Check out part 2 of this project. I removed jQuery entirely and added a feature to prevent immediate losses due to bad luck on the first click. I hope you enjoy it!

I Built Tic Tac Toe With JavaScript

Tic Tac Toe JavaScript Game

In my last post I showed you guys a matching game I built using JavaScript and talked a bit about front-end web technologies. I received some positive feedback, so for this week’s post I decided to build a tic tac toe game using JavaScript and describe its construction in detail. I also took on the additional challenge of not using any external JavaScript libraries in the project. If you haven’t done much programming before, it’s probably best to check out my introductory post on computers first.

Click here to play tic-tac-toe!

There are two difficulty levels: moron and genius. Once you’ve bested the moron, see if you can defeat the tic-tac-toe genius. The genius is more formidable than the moron, but he is a little arrogant and isn’t actually all that bright. As a reader of my blog, I bet you are smart enough to exploit the flaws in his thinking.

How It’s Made

This tic tac toe game is built using the three basic front-end web technologies: HTML, CSS, and JavaScript. I’m going to show you the code for each and describe the role they play in creating the final game. Here are the three files:

tic-tac-toe.html

tic-tac-toe.css

tic-tac-toe.js

HTML

The Header

Let’s start with the head tag, shown below. This tag comes at the start of every HTML document you create. It’s a good place for including elements that affect the page as a whole.

<head>
    <title>Tic Tac Toe</title>
    <link rel="stylesheet" href="tic-tac-toe.css">
    <link rel="shortcut icon" 
          href="https://mitchum.blog/wp-content/uploads/2019/05/favicon.png" />
</head>        

Our head tag has three child tags inside of it: a title tag and two link tags. The tab of our web browser displays the contents of our title tag. In our case this is “Tic Tac Toe”. The second link tag contains a reference to the icon we want displayed in the tab of our web browser. Together, they form a tab that looks like this:

Browser tab for javascript Tic Tac Toe game

The first link tag contains a reference to our tic-tac-toe.css file. This file is what lets us add color and positioning to our HTML document. Our game would look rather dreary without including this file.

Tic Tac Toe game without css applied
Our HTML document without any style.

Next we have the main body of our HTML document. We are going to break it up into two sections: the board and the controls. We’ll start with the board.

The Board

We are using a table tag for representing our tic-tac-toe game board. The code is shown below:

      <table class="board">
        <tr>
          <td>
              <div id="0" class="square left top"></div>
          </td>
          <td>
              <div id="1" class="square top v-middle"></div>
          </td>
          <td>
              <div id="2" class="square right top"></div>
          </td>
        </tr>
        <tr>
          <td>
              <div id="3" class="square left h-middle"></div>
          </td>
          <td>
              <div id="4" class="square v-middle h-middle"></div>
          </td>
          <td>
              <div id="5" class="square right h-middle"></div>
          </td>
        </tr>
        <tr>
          <td>
              <div id="6" class="square left bottom"></div>
          </td>
          <td>
              <div id="7" class="square bottom v-middle"></div>
          </td>
          <td>
              <div id="8" class="square right bottom"></div>
          </td>
        </tr> 
       </table>

We have added the class, “board” to the table in order to add styling to it. The board has three table row tags each containing three table data tags. This results in a 3×3 game board. We have assigned each square of the game board a numerical id and some classes indicating its positioning.

The Controls

What I’m calling the controls section consists of a message box, a few buttons, and drop down list. The code looks like this:

       <br>
       <div id="messageBox">Pick a square!</div>
       <br>
       <div class="controls">
         <button class="button" onclick="resetGame()">Play Again</button> 
         <form action="https://mitchum.blog/sneaky-subscribe" 
               style="display: inline-block;">
            <button class="button" type="submit">Click Me!</button> 
         </form>
         <select id="difficulty">
           <option value="moron" selected >Moron</option>
           <option value="genius">Genius</option>
         </select>
        </div>

The message box is situated between two line breaks. Following the second line break is a div containing the rest of our controls. The play again button has a click handler that calls a JavaScript function in tic-tac-toe.js. The mystery button is wrapped inside of a form tag. Finally, the select tag contains two options: moron and genius. The moron option is selected by default.

Each of these HTML elements has been assigned various classes and ids which will be used for assisting in executing the game logic and for adding styling. Let’s talk about how that styling is applied.

CSS

I’m going to break the explanation of the tic-tac-toe.css file up into several sections because I think that will make it easier to follow as a reader.

Basic Elements

The first section contains styling for the body, main, and h1 tags. The background styling on the body tag simply sets the light blue background color of the page using RGB values.

The max-width, padding, and margin styling on the main tag centers our game on the screen. I borrowed this awesome and succinct styling from this blog post.

The h1 tag is contains the big “Tic Tac Toe” heading, and we add style to center it and give it that yellow coloring.

See below:

CSS styling for the page
The Controls

Next we are going to talk about styling for the message box, difficulty drop down list, and the top-level controls section.

We center the text inside the message box and color it yellow. Then we add a border with rounded corners.

We set the size of our difficulty drop down, and add rounded corners, and then we set its font size, colors, and positioning.

The only change we need to make to the controls div is to make sure that everything is centered.

See below:

 CSS styling for the controls
The Board

Next comes the styling of our game board itself. We need to set the size, color, and text positioning of each square. More importantly, we need to make the borders visible in the appropriate locations. We added several classes for identifying where squares are located on the game board, allowing us to create the famous tic-tac-toe pattern. We also varied the size of the border to get a more three dimensional look and feel.

CSS styling for the tic tac toe board
The Buttons

Finally we come to the buttons. I have to confess, I borrowed these styles from w3schools. However, I did modify them slightly to match our color scheme.

CSS styling for the buttons

Alright, that’s it for the CSS! Now we can finally move onto the fun part: JavaScript.

JavaScript

As should be expected, the JavaScript code is the most complex part of the tic tac toe game. I’m going to describe the basic structure and the artificial intelligence, but I’m not going to describe each and every function. Instead, I’m going to leave it as an exercise for you to read the code and understand how each function was implemented. These other functions have been made bold for your convenience.

If something in the code is confusing then leave a comment and I’ll do my best to explain it! If you can think of a better way to implement something then I would love to hear your feedback in the comments as well. The goal is for everyone to learn more and have fun in the process.

Basic Structure

The first thing we need to do is initialize some variables. We have a couple variables for keeping track of the game’s state: one for keeping track of if the game is over, and one for storing the chosen difficulty level.

We also have a few more variables for storing some useful information: An array of our squares, the number of squares, and the win conditions. Our board is represented by a sequential list of numbers, and there are eight possible win conditions. So the win conditions are represented by an array containing eight arrays, one for each possible three square winning combination.

See below:

initialization javascript variables

With that in mind, let’s talk about how this program works. This game is event-driven. Any action that occurs on-screen happens because you clicked somewhere, and the code responded to it. When you click on the “Play Again” button, the board is cleared and you can play another round of tic tac toe. When you change the difficulty level, the game responds by making different moves in response to yours.

The most important event we have to respond to is when a player clicks on a square. There are lots of things that need to be checked. The bulk of this logic happens inside the top-level function I wrote called chooseSquare.

See below:

Javascript for choosing a tic tac toe square.
The Code Examined

Let’s walk through the code from top to bottom.

Line 176: The first thing we do is set the difficulty variable to whatever was chosen in the drop down list. This is important because our artificial intelligence looks at this variable to determine what move to make.

Line 177: The second thing we do is check if the game is over. If it is not then we can proceed. Otherwise, there is no need to continue.

Lines 179 – 181: Third, we set the message displayed to the player to the default, “Pick a square!” message. We do this by calling the setMessageBox function. Then we set variables for the id and the HTML of the square that was selected by the player.

Line 182: We check if the square is open by calling squareIsOpen. If a marker has already been placed there then the player is trying to make an illegal move. In the corresponding else block, we notify him as such.

Lines 184 -185: Since the square is open, we set the marker to “X”. Then we check to see if we won by calling checkForWinCondition. If we won we are returned an array containing the winning combination. If lost we are simply returned false. This is possible because JavaScript is not type safe.

Line 186: If the player didn’t win then we must continue so that his opponent can make a move. If the player did win, then the corresponding else block will handle it by setting the game over variable to true, turning the winning squares green by calling highlightWinningSquares, and setting the winning message.

Lines 188 – 189: Now that the player’s move is finished we need to make a move for the computer. The function called opponentMove handles this, and it will be discussed later in detail. Then we need to check to see if the player lost by calling the same function we used on line 185, but this time passing in “O” as a parameter. Yay for reusability!

Line 190: If the computer did not win then we must continue so that we can check for a draw. If the computer did win, then the corresponding else block will handle it by setting the game over variable to true, turning the winning squares red by calling highlightWinningSquares, and setting the losing message.

Lines 192 – 197: We check for a draw by calling the checkForDraw function. If there are no win conditions met and there are no more available moves to be made then we must have reached a draw. If a draw has been reached then we set the game over variable to true and set the draw message.

That’s it for the main game logic! The rest of this function is just the corresponding else blocks which we already covered. As I mentioned previously, go read through the other functions to get a fuller understanding of how the game logic works.

Artificial Intelligence

There are two difficulty levels: moron and genius. The moron always takes the first available square in order of id. He will sacrifice a win just to keep up this orderly pattern, and he will not deviate from it even to prevent a loss. He is a simpleton.

The genius is much more sophisticated. He will take a win when its there, and he will try to prevent a loss. Going second puts him at a disadvantage, so he favors the center square for its defensive qualities. However, he does have weaknesses that can be exploited. He’s following a better set of rules, but he isn’t great at adapting to situations on the fly. When he can’t find an obvious move to make he reverts back to the same simple ways of the moron.

See below:

AI top level javascript function
The top level AI function
AI implementation details in javascript
The AI implementation details

Once you understand the algorithm let me know in the comments what changes we could make to turn our wannabe genius into a true one!

Summary

In this post I showed off the Tic Tac Toe game I made using JavaScript. Then we looked at how it was constructed and how the artificial intelligence works. Let me know what you think, and what kind of games you would like to see me make in the future. Keep in mind though, I’m only one guy, so no asking for Call of Duty!

If you want to learn more about how to write good programs in JavaScript, one book that I recommend is JavaScript: The Good Parts, by the legendary Douglas Crockford. The language has been improved dramatically over the years, but it still has some odd properties because of its development history. The book does a great job of helping you navigate around its more questionable design choices. I found it helpful when I was learning the language.

If you decide to purchase it, I would be grateful if you decided to go through the link above. I will get a commission through Amazon’s affiliate program, with no additional cost to you. It helps me keep this site up and running.

Thanks for reading, and I’ll see you next time!

As always, if you are enjoying the ideas I’ve presented or you think I’m crazy and want to tell me why I’m wrong, go ahead and subscribe to stay up to date with all the latest content.

I Built A Simple Matching Game With JavaScript

Heroes And Villains Matching Game

Half a decade ago I built a simple little heroes and villains themed matching game using only the most basic front-end web technologies: HTML, CSS, and JavaScript.

It had been gathering dust for a while. Since I have a blog now, I thought I would share my creation with you guys. The goal of the game is to find the match for each hero and villain using the fewest number of clicks. You probably have played something similar at some point in your life. This little game won’t win any awards, but much like tic tac toe, it’s great for kids and makes for a good introduction to front-end web technology.

Click here to play the matching game!

How It’s Made

For the tech-savvy among you, please forgive me for the code quality. I’ve learned a lot about code readability and maintainability since my early programming days, but I’m not really interested in spending time refactoring this little project.

If you’re not tech-savvy but want to understand how it works, it actually is pretty simple. It consists of only three files: matching.html, matching.css, and matching.js.

You can view the raw CSS and JavaScript files by following the links above. For viewing the raw html file, just right click on the game’s page and then click on “View Page Source”. The HTML file contains the basic structure of the page, while the CSS file controls the colors and spacing of some of the html elements. The JavaScript file is where the heart of the program lies, and is what controls the logic for the matching game. If you want to learn more about programming languages like JavaScript, check out my post about the topic.

Showing how to view the source code of the javascript matching game.
Click View Page Source to see the raw html.

That’s the whole game! For extra fun, try creating these three files in a folder on your own desktop computer.

The html, css, and javascript files for the matching game shown on your own computer
The three files saved on your own computer.

Then you can change the color scheme, fix bugs, add new features, and more. Just open up the html file you modified in your web browser to see your own creation in action. By making just a few tweaks you could end up with a matching game as cool as this one:

Matching game after making modifications