First of all, it defines a constant named
MAX_LIVES
that contains the maximum
number of lives in the game. This is the place to go for cheaters. The
GameStates
map defines the game’s possible states. This is a very common pattern in
game programming, and you’ll see later how easy it is to write the game’s
main loop when you identify the game states properly.
The
Game
object defines all of the game’s properties, such as the current score,
the number of lives left, and the game’s current state. It also contains all
information about the game’s object, such as the ball’s current velocity in all
directions or the paddle’s speed. Of course, it also defines a
GameController
object, and you have to adjust the path to the Arduino’s serial port.
Most of the
Game
objects are constants at the beginning; we set only the ball’s
velocity in the X direction to a random value. This way, the ball won’t always
go into the same direction each time you start a new round.
Note that we use jQuery functions for the first time when we determine the
width and height of the game objects. Look at the following piece of code:
width: $("#paddle").width()
It looks cryptic at first, but it should be obvious that it somehow determines
the paddle’s width. Therefore, it uses jQuery’s most important method. Its
name is
$
(yes, you can actually define a JavaScript function named
$
), and
it’s a versatile method you can use for various purposes.
The
$
function expects a single argument you can use to specify a certain
element in your current HTML page. To identify the element, you can use the
usual CSS selectors. In our case, we’d like to get the element with the ID
paddle
, and in CSS you can look up elements specified by an ID by inserting
the
#
character before the ID.
After we’ve retrieved the element we’re looking for, we use jQuery’s
width
method
to read its width. jQuery offers many more methods for accessing all possible
CSS attributes. Using these methods for getting and setting CSS attributes
is much easier than using JavaScript’s native functions for looking up and
manipulating elements on the current HTML page.
Now that we’ve set up the game’s data structures, we can implement the
game’s main logic. We start by defining a few methods for initializing and
resetting the game.
BrowserGame/Arduinoid/js/arduinoid.js
function initGame() {
Line 1
Game.state = GameStates.PAUSED;
-
Game.lives = MAX_LIVES;
-
report erratum • discuss
Creating the Game • 117
www.it-ebooks.info