-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatistics.js
More file actions
74 lines (62 loc) · 1.48 KB
/
statistics.js
File metadata and controls
74 lines (62 loc) · 1.48 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @fileoverview Manages player statistics, including loading, saving, and updating game history.
*/
import database from './database.js';
class Statistics {
/**
* Creates a Statistics instance for a player.
* @param {*} username - The player's username.
*/
constructor(username) {
this.username = username;
this.gameHistory = [];
}
/**
* Loads the player's statistics from the database.
*/
async load() {
const db = await database.connect();
const collection = db.collection('statistics');
const data = await collection.findOne({ username: this.username });
if (data) {
this.gameHistory = data.gameHistory || [];
}
}
/**
* Saves the player's statistics to the database.
*/
async save() {
const db = await database.connect();
const collection = db.collection('statistics');
console.log('Saving statistics for', this.username);
await collection.updateOne(
{ username: this.username },
{
$set: {
gameHistory: this.gameHistory
}
},
{ upsert: true }
);
}
/**
* Adds a game result to the player's history.
*
* @param {Object} result - The game result to add.
*/
addGameResult(result) {
this.gameHistory.push({
...result
});
}
/**
* Retrieves the last n game results.
*
* @param {number} n - The number of recent game results to retrieve.
* @return {Array} - An array of the last n game results.
*/
getStats(n = 5) {
return this.gameHistory.slice(-n).reverse();
}
}
export default Statistics;