forked from TomK32/Unstack2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
highscores.moon
63 lines (52 loc) · 1.46 KB
/
highscores.moon
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
export json = require 'json'
export class Highscores
highscores_file: 'unstack2-highscores.txt'
scores_to_keep: 10
new: =>
@highscores = {}
@total_games = 0
@total_score = 0
@readLocalHighscores()
return @
insert: (score) =>
table.insert(@highscores, score)
@total_games += 1
@total_score += score.score
@tidyHighscores()
@saveLocalHighscores()
tidyHighscores: () =>
count = 0
min = nil
for i, score in ipairs(@highscores)
count += 1
if not min or score.score < min.score
min = score
min.pos = i
if count > @scores_to_keep and min
table.remove(@highscores, min.pos)
if count > @scores_to_keep + 1
@tidyHighscores()
@sortHighscores()
sortHighscores: =>
table.sort(@highscores, (a,b) -> return a.score > b.score)
highscoresFile: (right, block) =>
file = io.open(system.pathForFile(@highscores_file, system.DocumentsDirectory), right)
if not file
return
block(self, file)
io.close(file)
fileContent: =>
{
highscores: @highscores,
total_score: @total_score,
total_games: @total_games
}
saveLocalHighscores: =>
file = @highscoresFile 'w', (file) => file\write( json.encode(@fileContent()) )
readLocalHighscores: =>
file = @highscoresFile 'r', (file) => @content = json.decode( file\read("*a") )
if not @content
@highscores = {}
return
for k,v in pairs(@content)
@[k] = v