Newer
Older
MazeGame / src / menu / LeaderboardPage.js
/*
 * Copyright (c) 2020. Antonio Martinez Casadesus and Pascal Syma.
 * All rights reserved.
 */

Page = require("./Page");
Storage = require("../Storage");
Player = require("../Player");

class LeaderboardPage extends Page {

    initChilds() {

        this.nodes = [
            Page.addH("TemplAir"),
            Page.addH("Leaderboard", 2)
        ];

        this.loadLeaderboard();
        super.initChilds();
    }

    loadLeaderboard() {
        let games = [];
        Storage.get().recentGames.forEach((g, i, a) => {
            if (!g.success)
                return;

            let levelsplit = g.level.split("-");
            let level = parseInt(levelsplit[0]) - 1;
            if (!games[level])
                games[level] = [];

            for (let j = i - 1; j > (i - parseInt(levelsplit[1])); j--) {
                if (!a[j])
                    break;

                g.tickCount += a[j].tickCount;
            }

            games[level].push(g);
        });
        Object.keys(games).forEach((e) => {

            games[e] = games[e].sort((a, b) => {
                return a.tickCount - b.tickCount;
            });
        });

        console.log(games);

        let nodes = [];

        games.forEach((g, i) => {
            nodes.push(Page.addH("Level " + (i + 1), 3));
            g.forEach((p, i) => {
                if (i >= 5)
                    return;
                nodes.push(Page.addP(p.name + " - " + this.parseTime(p.tickCount), 4));
            });
        });

        nodes.forEach((p) => this.nodes.push(p));
    }

    parseTime(tickCount) {

        tickCount = Math.round(tickCount / 10);

        let m = Math.floor(tickCount / 60);
        let s = Player.mod(tickCount - (m * 60), 60);

        return "" + (m > 9 ? m : "0" + m) + ":" + (s > 9 ? s : "0" + s);
    }
}

module.exports = LeaderboardPage;