/
Player.elm
151 lines (101 loc) · 2.61 KB
/
Player.elm
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
module Player exposing
( Player, init
, PlayerId, id, idSorter
, name
, rating, setRating
, matchesPlayed, setMatchesPlayed, incrementMatchesPlayed
, encode
, decoder
)
{-|
@docs Player, init
@docs PlayerId, id, idSorter
@docs name
@docs rating, setRating
@docs matchesPlayed, setMatchesPlayed, incrementMatchesPlayed
@docs encode, decode
-}
import Elo
import Json.Decode as Decode exposing (Decoder)
import Json.Encode as Encode exposing (Value)
import Murmur3
import Sort exposing (Sorter)
type Player
= Player
{ id : PlayerId
, name : String
, rating : Int
, matches : Int
}
init : String -> Player
init name_ =
Player
{ id = PlayerId (Murmur3.hashString 0 name_)
, name = name_
, rating = Elo.initialRating
, matches = 0
}
-- ID
type PlayerId
= PlayerId Int
id : Player -> PlayerId
id (Player player) =
player.id
idSorter : Sorter PlayerId
idSorter =
Sort.by (\(PlayerId id_) -> id_) Sort.increasing
-- NAME
name : Player -> String
name (Player player) =
player.name
-- RATING
rating : Player -> Int
rating (Player player) =
player.rating
setRating : Int -> Player -> Player
setRating rating_ (Player player) =
Player { player | rating = rating_ }
-- MATCHES PLAYED
matchesPlayed : Player -> Int
matchesPlayed (Player player) =
player.matches
setMatchesPlayed : Int -> Player -> Player
setMatchesPlayed matches (Player player) =
Player { player | matches = matches }
incrementMatchesPlayed : Player -> Player
incrementMatchesPlayed (Player player) =
Player { player | matches = player.matches + 1 }
-- INTEROP
decoder : Decoder Player
decoder =
Decode.map4
(\id_ name_ rating_ matches ->
Player
{ id = id_
, name = name_
, rating = rating_
, matches = matches
}
)
(Decode.oneOf
[ Decode.field "id" Decode.int
, Decode.field "name" Decode.string
|> Decode.map (Murmur3.hashString 0)
]
|> Decode.map PlayerId
)
(Decode.field "name" Decode.string)
(Decode.field "rating" Decode.int)
(Decode.field "matches" Decode.int)
encode : Player -> Value
encode (Player player) =
let
(PlayerId idInt) =
player.id
in
Encode.object
[ ( "id", Encode.int idInt )
, ( "name", Encode.string player.name )
, ( "rating", Encode.int player.rating )
, ( "matches", Encode.int player.matches )
]