Game Development Reference
In-Depth Information
The code
The two upgrades we added to this second version of the game are simple, yet they
add a lot of value to the game. We added a persistent high score engine, so users can
actually keep track of their latest record, and have a sticky record of past successes.
We also added a pretty nifty feature that takes a snapshot of the game board each
time the player scores, as well as whenever the player ultimately dies out. Once the
player dies, we display all of the snapshots we had collected throughout the game,
allowing the player to save those images, and possibly share it with his or her friends.
Saving the high score
The first thing you probably noticed about the previous version of this game was that
we had a placeholder for a high score, but that number never changed. Now that we
know how to persist data, we can very easily take advantage of this, and persist a
player's high score through various games. In a more realistic scenario, we'd probably
send the high score data to a backend server, where every time the game is served,
we can keep track of the overall high score, and every user playing the game would
know about this global score. However, in our situation, the high score is local to a
browser only, since none of the persistence APIs (local and session storage, as well
as IndexedDB) share data across other browsers, or natively to a remote server.
Since we want the high score to still exist in a player's browser even a month from
now, after the computer has been powered off (along with the browser, of course) mul-
tiple times, storing this high score data on sessionStorage would be silly. We could
store this single number either in IndexedDB or in localStorage. Since we don't care
about any other information associated with this score (such as the date when the
score was achieved, and so on), all we're storing really is just the one number. For
this reason, I think localStorage is a much better choice, because it can all be done
in as few as 5 lines of code. Using IndexedDB would work, but would be like using a
cannon to kill a mosquito:
function setHighScore(newScore, el) {
var element = document.querySelector(el);
// Multiply by 1 to cast the value from a
string to a number
var score = localStorage.getItem("high-score")
Search WWH ::




Custom Search