Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:24
Show Gist options
  • Save davidallsopp/6d8a4e0523922f038167 to your computer and use it in GitHub Desktop.
Save davidallsopp/6d8a4e0523922f038167 to your computer and use it in GitHub Desktop.
Game loop - looping with a fixed delay in Haskell until a condition is met
module TimerLoop where
import Control.Monad.Loops (iterateUntilM)
import Control.Concurrent (threadDelay)
-- Adapted from https://stackoverflow.com/questions/19285691/how-do-i-write-a-game-loop-in-haskell
--
-- NB must compile with -threaded option or the threadDelay has no apparent effect
-- even, then 9 and 10 are printed out simultaneously on my Windows 7 machine (GHCi 7.8.3)
type World = Int
initWorld :: World
initWorld = 1
-- False when the user wants to exit the game
keepGoing :: World -> Bool
keepGoing w = (>= 10)
displayWorld :: World -> IO ()
displayWorld = print
gameLoop :: World -> World
gameLoop = (+1)
main :: IO World
main = iterateUntilM keepGoing displayLoop initWorld
where displayLoop w = do
threadDelay 1000000 -- microseconds not millis!
displayWorld w >> return (gameLoop w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment