如何将玩家得分发送到本地存储?

时间:2017-12-15 01:18:28

标签: javascript html storage local ranking

我想添加玩家在玩游戏时获得的分数到html本地存储? 我该怎么做呢? 此外,如果对任何人来说都不会太麻烦,我怎样才能从本地存储中检索得分并将其放在排名表中? 大多数代码都存在,只有一些我无法理解的东西

https://jsfiddle.net/gugui3z24/ab4gaf15/2/

    /* This function is called when a logged in user 
        plays the game and gets a score */
    function updateScore(newScore) {
        //Get the JavaScript object that holds the data for the logged in user
        var usrObj = JSON.parse(localStorage[localStorage.loggedInUser]);

        //Update the user object with the new top score
        /* NOTE YOU NEED TO CHANGE THIS CODE TO CHECK TO SEE IF THE NEW SCORE
            IS GREATER THAN THE OLD SCORE */
        usrObj.topscore = newScore;

        //Put the user data back into local storage.
        localStorage[localStorage.loggedInUser] = JSON.stringify(usrObj);
    }


    /* Loads the rankings table.
        This function should be called when the page containing the rankings table loads */
    function showRankingsTable() {
        //Get a reference to the div that will hold the rankings table.
        var rankingDiv = document.getElementById("RankingsTable");

        //Create a variable that will hold the HTML for the rankings table
        var htmlStr = "";

        //Add a heading 
        htmlStr += "<h1>Rankings Table</h1>";

        //Add the table tag
        htmlStr += "<table>";

        //Work through all of the keys in local storage
        for (var key in localStorage) {
            //All of the keys should point to user data except loggedInUser
            if (key !== "loggedInUser") {
                //Extract object containing user data

                //Extract user name and top score
                htmlStr += "David";
                //Add a table row to the HTML string.
            }
        }

        //Finish off the table
        htmlStr += "</table>";

1 个答案:

答案 0 :(得分:0)

首先,当我看到你写的游戏时,我印象非常深刻。它看起来很整洁!

我首先阅读LocalStorage API docs,以了解LocalStorage的工作原理。然后我建议您查看一个可以方便使用Local storage.js等LocalStorage API的库。

使用storage.js,负责检索用户分数的代码将是(例如):

// Set user score
storage.set('score', 52.0);
// Retrieve user score
var storoage.get('score');
相关问题