Let’s Program A JavaScript Game: Index and Code

JavaScript is a powerful programming language that’s built right into most web browsers. Because of this it’s rapidly become the default way to provide user friendly interactive web experiences. The Internet experience as we know it today wouldn’t exist without good old JS.

But who cares about silly little things like that? The real question is: Can we use it to program games? And thanks to the introduction of HTML5 elements like the “canvas” the answer is now a resounding “YES”.

So come along and join me as we program ourselves a simple JavaScript web game.

Index

Let’s Program A JavaScript Game 1: Browser Games With JavaScript

Let’s Program A JavaScript Game 2: The Canvas Of Dreams

Let’s Program A JavaScript Game 3: Designing “Defrag Cycle”

Let’s Program A JavaScript Game 4: V8 600HP Game Engine

Let’s Program A JavaScript Game 5: Press Start To Play

Let’s Program A JavaScript Game 6: When Worlds Collide

Let’s Program A JavaScript Game 7: When Worlds Collide For Real

Let’s Program A JavaScript Game 8: That Sinking Feeling

Let’s Program A JavaScript Game 9: Look Before You Leap

Let’s Program A JavaScript Game 10: Letting The World Pass By

Let’s Program A JavaScript Game 11: This Post Isn’t About Malware, Honest

Let’s Program A JavaScript Game 12: Making A STATEment

Let’s Program A JavaScript Game 13: Some Much Needed Polish

Let’s Program A JavaScript Game 14: A Winner Is You

Let’s Program A JavaScript Game 15: The Computer Is Out To Get You

Let’s Program A JavaScript Game 16: Do You Believe In Magic?

Let’s Program A JavaScript Game 17: Can You Hear Me Now?

Let’s Program A JavaScript Game 18: Moving Pictures

Let’s Program A Javascript 19: Cross Browser Chaos

Let’s Program A JavaScript Game 20: BONUS STAGE!

Code

You can play a complete demo of the game we’re building here: https://scottcornaby.com/games/debugcycle/defrag-cycle-final.html

To run the game locally so you can examine the code and make changes just download all the html, png and ogg files in this folder: https://scottcornaby.com/games/debugcycle/

Let’s Program A JavaScript Game 20: BONUS STAGE!

We’ve successfully built a full browser game from scratch and learned a lot of useful stuff about game design in general and JavaScript in particular.

Now what?

That really depends on what you hope to accomplish.

If You Want More JavaScript Practice

Defrag Cycle is a simple game that could be made infinitely better by the addition of a few key features. So if you want to make sure you really understood this Let’s Program why not grab one of these projects and implement it all on your own?

  • Add a life system so that players can survive a couple enemy collisions before getting a game over.
  • Add a double jump to help make sure the player can always make it over or under the next enemy. Remember that letting the player jump higher will also require modifying the code that decides what the max possible height and distance between new platforms is.
  • Add in some collectible powerups that temporarily stop the clock, give the player bonus defrag points or makes them immune to enemies for a short time.
  • If you’re feeling really ambitious give the player a laser gun so they can shoot down enemies.

If You Want To Make A Professional Quality Browser Game

Knowing how things work at a very basic level is important, but reinventing the wheel every time you want to program a new game is a real waste of time. It’s much more efficient to use existing game code for your engine. Ideally code that other people have already spent a lot of time debugging and testing for cross browser compatibility.

But where to find an existing JavaScript game engine?

You could always just Google “JavasScript game engine”, which is how I found this handy list.

Most of the engines and editing tools on that list are either free or offer free trials, so just grab a few and start messing around until you find one you like. Most of them also offer tools that let you create events and game behavior with a few button clicks instead of having to write actual JavaScript code, which is a real time saver. Just because we know how to do everything the hard way doesn’t mean we always want to do it that way.

So best of luck and be sure to email me a link to any cool games you create.

Gengo Girls #120: Never Say Goodbye

Gengo Girls #120: Never Say Goodbye

Over the past nine months and 120 strips we’ve covered the core fundamentals of Japanese. And while there’s still a lot to learn I need to take a break for a while so I can focus on some other projects that I’ve been neglecting. So for now it’s up to you to take the basics you’ve learned and chart your own study course until I get back! (Current rough estimate: Sometime in November).

