-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounter.hs
61 lines (48 loc) · 1.54 KB
/
Counter.hs
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
{-# LANGUAGE TemplateHaskell #-}
module GameEngine.Counter
(Counter()
,mkCounter
,resetCounter
,addCounter
,subCounter
,counterCount
,counterInitialCount
,counterMinCount
,counterMaxCount
,atMin
,atMax
)
where
import Control.Lens
import Foreign.C.Types
-- A counter keeps a CInt between a range
data Counter = Counter
{_counterCount :: CInt
,_counterInitialCount :: CInt
,_counterMinCount :: CInt
,_counterMaxCount :: CInt
}
deriving (Show,Eq)
makeLenses ''Counter
mkCounter :: CInt -- ^ Initial count
-> CInt -- ^ Minimum count
-> CInt -- ^ Maximum count
-> Maybe Counter -- ^ minimum <= initial <= maximum
mkCounter iC minC maxC
| (minC <= iC) && (iC <= maxC) && (minC <= maxC) = Just $ Counter iC iC minC maxC
resetCounter :: Counter -> Counter
resetCounter c = set counterCount (c^.counterInitialCount) c
-- Add an amount to a counter. Dont exceed the minimum or maximum.
addCounter :: CInt -> Counter -> Counter
addCounter x c
| c^.counterCount + x < c^.counterMinCount = set counterCount (c^.counterMinCount) c
| c^.counterMaxCount < c^.counterCount + x = set counterCount (c^.counterMaxCount) c
| otherwise = over counterCount (+x) c
subCounter :: CInt -> Counter -> Counter
subCounter x = addCounter (-1 * x)
-- Is the counter at its minimum value?
atMin :: Counter -> Bool
atMin c = c^.counterCount == c^.counterMinCount
-- Is the counter at its maximum value?
atMax :: Counter -> Bool
atMax c = c^.counterCount == c^.counterMaxCount