HTML5 High Scores Board for WinRT and Desktop Ultrabook apps

One neat thing about HTML5 is the ability to store data locally, and a common use for that is creating a high score board for your game.  The following is how I recently deployed this.  This code is working in my WinRT app however it could be done in a pure HTML5 app running for PC desktop by simply swapping out the file read and write portions.  I broke down the process into 5 steps

  • Initializing and reading the high scores from file
  • Checking the rank of your score
  • Repositioning lower ranked scores
  • Diplaying the high scores
  • Saving the scores to file
Initialize High Scores:
The first thing we need to do is create a default high scores board and scores array.  This way the first time the game is played or if the scores file is moved or deleted we will have default scores to work with.  
This code creates sample high scores from 10,000 to 1,000; where Score(0) is the highest score where Score (9) is the 10th and lowest score 
function createLeaderboard() {
    // create array of sample scores
    for (var i = 0; i < highScores; i++) {
        readScore.push([10000 - (i * 1000)]);
    }
Next we need stringify the array to a variable, so you can save it to a text file. This is done using JSON,stringify
   
var ScoresSerialized = JSON.stringify(readScore);
From here we'll want to save the string to the High Scores file, if the File does not exist.  (This is WinRT specific, however HTML5 localstorage equivilant is available)
    var applicationData = Windows.Storage.ApplicationData.current;
    var localFolder = applicationData.localFolder;
    localFolder.createFileAsync("myScores.txt",
    Windows.Storage.CreationCollisionOption.failIfExists)
    .then(function (sampleFile) {
        return Windows.Storage.FileIO.writeTextAsync(sampleFile,
        ScoresSerialized);
    });
Finally read value from High Scores file and parse into Scores Array with JSON.parse
 
   localFolder.getFileAsync("myScores.txt")
     .then(function (sampleFile) {
         return Windows.Storage.FileIO.readTextAsync(sampleFile);
     }).done(function (gotscores) {
             var fscores = JSON.parse(gotscores);
         readScore = fscores;
     }, function () {
     });
}
You can test this by finding the myScores.txt file after running this code,  You will see a string of numbers from 10,000 down to 1000.  If you delete the file it will be recreated.  

Did we Make the Leader Board?: 
Once we've get to the End Game screen we'll wan to see if we made the score board.  This bit of code will run through the Array of scores that we read from the high score file, Score(0) is the highest score where Score (9) is the 10th and lowest score.  If first checks if a newRank is not yet set and if score is greater than the score its checking.  If we meet the criteria we now have a newRank
 for (var i = 0; i < highScores; i++) {
        if (newRank < 0 && score > readScore[i]) {
            newRank = i;
For example if Is Score(0) <  Score, or Score(1) < Score, or Score(2) < Score and so on,  then we know (i) is the new ranking for our score

Repositioning Lower Score
If the situation is oir our score beat the existing 7th value, its value must move to Score 8 and so on
This code will run through the lowest scores starting with Scores 9 and up to the place where we have a new score.
       
for (var j = highScores - 1; j > newRank; j--) {
This effectively swap values saying, Score 9 now equals Score 8, Score 8 equals Score 7
                
k = j - 1;
                readScore[j] = readScore[k];
And with the lower scores moved down we now set our score to the proper value in our Array 
            
readScore[newRank] = score

Display out the Results
In Canvas we can now display each score the array as a new line.  However when I get to the newly added score (newRank) I change that text so it stands out
    
for (var i = 0; i < highScores; i++) {
        if (i == newRank) {
            context.fillStyle = "red";
            context.shadowOffsetX = 0;
            context.shadowOffsetY = 0;
            context.shadowBlur = 5;
            context.shadowColor = "white";
        }
This part displays the next ranking and moves down 15 pixels from the last entry
        
else {
            context.fillStyle = "yellow";
        }
        context.fillText("#" + (i + 1) + ": ", 400, 290 + (i * 15));
        context.fillText(readScore[i], 580, 290 + (i * 15));
        context.closePath();
    }
    context.closePath();

Save The Array to the File 
Now we can save the Array to File just as done before with the sample set of scores
As before we Stringify the array
function saveLeaderboard() {
    var ScoresSerialized = JSON.stringify(readScore);
Write the string to our high scores file but this time replace existing file 
    
    var applicationData = Windows.Storage.ApplicationData.current;
    var localFolder = applicationData.localFolder;
    localFolder.createFileAsync("myScores.txt",
    Windows.Storage.CreationCollisionOption.replaceExisting)
    .then(function (sampleFile) {
        return Windows.Storage.FileIO.writeTextAsync(sampleFile,
        ScoresSerialized);
    });
}
And there you have a high scores board that will continue to add scores as players best previous sccres.  You may want to try and extend the scores array to include level completed, date, user name.
如需更全面地了解编译器优化,请参阅优化注意事项