17 - Storage
It would be nice to save a high score between plays! Replay provides a simple way to save things to local storage on the device.
In our top-level Game
Sprite we add a highScore
state field. In init
we want to set this value to be what's saved in local storage. device.storage.getItem(key)
returns a Promise containing the string value we saved under the key "highScore"
. When the Promise returns we update our high score field. If there's no highScore
value saved from a previous game, then we set a default of 0
.
In the gameOver
callback we'll have the Level
Sprite pass in the current score. If it's higher than our highScore
state value, we replace the value in the Game
Sprite's state and the store. Calling device.storage.setItem(key, value)
will save the value on the device under the key passed in.
In the Level
Sprite we need to pass the score into the gameOver
callback.
In the Menu
Sprite we read the Game
Sprite's highScore
value through a prop and display it. In order to have the high score text stand out a bit, we explicitly set the font name and size through the font
prop.
- JavaScript
- TypeScript