previousnext

In addition to the ball, there is another object: the game itself. We have many parameters, such as the height and width of the canvas for instance, that are specific to the game and which are declared as global variables. By creating a Game class, we can remove these variables from the global namespace, keeping only two such names: game and ball.

When looking at the above code, you might wonder where the class definition for Ball went ... It has been put in a library available as a separate tab in our editor. This enables us to focus on the changes we made without having to deal with the clutter of extra code which we know is working.

Experiment!

You can change the code in the main (code) tab and also the code in the lib tab and see the effect of any changes you make when you run the code. As before, the code in the pre tab is there just for reference and has no effect on the running code.

In the future, the code included in the pre tab, when present, will only be a relevant subset of the full code for the program.

Notes

Instead of hard-coding explicit values for the canvas height and width, we use jQuery to get the values for us. This would enable us, if we so chose, to use the code as is with different size canvases.

We used the name init(), following the usual convention, to denote what has to be done once to initialize the game. Similarly, we indicated that we have a game loop, as it is commonly known, by naming such a method explicitly.

previousnext