How to get random numbers in Elm 0.13 without signal?
I am making a game where I need to draw random lines on the screen. Now it seems that Random needs a signal to work at 0.13 (and we are forced to work at 0.13). So how do I get this random number?
I started with the game skeleton provided on the elm-lang website and got to this:
type UserInput = { space : Bool, keys : [KeyCode] }
type Input = { timeDelta : Float, userInput : UserInput }
userInput : Signal UserInput
userInput = lift2 UserInput Keyboard.space Keyboard.keysDown
framesPerSecond = 30
delta : Signal Float
delta = lift (\t -> t / framesPerSecond) (Time.fps framesPerSecond)
input : Signal Input
input = Signal.sampleOn delta (Signal.lift2 Input delta userInput)
gameState : Signal GameState
gameState = Signal.foldp stepGame defaultGame input
stepGame : Input -> GameState -> GameState
stepGame i g =
if g.state == Start then *Get random floats*
Now in stepGame I want to draw random lines. The problem is that I can get random floats by giving a signal at 0.13 . I have an input close to a step function, but when I change the title to say
stepGame : Signal Input -> GameState -> GameState
it doesn't compile. So how can I get the signal in this function to get some random numbers ... I can't seem to find a solution, it drives me crazy.
source to share
There are two ways to do this. It really depends on whether the amount of random numbers is static to you or not.
Static number of random numbers
Expand input
with random numbers from Random.floatList
:
type Input = { timeDelta : Float, userInput : UserInput, randoms : [Float] } staticNoOfFloats = 42 input : Signal Input input = Signal.sampleOn delta (Signal.lift3 Input delta userInput (Random.floatList (always staticNoOfFloats <~ delta)))
Dynamic number of random numbers
Use a community library ( also described in this SO answer ) called generator . You can use a random seed using the Random.range
same as described above. The library is a pure pseudo-random number generator based on generating a random number and a new Generator
one that will produce the next random number.
Why not use it Random.floatList
in a dynamic case?
Usually if you need a dynamic number of random numbers, the number of which depends on the current state of the program. Since this state is fixed internally foldp
, where you are also doing an update based on those random numbers, it makes it impossible to use a "signal function", that is, something like Signal a -> Signal b
.
source to share