-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.mo
More file actions
82 lines (65 loc) · 2.48 KB
/
app.mo
File metadata and controls
82 lines (65 loc) · 2.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
75
76
77
78
79
80
81
82
import Array "mo:base@0.16/Array";
import Int "mo:base@0.16/Int";
import Random "mo:base@0.16/Random";
import ZenDB "mo:zendb";
persistent actor FlyingNinja {
type LeaderboardEntry = {
name : Text;
score : Nat;
};
let LeaderboardEntrySchema : ZenDB.Schema = #Record([
("name", #Text),
("score", #Nat),
]);
let candify : ZenDB.Candify<LeaderboardEntry> = {
to_blob = func(data : LeaderboardEntry) : Blob = to_candid (data);
from_blob = func(blob : Blob) : ?LeaderboardEntry = from_candid (blob);
};
stable let zendb = ZenDB.newStableState(null);
let db = ZenDB.launchDefaultDB();
let #ok(leaderboard) = db.createCollection(
"leaderboard",
LeaderboardEntrySchema,
candify,
?{
schema_constraints = [#Unique("name")];
},
);
let #ok(_) = leaderboard.createIndex("score_idx", [("score", #Descending)], null);
// Returns if a certain score is good enough to warrant an entry on the leaderboard.
public query func isHighScore(score : Nat) : async Bool {
if (leaderboard.size() < 10) {
return true;
};
// Whenever a new entry is added, the leaderboard is sorted.
// We can safely assume that the last entry has the lowest score.
let #ok(lowestScores) = leaderboard.search(
ZenDB.QueryBuilder().SortBy("score", #Ascending).Limit(1)
);
return score > lowestScores[0].score;
};
// Adds a new entry to the leaderboard if the score is good enough.
public func addLeaderboardEntry(name : Text, score : Nat) : async [LeaderboardEntry] {
let newEntry : LeaderboardEntry = { name; score };
let #ok(_) = leaderboard.insert(newEntry);
// Keep only the top 10 scores
// delete the smallest score immediately, if the leaderboard is larger than 10
if (leaderboard.size() > 10) {
let #ok(_) = leaderboard.delete(
ZenDB.QueryBuilder().SortBy("score", #Ascending).Limit(1)
);
};
return leaderboard;
};
// Returns the current leaderboard.
public query func getLeaderboard() : async [LeaderboardEntry] {
let #ok(entries) = leaderboard.search(
ZenDB.QueryBuilder().SortBy("score", #Descending)
);
return entries;
};
// Produces secure randomness as a seed to the game.
public func getRandomness() : async Blob {
await Random.blob();
};
};