Unless you’re reading this in the future in which case you can just skip straight to strip 121 and pretend nothing happened at all.

Vocabulary

さよなら = goodbye

明日 = あした = tomorrow

Transcript

言語ガールズ #120

Never Say Goodbye

Yellow: Today went by fast. さよなら

Blue: Actually, さよなら is usually save for people you don’t expect to see again for a really long time.

Blue: For a more casual goodbye you can use また明日.

Yellow: “Again tomorrow”?

Blue: It’s short for “We’ll meet again tomorrow”.

Yellow: What if I might not see them tomorrow?

Blue: There’s also the very casual またね for “Until next time”.

Blue: Of course, you may not want to be quite this casual in a business environment.

Blue: For business situations it might be better to use…

Yellow: またね!

Gengo Girls #119: Plot Twist!

Gengo Girls #119: Plot Twist!

If associating stories and pictures with the kanji works for you you might want to take a look at Remembering the Kanji. It won’t teach you how to pronounce the kanji or what words they appear in but if you just want some help remembering the basic meaning of the 2000+ most common kanji and radicals it might be just what you need.

The book starts off with solid example stories and mental images for a few hundred of the most basic kanji. The rest of the book then just gives you the hints and suggestions to need to make up your own personal memory images for the rest.

Transcript

言語ガールズ #119

Plot Twist!

Blue: When memorizing complicated kanji you might want to try making up a little story that ties all of its parts together.

Blue: The story doesn’t have to make sense. It just has to help you remember.

Blue: The kanji for “bomb” or “explosion” includes the kanji for “fire”, “sun”, “well” and a variation of “water”.

Blue: So I think of a “fiery” explosion brighter than the “sun”.

Blue: And then everyone runs to the “well” to get “water”.

Yellow: Let me try: It was a dark and stormy night and someone had just been murdered.

Blue: What does that have to do with the kanji?

Yellow: I’ll get to that part in chapter three.

Gengo Girls #118: Mix And Match

 

Gengo Girls #118: Mix And Match

Sometimes the meaning of a kanji is very closely tied to the parts that make it up. But sometimes it isn’t. So don’t be too surprised when you find a kanji with something like a “sun” radical in it but no actual solar meaning.

Transcript

言語ガールズ #118

Mix And Match

Blue: Most kanji are made up of multiple smaller pieces.

Blue: If you remember the pieces remembering the whole kanji is much easier.

Blue: For instance, the kanji for “forest” is just three “tree” kanji grouped together.

Blue: And the kanji for “sing” is made up of the kanji for “mouth” and “yawn”.

Blue: Easy to think of singing as people opening their mouths like a yawn.

Yellow: Isn’t that amazing? Now order your starter pack of kanji and start combining today!

Blue: Who exactly are you talking to?

Gengo Girls #117: Avalon

Gengo Girls #117: Avalon

Obviously a lot of kanji are based on oriental cultural ideas. Chinese architecture, eastern mythology, rice fields and bamboo, etc…

While this undoubtedly helped the original inventors of the kanji remember what each symbol meant it isn’t nearly as helpful to those of us who grew up in the modern West.

Which is why sometimes it’s best to ignore the real history of a kanji and come up with your own interpretation of what it looks like instead. After all, as long as you accurately remember WHAT the kanji means it doesn’t really matter HOW you remember it.

Transcript

言語ガールズ #117

Avalon

Blue: Some kanji represent abstract ideas instead of physical objects.

Blue: Working with these requires a little more imagination.

Blue: One popular way to remember the kanji for “early” is to think of it as a flower that blooms early in the day to soak up the sun.

Blue: And for this “old” kanji I like to think of an old fashioned church with a giant cross on the roof.

Yellow: Looks more like a sword in a stone to me.

Blue: As long as you remember “old” it doesn’t matter if you imagine an old church or an old sword or something else entirely.

Yellow: EXCALIBUR COME FORTH!

Let’s Program A Javascript 19: Cross Browser Chaos

