In the http://guide.elm-lang.org/architecture/effects/random.html, we were given an application that rolls a die and prints the number of the face that was rolled.
We were asked to add a second die that would be rolled together with the first one and show an image of a die instead of just printing the number on the face of the die.
Following you will find our proposed solution. We added a new value in the model for the second die and updated the message for NewFace to produce a message to roll the second die as well. Also we created a function that accepts the number of the face of the die and produces a path to the image that should be loaded.
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 | import Html exposing (..) import Html.App as Html import Html.Events exposing (..) import Html.Attributes exposing (..) import Random import String exposing (concat) main = Html.program { init = init , view = view , update = update , subscriptions = subscriptions } -- MODEL type alias Model = { dieFaceA : Int , dieFaceB : Int } init : (Model, Cmd Msg) init = (Model 1 1, Cmd.none) -- UPDATE type Msg = Roll | NewFaceA Int | NewFaceB Int update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Roll -> (model, Random.generate NewFaceA (Random.int 1 6)) NewFaceA newFace -> ({model | dieFaceA = newFace}, Random.generate NewFaceB (Random.int 1 6)) NewFaceB newFace -> ({model | dieFaceB = newFace}, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- UTILITIES createImage : Int -> String createImage dieFace = concat [ "./4-random/" , (toString dieFace), ".png" ] -- VIEW view : Model -> Html Msg view model = div [ ] [ img [ src (createImage model.dieFaceA) ] [ ] , h1 [ ] [ text (toString model.dieFaceA) ] , img [ src (createImage model.dieFaceB) ] [ ] , h1 [ ] [ text (toString model.dieFaceB) ] , button [ onClick Roll ] [ text "Roll" ] ] |
You can download the solution from here [download id=”1804″]
This post is also available in: Αγγλικα