簡體   English   中英

如何使用Phaser創建全球高分?

[英]How to Create a Global High Score With Phaser?

我一直在使用Phaser JavaScript框架來制作可以放入HTML的游戲,但我似乎無法弄清楚如何制作一個高分系統。

我只能夠找到解決方案,像這一個 ,但它似乎在本地存儲在客戶端系統上的高分值,使他們只能看到自己的高分。 如果可能的話,我希望能夠以最高的級別和名字獲得全球最高分。

我知道,很可能我將不得不創建一個SQL數據庫來存儲所有這些內容,並使用node.js在游戲和數據庫之間移動它(我對SQL和node.js的了解非常有限),但是我不知道特別是應該如何與Phaser配合使用。 任何幫助表示贊賞。

由於您不了解SQL(而且您也不會保留那么多數據),因此您可以使用JSON文件。 該答案假設您有一台服務器(如果您打算使用Node.js,則需要一台服務器)。 另外,我假設您想制作一張老式的高分表 ,上面有一個分數和一個名稱。

這旨在作為一般指導。 您將需要找到如何用您選擇的語言來做我正在解釋的事情。

在您的服務器中,您將擁有一個文件(例如,scores.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請求 jQuery提供了更好的語法

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

在發送分數之前,最好先檢查一下客戶端中的分數是否足夠高。 另外,您可能需要考慮采取一些安全措施,因為任何用戶都可以通過欺騙來執行來自客戶端的請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM