-
Notifications
You must be signed in to change notification settings - Fork 1
/
counter.lua
112 lines (94 loc) · 2.36 KB
/
counter.lua
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
local fontpool = require('fontpool')
local color = require('hug.color')
local textrender = require('textrender')
local counter = {}
local mt = { __index = counter }
local setmetatable = setmetatable
local abs = math.abs
local graphics = love.graphics
local setColor, setFont = graphics.setColor, graphics.setFont
local rectangle, polygon = graphics.rectangle, graphics.polygon
local counterFont = fontpool:get(22)
local counterMidY = 96 / 2
function counter.new(owner, name, x, min, max, value, interactive, bgcolor)
local instance = {
owner = owner,
name = name,
x = x,
y = owner:y(x),
min = min,
max = max,
value = value or min,
interactive = interactive or true
}
-- sets valuew and valueh on instance
counter.calculateValueSize(instance)
-- sets backcolor and forecolor
counter.setColor(instance, bgcolor or color.fromrgba(1, 1, 1))
return setmetatable(instance, mt)
end
function counter:up()
if self.interactive == false then
return false
end
local target = self.value + 1
if target > self.max then
return false
else
self.value = target
self:calculateValueSize()
return true
end
end
function counter:down()
if self.interactive == false then
return false
end
local target = self.value - 1
if target < self.min then
return false
else
self.value = target
self:calculateValueSize()
return true
end
end
function counter:draw()
local x = self.x
local y = self.y
setColor(self.backcolor)
rectangle('fill', x - 16, y - 96 + 32, 32, 32)
if self.interactive == true then
-- up arrow
polygon('fill',
x - 8, y - 48 - 16 - 8,
x + 8, y - 48 - 16 - 8,
x , y - 48 - 16 - 8 - 16)
-- down arrow
polygon('fill',
x - 8, y - 48 + 16 + 8,
x + 8, y - 48 + 16 + 8,
x , y - 48 + 16 + 8 + 16)
end
setFont(counterFont)
setColor(self.forecolor)
textrender.print(self.value, x - self.valuew / 2, y - counterMidY - self.valueh / 2)
end
function counter:overlaps(x, r)
local w = 32
local d = abs(self.x - x)
return d < r + w / 2
end
function counter:calculateValueSize()
self.valuew = counterFont:getWidth(self.value)
self.valueh = counterFont:getHeight()
end
function counter:setColor(bg, fg)
self.backcolor = bg
if fg ~= nil then
self.forecolor = fg
else
self.forecolor = -bg
end
end
return counter