-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaderboard.js
40 lines (32 loc) · 1.3 KB
/
leaderboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"use strict";
const LEADERBOARD_SIZE = 10;
class Leaderboard {
constructor () {
this.db = fbApp.database();
}
getUserInfo (username, callback) {
this.db.ref('userdata/' + encodeURIComponent(username)).once('value', (snapshot) => {
callback(username, snapshot.val());
});
}
getHighScores (callback) {
this.db.ref('userdata').orderByChild('totalScore').limitToLast(LEADERBOARD_SIZE).once('value', (snapshot) => {
var board = [];
snapshot.forEach((data) => {
board.push({user: data.key, data: data.val()});
});
board.reverse();
callback(board);
});
}
updateUserScore (username, level, score, totalScore) {
this.db.ref('userdata/' + encodeURIComponent(username) + '/totalScore').once('value', (snapshot) => {
this.db.ref('userdata/' + encodeURIComponent(username) + '/totalScore').set(Math.max(snapshot.val(), totalScore));
});
this.db.ref('userdata/' + encodeURIComponent(username) + '/levels/' + level.toString()).set(score);
}
addUser (username) {
this.db.ref('userdata/' + encodeURIComponent(username) + '/totalScore').set(0);
this.db.ref('userdata/' + encodeURIComponent(username) + '/levels/').set({});
}
}