Learn JavaScript By Building A Game (Part 1)

January 11, 2019 Posted by Programming 0 thoughts on “Learn JavaScript By Building A Game (Part 1)”

The best way to learn a language is to speak it. If you’ve ever had a friend learning French for the first time, they’ve probably peppered you with a bevy of phrases in French. The same goes for medical students learning the language of medicine. Jargon is its own language. To learn it, you have to speak it. 

Programming languages like JavaScript are special in that they help you communicate with your computer. The computer understands you through a third party called a compiler. So if JavaScript is a form of language, how do we speak it? We write it.

Of course, you may say. Okay, but how do we apply it?

We build stuff; the best way to learn JavaScript is to build cool things.

The Build: Whack-a-Mole With a twist

Today we’re going to be making a twist on the famous Whack-a-Mole game. Since this lesson is really going to set you on a road trip through some of JavaScript’s quirks, I will provide the HTML and CSS below if you want to code along.

Grab the HTML code here

Grab the CSS here

This is what the HTML and CSS gives us:

Keep in mind that we’ll be making a very minimal version of this game.

Setting up jQuery

What we now have is a static game board. Nothing works. With this example alone, you can see that JavaScript is responsible for a ton of the interactivity you see on websites (although, CSS does play its part here and there). 

In order to make our HTML elements “do things,” we’re going to have to write some JavaScript. There are two ways of doing this. 1) We can use plain JavaScript and traverse the DOM(Document Object Model) 2) Or we can use jQuery, which does the same as option 1 but in a more user-friendly way.

If you’re unsure what “traversing the DOM” means, think of a marionette show. The puppeteer(JavaScript) moves his puppet(HTML). But he doesn’t use magic to make it do things. He uses strings that are attached to the puppet’s limbs. 

We can divide the puppet up like so:

Body (parent of Head, Arm, Leg)
Head
eyes (child of head)
mouth (child of head)
  Right Arm
hand(parent of fingers & child of right arm)
fingers(child of hand)
Right Leg
foot(child of right leg)

 Say we were building our own marionette and we wanted to attach a string to its right foot. We would pick up our string, find the body, move down from the head to the right leg(aha!), and, finally, we would attach the string to the right foot. That’s DOM traversal marionette-style.

When you write up your HTML, it’s important to keep in mind the relationships of your elements, because in order to move a certain element, we need to know where it is first. That’s where jQuery comes in.

jQuery is a JavaScript library that helps us “query” (i.e. find) an element in the DOM so that we can make it do things with JavaScript. Before we can start using this library, we have to link it to our HTML file.

 Stick the Google CDN(Content Distribution Network) into your <head> tag and make sure that it’s placed above all other script tags:

<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

Now, we can begin coding by writing our first line of jQuery:

$(document).ready(function(){
  //all our code goes in here
});

In English, the above line of code reads, “jQuery, find my entire HTML document. When, it’s fully loaded, execute all of my code.”

The funny symbol $( ) is called a query selector. The dollar sign can be replaced with jQuery

document and the ready() function are built into jQuery, meaning that you can traverse your way to the jQuery docs to find all of its available methods. That’s basically what a library is. A library of functions. Get it? No? Okay moving on…

Callback functions

Now’s the perfect time to tackle callback functions. We’re only going to explore one facet of callback functions to make things simple. Though, callbacks aren’t as advanced as some would have you believe. You can certainly do cool things with them, so if advanced means cool, then,yes, callbacks are advanced.

Here’s why: 

See that ready() function? Well we’ve stuffed another function in the parameter. That means that ready() expects a function and once it receives it, it will execute it depending on certain conditions. That’s a callback function.

We’re almost at the cool part.

Normal functions are automatically executed, and then they’re discarded. 

Callback functions, like packages, can be saved and “opened” whenever we’re ready to open them. It’s because of callbacks that we can wait for the DOM to fully load before we query elements.

Still not sure about callbacks? 

That’s okay. Their power will make itself known the more you code. It also helps that they’re present almost everywhere you turn.

Let’s start jQuery-ing

Now that we have our marionette analogy down, let’s attach a string to one of our HTML elements. In other words, let’s query an element.

jQuery(and vanilla JS as well admittedly) makes querying easy because all we have to do is find class or id we’ve assigned to an element and plug it into the jQuery selector.

We’ll start by querying one of the moles. The selector is called .frmp-hd . You can go ahead and make your class/id selectors infinitely more readable than mine, if you want. 

$(.frmp-hd).

You know what? Let’s list all of the elements we’re going to need and use console.log() each one of them. 

