elm generate random number

家住魔仙堡 提交于 2019-11-30 18:56:21

Updated for 0.18

app =
  Html.programWithFlags
    { init = init
    , update = update
    , view = view
    , subscriptions = always Sub.none
    }

init : {startTime : Float} -> Model 
init {startTime} = 
    { blankModel | randomSeed = Random.initialSeed <| round startTime }

index.html

<script type="text/javascript">
    var yourPgm = Elm.fullscreen(Elm.Main, {startTime: Date.now()});
</script>

Original Answer

Random numbers are complex in pure programs, but this is how I do it in one of my games (using Elm Architecture):

Main.elm

startTimeSeed : Seed
startTimeSeed = Random.initialSeed <| round startTime

app =
  StartApp.start
    { init = (init 8 8 startTimeSeed, Effects.none)
    , update = update
    , view = view
    , inputs = []
    }

port startTime : Float

index.html

<script type="text/javascript">
    var yourPgm = Elm.fullscreen(Elm.Main, {startTime: Date.now()});
</script>

In other words pass the time stamp through port when you start the game

mgold

it's always return[ing] the same value

This is how pure random number generators work. You pass in a Seed, and you get back another Seed.

and it's not even an int it's something like this [crazy code snippet]

This is a pair of values. The first is the int you're looking for. The second is the new seed to generate random values. Don't worry about what a seed actually is; it should be opaque. You can get the int out the pair using fst, but if you want more random numbers, you'll need the new seed.

So from the doc, it's better to use the current time for the seed.

This doc is wrong, wrong, wrong. As you've discovered, there isn't an easy way to get the current timestamp. And if you're passing it in from JS, like Simon advises, just use Math.floor(Math.random()*0xFFFFFFFF) instead. This gives you a seed that is better sampled over the possible input space.

This is extremely important because the random number generator will output similar values for similar seeds. For example, if you you use any seed less than 53668 and generate one bool, it will be True. This is because of weaknesses in the algorithm used.

The better solution: --> use this library<-- . It works the same way as the core library, but the algorithm is much better, and the docs on seeds aren't blatantly wrong.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!