简体   繁体   中英

Haskell Random Number Generator

I want to spawn an enemy at a random time in my game. To do this I wanted to check each frame if a random value [0..100] == 50

spawnEnemy :: World -> World
spawnEnemy (world@World { rndGen = r, enemies = e }) = world { enemies = if rand 0 100 == 50 then Enemy (rand (-200) 200, rand (-200) 200) 0 0 : e else e }
    where
        rand :: Float -> Float -> Float
        rand l h = fst $ randomR (l, h) r

(here rndGen :: stdGen and enemies :: [Enemy])

But rand never seems to return 50. What am I doing wrong here?

The chance of getting a random Float to equal 50 is pretty low because Floats are not necessarily whole numbers. Try converting your random number to an Integral first using floor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM