只是通过样本,得到了关于创建 2 个随机骰子并用按钮滚动它们的练习。
http://guide.elm-lang.org/architecture/effects/random.html
所以我想我会将骰子创建为一个模块,删除滚动 Action ,然后让它在初始化时创建一个 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 ]
]
问题在于它总是产生相同的值。一开始我以为我的种子有问题,但如果你改变
init =
( Model 0, (Random.generate NewFace (Random.int 1 6)) )
init =
( Model 0, (Random.generate NewFace (Random.int 1 100)) )
它完全按预期工作。所以看起来默认生成器不能使用小值,似乎低至 10。
奇怪的是,在这个例子中(我从这个例子开始)http://guide.elm-lang.org/architecture/effects/random.html ,当它不在 init 中时,它与 1-6 一起工作正常。
所以我的问题是,我做错了什么,还是这只是榆树的一个皱纹?我在 init 中使用命令可以吗?
最后,我把它放进去以获得想要的效果,感觉很不稳定。
init =
( Model 0, (Random.generate NewFace (Random.int 10 70)) )
和
NewFace newFace ->
( Model (newFace // 10), Cmd.none )
最佳答案
这一定与播种有关。您没有为种子指定任何值,因此生成器默认使用当前时间。
我认为您尝试在几秒钟内刷新页面几次,但您没有看到值发生变化。如果您等待更长的时间(大约一分钟),您会看到您的值发生变化。
我查看了 Random 的源代码,我怀疑对于足够接近的种子值,在 [1,6] 范围内生成的第一个值不会改变。我不确定这是否是预期的,可能值得在 GitHub 上提出一个问题
关于random - Elm - 初始化奇怪行为的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37522369/