在递归函数中更改变量

时间:2015-10-30 15:51:25

标签: haskell recursion

我正在努力在Haskell制作游戏。现在,我正在进行敌人的碰撞:也就是说,如果敌人与玩家发生碰撞,则分数会重置为0并且敌人会死亡。但是,我只是无法解决如何

我已经考虑了do块,但这不对(我不想返回IO)。我找不到任何指示我正确方向的东西,让我想知道它是否可能......

我所拥有的(那种丑陋的)代码是:

newEnemies = updateEnemies enemies
    updateEnemies :: [Point] -> [Point]
    updateEnemies [] = []
    updateEnemies (x:xs) | hitPlayer (nextLocation x) = -- TODO: Reset multipliers
                                                        updateEnemies xs
                         | otherwise = nextLocation x : updateEnemies xs
        where
        hitPlayer :: Point -> Bool
        hitPlayer (x, y) | abs (fst newPosition - x) < 10 && abs (snd newPosition - y) < 10
                            = True
                         | otherwise = False
        nextLocation loc = (loc + ((dirToPlayer loc) * (100, 100) * (timeStep, timeStep)))
        dirToPlayer loc = normalizeV (playerPosition - loc)

你们其中一个人能指出我正确的方向,还是我太习惯了命令式语言了?

谢谢!

1 个答案:

答案 0 :(得分:1)

所有updateEnemies确实在做的是将nextLocation应用于输入列表的每个元素,然后丢弃hitPlayer的元素。因此,主体可以简化为:

updateEnemies xs = filter (not . hitPlayer) $ map nextLocation xs

或者,如果您更喜欢更无积分的东西:

updateEnemies = filter (not . hitPlayer) . map nextLocation

此外,通过使用警卫来决定是否返回hitPlayerTrue来定义False是错误的;其他语言中的同等错误就是写if (condition) return true; else return false;。只需直接返回测试结果即可!

hitPlayer (x, y) = abs (fst newPosition - x) < 10 && abs (snd newPosition - y) < 10