Game Development Reference
In-Depth Information
* 1;
// Check if there is a numerical score saved
if (score && !isNaN(score)) {
// Check if new score is higher than
current high score
if (newScore > element.textContent * 1) {
localStorage.setItem("high-score",
newScore);
element.textContent = newScore;
} else {
element.textContent = score;
}
} else {
localStorage.setItem("high-score",
newScore);
element.textContent = newScore;
}
}
This function is pretty straight forward. The two values we pass it are the actual score
to set as the new high score (this value will be both saved to localStorage, as well as
displayed to the user), and the HTML element where the value will be shown.
First, we retrieve the existing value saved under the key high-score, and convert it to
a number. We could have used the function parseInt() , but multiplying a string by
a number does the same thing, but with a slightly faster execution.
Next, we check if that value evaluated to something real. In other words, if there was
no high-score value saved in local storage, then the variable score would have been
evaluated to undefined multiplied by one, which is not a number. If there is a value
saved with the key high-score, but that value is not something that can be converted
into a number (such as a string of letters and such), we know that it is not a valid
value. In this case, we set the incoming score as the new high score. This would
work out in the case where the current persisted value is invalid, or not there (which
would be the case the very first time the game loads).
Next, once we have a valid score retried from local storage, we check if the new
value is higher than the old, persisted value. If we have a higher score, we persist
Search WWH ::




Custom Search