只需处理样本,就可以创建2个随机骰子并用按钮滚动它们.
http://guide.elm-lang.org/architecture/effects/random.html
所以我想我会将骰子创建为模块,删除滚动动作,然后让它在init上创建D6值.
所以我的代码现在如下(应该直接在elm-reactor中打开)
module Components.DiceRoller exposing (Model, Msg, init, update, view)
import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Random
import String exposing (..)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ dieFace : Int
}
init : ( Model, Cmd Msg )
init =
( Model 0, (Random.generate NewFace (Random.int 1 6)) )
-- UPDATE
type Msg
= NewFace Int
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NewFace newFace ->
( Model newFace, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
dieFaceImage : Int -> String
dieFaceImage dieFace =
concat [ "/src/img/40px-Dice-", (toString dieFace), ".svg.png" ]
view : Model -> Html Msg
view model =
let
imagePath =
dieFaceImage model.dieFace
in
div []
[ img [ src imagePath ] []
, span [] [ text imagePath ]
]
Run Code Online (Sandbox Code Playgroud)
这个问题是它总是产生相同的值.我以为我的种子开始有问题,但如果你改变了
init =
( Model 0, (Random.generate NewFace (Random.int 1 6)) )
init =
( Model 0, (Random.generate NewFace (Random.int 1 100)) )
Run Code Online (Sandbox Code Playgroud)
它完全按照预期工作.所以看起来默认生成器不能处理小值,似乎工作低至10.
奇怪的是,在这个例子中(我开始使用)http://guide.elm-lang.org/architecture/effects/random.html,当它不在init时,它适用于1-6.
所以我的问题是,我做错了什么,或者这只是榆树的皱纹?我在init中使用该命令是否正常?
最后,我把它放进去以获得理想的效果,感觉很不稳定.
init =
( Model 0, (Random.generate NewFace (Random.int 10 70)) )
Run Code Online (Sandbox Code Playgroud)
同
NewFace newFace ->
( Model (newFace // 10), Cmd.none )
Run Code Online (Sandbox Code Playgroud)