1

使用 Haskell 的 Gloss 库,我正在尝试模拟星空。视觉方面(以不同的速度和大小在屏幕上绘制“星星”)正在发挥作用。然而,由于某种原因,恒星并没有随机分布,导致模拟具有模式。我在爆炸模拟中也遇到了这个问题,但为了简单起见,我暂时不考虑这个问题。到目前为止,这是我的代码的简化版本:

type Position       = (Float, Float)
type Velocity       = (Float, Float)
type Size           = Float
type Speed          = Float
type Drag           = Float
type Life           = Int

type Particle       = (Position, Velocity, Speed, Drag, Life, Size)

-- timeHandler is called every frame by the gloss ‘Play’ function. It's being passed
-- the delta time and the world it needs to update.
timeHandler dt world = world {rndGen = mkStdGen (timer world),
                              timer  = (timer world) + 1,
                              stars  = spawnParticle world (rndGen world) : updateParticles (stars world) dt world}

randomFloat :: StdGen -> Float -> Float -> Float
randomFloat rand min max = fst $ randomR (min, max) rand

spawnParticle :: World -> StdGen -> Particle
spawnParticle world gen = ((pos, (1 * speed, 0), speed, 1, 0, size), snd (split gen))
where pos   = (px', py')
      px'   = randomFloat gen (-600) (-500)
      py'   = randomFloat gen (-250) 250
      speed = size * (randomFloat gen 100 300) -- the smaller a particle, the slower 
      size  = randomFloat gen 0.1 1.3

updateParticles :: [Particle] -> Float -> World -> [Particle]
updateParticles []     _  _     = []
updateParticles (x:xs) dt world | fst(posPart x) > 500 = updateParticles xs dt world
                                | otherwise            = updatedPart : updateParticles xs dt world
    where pos'        = updateParticlePosition dt x world
          updatedPart = (pos', velPart x, speedPart x, 1, 0, sizePart x)

注意:velPartspeedPart是从给定粒子中获取属性的函数。同样,绘图工作正常,所以我将省略该代码。updateParticlePosition简单地将速度添加到恒星的当前位置。

我认为这个问题与我的随机生成器没有正确传递这一事实有关,但我太困惑了,无法提出解决方案......非常感谢任何帮助!

4

1 回答 1

2

这与光泽无关,只是与纯随机数生成的语义有关。每次使用新种子重新初始化新生成器不会给您伪随机数,因为随机性仅来自于由 eg 创建的新生成器randomRsplit将具有与原始生成器非常不同的种子。您只需在每个步骤map mkStdGen [0..]中添加1, 即可。timer

考虑以下分布的差异:

map (fst . randomR (1,1000) . mkStdGen) [0..1000]
take 1000 $ randomRs (1,1000) (mkStdGen 123)

第一个是你在做什么,第二个是正确的随机数。

解决方案很简单,只需split在您的时间更新功能中使用(您已经拥有它spawnParticle):

timeHandler dt world = 
  let (newRndGen, g) = split (rndGen world) in 
   world { rndGen = newRndGen 
         , timer  = (timer world) + 1 , 
         , stars  = spawnParticle world g : updateParticles (stars world) dt world
         }

请注意,现在timer没有使用,timer = timer world + dt无论如何使用它可能更有意义(时间增量可能不完全相等)。

另外请记住,您不应该重用生成器,因此如果您有许多将生成器作为参数的本地函数,您可能需要类似:

timeHandler dt world = 
  let (newRndGen:g0:g1:g2:_) = unfoldr (Just . split) (rndGen world) in 
   world { rndGen = newRndGen 
         , timer  = (timer world) + 1 , 
         , stars  = spawnParticle world g0 : updateParticles (stars world) dt world
         , stuff0 = randomStuff0 g1 , stuff1 = randomStuff1 g2 }
于 2016-10-28T15:38:56.607 回答