console.log($(“.score”));
console.log($(“.sandbox”));

console.log() prints data to the console. You can access your web browser’s console with Right Click -> Inspect or CTRL+SHIFT+I. You may have to tab over to the console. 

Once you’re at the console, you will see the jQuery.fn.init object with a drop down arrow to the left. Click the arrow and you’ll find your element. The arrow next to your element will list all the methods you can call on said element. 

This information is gold. Not only do we know everything about our element from its position to its specific styling, we can access those properties simply by using the key names provided to us by the DOM API. By the way, that’s where the Object in Document Object Model comes into play. Our HTML has been modeled in the form of an object that we can access with JavaScript.

So, $(“sandbox”)[0].className yields “sandbox”

Why the [0]

The bracket([])notation is another way to access an object’s value. Unfortunately, 0 is the key name given to our <div> element. The dot( . )notation isn’t friendly with numbers so we have to use the bracket notation instead.

Variable Initialization

Are you tired of that jQuery selector yet? Dollar sign, parenthesis, quotations, periods, hashtags — man that’s annoying to type out. Instead of reusing the notation, stick your query selector into a variable.

This is good:

let sandbox = $(“.sandbox”);

This is better: 

let $sandbox = $(“.sandbox”)[0]; 

You can now access your element’s methods without adding the ugly 0. The dollar variable is simply a convention to remind yourself and others that the variable is a special DOM variable.

Game Plan

Okay, breathe. I know we’ve covered quite a lot. Feel free to play around by testing your querying skills. Querying elements will become intuitive so keep practicing. 

Now that we know a bit about accessing the DOM, we can start thinking about how we can make our creative Whack-a-Mole game. Whenever we want to build something, it’s always best to plan. Ideally, the planning should occur before any code is written, but for the purpose of this article we’ll start planning now that we’ve gotten our feet wet.

  1. The mole has to appear and disappear
  2. The appearance of a mole has to occur at random
  3. When we hit the mole, we should get points

Time to Solve Some Problems

To solve our first problem, we know we need to animate the elements somehow. JavaScript has a ton of animation libraries. Let’s choose animejs. We’ll deal with the library later. For now, you can plug the source into the head of your HTML.

To solve our second problem, we may be able to take advantage of JavaScript’s built in Math.random() function. We can then randomly select elements to animate. 

But now we’ve encountered a hidden problem! We will need to trigger a new animation every time, otherwise our animation function will execute automatically and die. The animation should be packaged and ready to go when we want it to go. Sounds like the job of a callback, right?

Well, there’s a built-in function called setInterval(callback, 1000) that takes a callback function and executes it after a specified period of time. Rinse and repeat. It’s not the prettiest solution but it will work for our simple game.

Finally, we need to trigger an event when someone clicks on our “mole” so that we can add points to our score board.

Hmm…let’s step back a bit because we’re getting into the meat of JavaScript.

Event Driven Programming

Click send on your favorite messaging platform — you’ve just triggered an event. Every form of interaction can be considered an event. You can trigger an event by scrolling or by doing nothing for too long. Sometimes events are beyond your control. Other times, they’re entirely predictable. Generally, there’s a flow to these events. The user swipes his mouse over the menu button(trigger), triggers an event(likely a smooth animation) by clicking it, and the menu pops up. The event has been handled, thereby ending the event loop.

That loop is exactly what we’re looking for in our whack-a-mole game. In order to “catch” the event of a click, we need to have someone listening for it. That someone is an event listener. Event listeners wait for a specific event to occur before executing any code(event handler). And, as you may be thinking, that code lying in wait is our dear old callback function. 

jQuery provides us with a bevy of event listeners. Here’s a list of them: https://api.jquery.com/category/events/

For our game, we need to listen for a click. It may be tempting to choose .click() from the library, but you’re actually better off choosing .on(). The main difference between the two is flexibility you get by writing .on(“click”, fn) vs .click(fn) . This stack overflow answer does a great job of fully addressing the benefits of .on().

Let’s Create an Event

So if we want to change the score when someone clicks on a mole, we write:

$frump.on("click", function() {
$score = Number($score) + 10;
$newScore.innerHTML = $score + "";
});

What I did was convert our string into a number, add 10 and assign the new number to the $score variable. The new score is then forced into a string again, giving us points.

Conclusion

So far, we’ve learned how to target certain elements within our HTML in order to listen for events. But these events won’t mean anything if we can’t get a mole to appear. In the next lesson, we will put everything together by animating our moles so that a player will have the ability to trigger our event.

Please follow and like us:
0
Tags: