You can download this week’s version of the game here: https://fvi.edu/wp-content/uploads/2016/10/asteroids.zip
If that all sounds difficult or complicated to you, don’t worry about it. Just double-click on the “index.html” file, and you’ll be able to play this simple video game in your browser!
Let’s take a look at the code inside of playWithCode.js, and see what’s going on.
First, let’s take a big picture view.
Three main sections.
There seem to be three main sections in the code, indicated by
Comments are notes that make it easier for developers to read the code. They are ignored by the browser. They are written for coders, by coders.
The first section is indicated on line 3 of the playWithCode.js, with the comment:
// GENERATE ASTEROIDS IN HTML DOCUMENT
Line 22 indicates the start of the second section:
// MOVEMENT CONTROLS FOR SHIP
The third section doesn’t have a comment to tell you where to look, or what it does. Can you spot where the third section starts in the code? Hint: It’s a very large function that spans nearly 100 lines of code.
Did you find it? The third section, the “game loop” function, starts on line 89 and goes to the end of the document.
What do these sections do?
These basic functions of these three sections are relatively self explanatory.
The first section generates asteroids on the webpage.
Section #2 defines how the movement controls will work for the space ship.
Now, by breaking it down into smaller and smaller sections, you can understand how this program works, and actually be able to tinker with it yourself. For example, you might see something unfamiliar to you, like the
Go ahead and tinker with the code, try to improve the game, and tweak it to your own specifications. We left a few “bugs” in there for you, in case you want to try to figure out how to fix them (notice the lagginess, for example, especially near the end of the game, and after it’s over). Let us know if you have a question, find a bug, or added a new feature to the game! firstname.lastname@example.org