LeaderboardState.kt 2.11 KB
Newer Older
1
package se.battlegoo.battlegoose.gamestates
2
3

import com.badlogic.gdx.graphics.g2d.SpriteBatch
4
5
import se.battlegoo.battlegoose.network.LeaderboardEntry
import se.battlegoo.battlegoose.network.MultiplayerService
Lars Mitsem Selbekk's avatar
Lars Mitsem Selbekk committed
6
import se.battlegoo.battlegoose.views.screens.LeaderboardView
7

Ulrik Røsby's avatar
Ulrik Røsby committed
8
class LeaderboardState : GameState() {
9

10
11
12
13
14
    companion object {
        private const val UNKNOWN_USERNAME = "???"
        private const val LEADERBOARD_SIZE = 10
    }

15
16
17
18
    private val leaderboardView = LeaderboardView(
        this::goBack,
        stage
    )
19

20
21
    private var userId: String? = null

22
23
    private var leaderboard: List<LeaderboardEntry> = listOf()

24
25
26
    private fun getUserScoreText(): String {
        if (userId != null) {
            val place = leaderboard.indexOfFirst { it.userId == userId }
27
28
29
30
31
32
            if (place == -1) {
                MultiplayerService.incrementScore(0) {
                    updateLeaderboard()
                }
                return ""
            }
33
34
            val score = leaderboard[place].score
            return "\n\nYou (no. ${place + 1}): $score"
35
        }
36
37
38
39
40
41
42
43
        return ""
    }

    private fun getLeaderboardText(): String {
        return leaderboard.take(LEADERBOARD_SIZE).joinToString("\n") { entry ->
            "${(entry.username ?: UNKNOWN_USERNAME)}: ${entry.score}"
        }
    }
44
45
46

    init {
        updateLeaderboard()
47
48
49
50
51
52
53
54
        MultiplayerService.getUserID {
            userId = it
            updateText()
        }
    }

    private fun updateText() {
        leaderboardView.setLeaderboardText(getLeaderboardText() + getUserScoreText())
55
56
57
58
    }

    private fun goBack() {
        GameStateManager.goBack()
59
60
61
    }

    private fun updateLeaderboard() {
62
63
64
        MultiplayerService.getLeaderboard {
            it?.let {
                leaderboard = it
65
                updateText()
66
            }
67
        }
68
69
    }

70
    private fun handleInput() {
71
        leaderboardView.registerInput()
72
73
    }

74
    override fun update(dt: Float) {
75
        handleInput()
76
77
78
    }

    override fun render(sb: SpriteBatch) {
79
        leaderboardView.render(sb)
80
81
82
    }

    override fun dispose() {
Andrine Bergan's avatar
Andrine Bergan committed
83
        leaderboardView.dispose()
84
    }
85
}