Forgive me readers for I have sinned.

I wrote this entire series of articles using nothing but Firefox on Linux to test my code. Only now that we’ve reached the end of the project do I notice that when you try to open it with anything else it crashes.

I should have prevented this by testing every code update on multiple browsers like a good software developer, but late is better than never so let’s get this working in all browsers.

fastSeek Was A Bad Idea

You hopefully remember that we use the Audio class function fastSeek to rewind our background music and sound effects. Game over? Reset the music with fastSeek(0). Did the player stop grazing enemies? Reset the grazing sound effect with fastSeek(0).

But it turns out Firefox is the only browser that actually supports fastSeek. Every other browser will throw an error if you try to use it. So if you open Defrag Cycle in Chrome the whole game will freeze up the first time a sound effect has to reset itself because you either died or stopped grazing.

What other browsers prefer is for you to directly manipulate the currentTime variable inside of each audio object.

So instead of :

bgMusic.fastSeek(0);

We need to do:

bgMusic.currentTime=0;

This also works in Firefox, so just replace all the fastSeek instances in your code with currentTime and you are now cross browser ready.

Sound Format Headaches

Try to open this Defrag Cycle in Internet Explorer and the game won’t even load.

This is because IE doesn’t support the Ogg audio standard and throws an error when you try to ask it to load a .ogg file.

After a bit more research it looks like the only file format that actually has universal browser support is mp3.

So easy fix, right? Just convert our two sound files to MP3.

WRONG!

It turns out there’s a whole bunch of really weird legal issues relating to using MP3. Basically if you make a game with MP3s that more than 5,000 people access you now technically owe $2,500 to the company that owns the patent on MP3 technology. You can read more about that here.

Now as hobby developers we probably don’t want to mess with the legal issues and cost of MP3.

Instead we’re going to stick with Ogg and modify our code to only try to load and play sound files when the user’s browser supports them.

Different Code For Different Browsers

This sound file problem, while frustrating, actually gives us a good opportunity to play with an important JavaScript feature: detecting the what the user’s browser can and can’t do and then running browser specific code.

This is an important technique in non-game related web development too. Not only do different browsers support different audio formats, they support different JavaScript functions and sometimes have conflicting support for things like CSS styling rules. So a lot of professional code starts by figuring out what browser the user has and then making slight changes to the page to make sure everything stays compatible.

For our needs we can rely on the canPlayType function of the Audio class. Give the function the name of an audio standard and it will return whether or not the browser can actually play it.

We can use this to improve our code to only load and play our .ogg files in browsers than support them, like so:

function loadGrazeSFX(){
   grazeSFX = new Audio();
   if(grazeSFX.canPlayType('audio/ogg')){
      grazeSFX.oncanplaythrough = function(){ grazeSFX.oncanplaythrough=0; loadBackgroundMusic();};
      grazeSFX.src = 'wubwub.ogg';
      grazeSFX.loop=true;
   }
   else{
      loadBackgroundMusic();
   }
}
function loadBackgroundMusic(){
   bgMusic = new Audio();
   if(bgMusic.canPlayType('audio/ogg')){
      bgMusic.oncanplaythrough = function(){bgMusic.oncanplaythrough=0;gameLoop();};
      bgMusic.src = 'Ouroboros.ogg';
      bgMusic.loop=true;
   }
   else{
      gameLoop();
   }
}

Pretty simple, right? If the browser supprots Ogg audio we set up the code to load like usual. If it doesn’t we just skip straight to the next function in our loading chain.

We also need similar logic when we try to actually play our music so we don’t accidentally try to reset an audio file that was never actually loaded. So anywhere the code looks like this:

bgMusic.pause();
bgMusic.currentTime=0;
grazeSFX.pause();
grazeSFX.currentTime=0;

We need to expand it to look like this:

if(bgMusic.canPlayType('audio/ogg')){
   bgMusic.pause();
   bgMusic.currentTime=0;
}
if(grazeSFX.canPlayType('audio/ogg')){
   grazeSFX.pause();
   grazeSFX.currentTime=0;
}

Now we only play and load music on browsers that can play and load music. We’re cross browser compatible again!

