【问题标题】:How to Create a Global High Score With Phaser?如何使用 Phaser 创建全球高分?
【发布时间】:2018-03-03 05:48:19
【问题描述】:

我一直在使用phaser JavaScript 框架制作可以放入 HTML 的游戏,但我似乎不知道如何制作高分系统。

我只能找到this one 之类的解决方案,但它似乎将高分值存储在客户端系统本地,因此他们只能看到自己的高分。如果可能的话,我希望能够获得具有最高级别和名称的全球高分。

我知道我很可能必须创建一个 SQL 数据库来存储所有这些内容并使用 node.js 在游戏和数据库之间移动它(我对 SQL 和 node.js 的了解非常有限)但我不知道不知道具体应该如何与Phaser联系起来。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript sql node.js phaser-framework


    【解决方案1】:

    由于您不了解 SQL(而且您也不会保存那么多数据),因此您可以使用 JSON 文件。此答案假设您有一台服务器(如果您打算使用 Node.js,则需要一台)。另外,我假设您想创建一个old-school high score table,带有分数和名称。

    这旨在作为一般指导。您需要了解如何使用您选择的语言执行我所解释的操作。

    在您的服务器中,您将有一个文件(例如 score.json),如下所示:

    {
        "data": [
            {
                "name": "Destroyer",
                "score": 23
            },
            {
                "name": "yo momma",
                "score": 5
            },
            {
                "name": "Joe",
                "score": 1
            },
            // And so on...
        ]
    }
    

    此外,在您的服务器中,您还需要在特定端口上进行侦听(您可以使用 Node.js、PHP、Ruby、Python 等),您将在该端口上发出请求。这个脚本将做的是(在 JavaScript 中):

    handleRequest(request) {
    
        // Fetch your file and populate the array
        var scoresTable = ...
    
        // On request, decide which type of request it is
        if (request.type === "getHighScoresTable") {
    
            // If it wants the scores, return the json as a string
            return scoresJson;
    
        } else if (request.type === "submitScore"
                && request.score > scoresTable[scoresTable.length - 1].score) {
    
            // Otherwise, check if the submitted score makes it into the table. 
            // If it does, search its position and replace.
            scoresTable.forEach(function(value, index) {
                if (value.score < request.score) {
                    scoresTable.splice(index, 0, {"name": request.name, "score": request.score});
                }
            });
    
            // Trim the last element and return
             scoresTable = scoresTable.slice(0, -1)
    
            // You probably want to update your file here
        }
    
    }
    

    现在,在您的 JavaScript 客户端文件上,当您想要保存新分数或获取高分表时,您应该向您的服务器发送一个AJAX request。 jQuery 提供了一个nicer syntax

        $.ajax({
            url: 'urlToYourServer',
            type: 'GET',
            data: '{
                "type": "submitScore",
                "name": "I beat Joe",
                "score": 2
            }'
        });
    

    在发送之前检查客户端中的分数是否足够高可能是个好主意。此外,您可能需要考虑一些安全措施,因为任何用户都可以在执行客户请求时作弊。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多