haskellgloss

Posting a message while running Gloss code in Haskell


The Haskell playIO has the below type:

 playIO:: Display   
-> Color    background color
-> Int  
-> world    --initial world 
-> (world -> IO Picture)  -- function to change world into a picture    
-> (Event -> world -> IO world) --event handler function
-> (Float -> world -> IO world) -- The function to update the world after the given time 
-> IO ()

Once you call playIOinside main, it runs continuously updating the GUI which is modelled by the world. In case something happened inside the code that handles events(see comments on code) or the function that updates the world and you wanted to output a message (Not necessarily an error), what approach would one use that does not violate the types? Would one have to break out of the function playIOto display my message and if so how would one do that?


Solution

  • If you want to, say, emit a message based on the event then put that operation inside the event handler. For example:

    main :: IO ()
    main = playIO black 100 world0 renderWorld handleEvent updateWorld
    
    handleEvent evt w =
        do print event -- Right here, you are emitting a message!
           updateWorldWithEvent evt w
           putStrLn "I have updated the world, now time for breakfast."
    

    Just keep in mind the handleEvent operation will potentially happen quite frequently so select your output accordingly.