-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dice.elm
88 lines (57 loc) · 1.5 KB
/
Dice.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
module Dice exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Random
main : Program Never Model Msg
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- Model
type alias Model =
{ dice : List Int }
initialModal : Model
initialModal =
{ dice = [ 1, 2, 3, 4, 5, 6 ] }
init : ( Model, Cmd Msg )
init =
( initialModal, Cmd.none )
-- Update
type Msg
= Roll
| NewFaceForIndex Int Int
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Roll ->
model ! (List.indexedMap generateRandomFace model.dice)
NewFaceForIndex index newFace ->
{ model | dice = (setValueAtIndex newFace index model.dice) } ! []
generateRandomFace : Int -> a -> Cmd Msg
generateRandomFace index _ =
Random.generate (NewFaceForIndex index) (Random.int 1 6)
setValueAtIndex : a -> Int -> List a -> List a
setValueAtIndex newVal index =
List.indexedMap
(\i oldVal ->
if index == i then
newVal
else
oldVal
)
-- View
view : Model -> Html Msg
view model =
div [] (List.map renderDie model.dice)
renderDie : Int -> Html Msg
renderDie face =
img
[ onClick Roll
, src ("https://wpclipart.com/recreation/games/dice/die_face_" ++ (toString face) ++ ".png")
, width 50
]
[]