We Could Have Done That Better

I will be the first to admit that this isn’t particularly elegant code. Nor is it particularly good behavior to just completely drop our music and sound effects on a major browser like IE.

Now this is just a demo project so I’m not too torn up about the code being less than perfect. But if this was a serious project for a paying customer we’d want to be a little bit smarter.

So what could we have done instead?

Well, probably the smartest thing to do (that doesn’t involve buying a MP3 license) is to include multiple versions of each audio file on your server. For instance, IE may not play Ogg but it apparently will play MP4 and WAV.

Then when loading music you use canPlay to decide which file version to load. Ogg for Firefox and Chrome. WAV for IE. Things like that.

This also cleans up the code that plays the audio. Since you know the audio objects will get a file one way or the other you don’t have to worry about wrapping them up in tons of ugly if statements.

Now We’re Really Done… Please?

Looks like Defrag Cycle is running in all my browsers, so time to get back on track and wrap up this Let’s Program with a final post about where we can go from here.

Gengo Girls #116: Everyone’s A Critic

Gengo Girls #116: Everyone's A Critic

If you look at the history of the kanji most of them started out looking a lot like drawings of real world things. But then over time details were removed and curves were replaced with straight lines until we finally wound up with the angular kanji we have today. For instance, the “sun” kanji used to be an actual circle instead of the rectangular 日 we have today.

Overall this was probably a good thing. Jotting down a handful of predictable straight lines is a lot faster and easier than having to actually draw a little picture. Especially for those of us that can’t even manage to draw a half-decent circle…

Transcript

言語ガールズ #116

Everyone’s A Critic

Blue: With practice you can recognize kanji as quickly and easily as you do English words.

Blue: But until then there are a few tricks to help you remember them.

Blue: Many kanji were designed to look like the word they represent.

Blue: And it’s easy to see the tree kanji as a trunk with branches.

Yellow: That tree kanji kind of just looks like a bad stick figure.

Blue: The kanji represent thousands of years of culture and are beautiful in their simple minimalism.

Yellow: If I had a thousand years I bet I could draw a better tree than that.

Gengo Girls #115: We’re Number One

Gengo Girls #115: We're Number One

Sometimes it makes a lot of sense when a word has double meaning. “Hayai” as both early and fast is easy to remember since they are related concepts.

On the other hand some aren’t so obvious. Why is “takai” both tall and expensive? No clue. But hopefully the thought of an expensive and tall mountain will help you remember.

Vocabulary

一番 = いちばん = first

二番 = にばん = second

三番 = さんばん = third

高い = たかい = tall, high

= やま = mountain

Transcript

言語ガールズ #115

We’re Number One

Blue: Adding (ばん) to the end of a number let’s you create words like “first”, “second”, “third” and so on.

Yellow: 一番, 二番, 三番

Blue: 一番 can also mean “the best” or “the most”.

Blue: You could say that Mt. Everest is the 一番高い山

Yellow: I thought 高い meant expensive?

Blue: It can also mean tall.

Yellow: I wonder what the 一番 expensive mountain is?

Blue: You mean the most expensive to visit?

Yellow: I mean the most expensive to buy and use as a doom fortress.

 

Gengo Girls #114: Incredibly Incredible

Gengo Girls #114: Incredibly Incredible

“Sugoi” has a kanji form but it doesn’t seem to get used nearly as often as just writing the word out in hiragana.

Vocabulary

すごい = amazing

静か = しずか = quiet

= もの = thing

Transcript

言語ガールズ #114

Incredibly Incredible

Blue: Adverbs can also be used to describe adjectives and other adverbs.

Yellow: The incredibly quick fox.

Blue: A useful adverb for describing adjectives is “すごく”. It means “very”, “extremely” or “incredibly”.

Blue: But try not to overuse it in business situations.

Blue: Here’s an example: 図書館はすごく静かです

Yellow: The library is very quiet?

Blue: That’s right. Now it’s your turn.

Yellow: すごく すごい物 は すごいです.

Blue: You could try adding a little variety to your sentence.

Yellow: We’re studying grammar, not vocab.