Breakout-6 introduces the ability to add and view high scores. For our storage mechanism, since we’re in the browser, we can use local storage. Local storage is a simple way to store small key/value pairs (kind of like cookies) for a particular domain on your browser. Read more about local storage here.
Important Functions
localStorage.getItem(key)- Gets a key/value pair from the browser’s local storage by the key.
localStorage.setItem(key, value)- Sets a key/value pair to the browser’s local storage with the provided key and value.
JSON.parse(string)- Takes a string containing valid JSON and converts it to a JavaScript object.
JSON.stringify(object)- Takes a JavaScript object and converts it to a string containing valid JSON.
Important Code
- In
HighScoreManager.js, we have two new functions:loadHighScores(): Loads existing high scores from the browser’s local storage.- If the key doesn’t exist, we create it and fill it with 10 placeholder names and scores.
addHighScore(): Adds a new high score to the browser’s local storage.
- These functions are used by
HighScoreState,GameOverState, andEnterHighScoreState, so have a look at those three files and make sure you understand how the high scores are being handled. - In
EnterHighScoreState.js, we allow users to enter their high scores by choosing a 3-character name. The name is selected by toggling the 3 characters using thew,a,s,dkeys. We use ASCII values to implement this behavior.- Once the user settles on a name, we write their score to local storage using
HighScoreManager, taking care to only store the top 10 scores.
- Once the user settles on a name, we write their score to local storage using
Files
Preparing Environment