Game Development Reference
In-Depth Information
return JSON.parse(eventObj);
}
Each time the player eats a fruit, we call this function, passing it a reference to the
snake
(our hero in this game), and the
fruit
(the goal of this game) objects. What
we do is really quite simple: we create an array representing the state of the snake
and of the fruit at each event that we capture. Each element in this array is a string
representing the serialized array that keeps track of where the fruit was, and where
each body part of the snake was located as well.
First, we check if this object currently exists in
sessionStorage
. For the first time
we start the game, this object will not yet exist. Thus, we create an object that refer-
ences those two objects, namely the
snake
and the
fruit
object. Next, we stringify
the buffers keeping track of the locations of the elements we want to track. Each time
we add a new event, we simply append to those two buffers.
Of course, if the user closes down the browser, that data will be erased by the
browser itself, since that's how
sessionStorage
works. However, we probably
don't want to hold on to data from a previous game, so we also need a way to clear
out our own data after each game.
function clearEvent(event) {
return sessionStorage.removeItem(event);
}
Easy enough. All we need is to know the name of the key that we use to hold each
element. For our purposes, we simply call the snapshots of the snake eating
"eat"
,
and the buffer with the snapshot of the snake dying
"die"
. So before each game
starts, we can simply call
clearEvent()
with those two global key values, and the
cache will be cleared a new each time.
Next, as each event takes place, we simply call the first function we defined, sending
it the appropriate data as shown in the following code snippet:
if (fruit.isAt(head.x, head.y)) {
// Save current game state