-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscoreboard.rb
61 lines (53 loc) · 1.3 KB
/
scoreboard.rb
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
require 'sqlite3'
require './event_handler'
class Scoreboard
def initialize
@score = 0
@font = Gosu::Font.new(16)
load_or_create_db
@highscore = load_highscore_from_disk
EventHandler.register_listener(:fruit_eaten, self, :increment)
EventHandler.register_listener(:gameover, self, :save)
EventHandler.register_listener(:game_start, self, :reset)
end
def load_or_create_db
@db = SQLite3::Database.new("scores.db")
begin
@db.execute "SELECT * FROM scores LIMIT 1;"
rescue SQLite3::SQLException
@db.execute "CREATE TABLE scores (name varchar(64), score int);"
@db.execute "INSERT INTO scores VALUES (NULL, 0);"
end
end
def load_highscore_from_disk
@highscore = @db.get_first_value "SELECT score from scores ORDER BY score DESC LIMIT 1"
end
def reset(context)
@score = 0
end
def save(context)
if @score == @highscore
@db.execute "INSERT INTO scores VALUES (NULL, ?);", "#{@highscore}"
end
end
def increment(context)
@score += context[:points]
@highscore =[@score, @highscore].max
end
def draw
@font.draw_text(
"Score: #{@score}",
5,
5,
1,
)
@font.draw_text_rel(
"Highscore: #{@highscore}",
Config::WINDOW_X - 5,
5,
1,
1,
0,
)
end
end