榆树生成随机数 [英] elm generate random number

查看:85
本文介绍了榆树生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在榆木的两个值之间生成一个随机整数. 像这样:

I want to generate a random int between two values in elm. Something like this:

nb = random(0, 10)

我已阅读文档和多篇文章.最好的答案是来自此stackoverflow post

I have read the doc and multiple post. The best answer was from this stackoverflow post

gen = Random.int 0 10
seed0 = Random.initialSeed 123456
Random.generate gen seed0

但是问题是它总是返回相同的值,甚至不是整数,它是这样的:

But the issue is it's always return the same value and it's not even an int it's something like this:

(7,Seed { state = State 645041272 40692, next = <function>, split = <function>, range = <function> })
: ( Int, Random.Seed )

因此,从 doc ,最好使用当前时间作为种子.但是我怎么得到呢?我必须为此使用信号吗?有没有简单的方法来获取时间戳?

So from the doc, it's better to use the current time for the seed. But how do I get it? Do I have to use signal for this ? is there not an easy way to get a timestamp?

我很困惑,我需要为种子生成一个随机整数,以便可以生成一个随机整数.如果不是,则生成的随机int不是随机的.我想我误会了一些东西...

I'm a lot confuse, I need to generate a random int for the seed so I can generate a random int. If not the random int generated is not random. I think I have misunderstood something ...

我也找到了这个帖子,但是我一无所知.

edit: I have also found this post but I didn't understand everything.

推荐答案

更新为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

index.html

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


原始答案

在纯程序中,随机数很复杂,但是这就是我在我的游戏之一中做到的(使用Elm体系结构):

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

这篇关于榆树生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