1
Fork 0
This repository has been archived on 2023-12-08. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
2022FuncProg-project2-patience/lib/InputHandler.hs

60 lines
1.7 KiB
Haskell

module InputHandler
( Event
, handleInput
, composeInputHandler
, handleSpace
, handleEnter
, handleUp
, handleDown
, handleLeft
, handleRight
) where
import Graphics.Gloss
import qualified Graphics.Gloss.Interface.IO.Game as Game
----------------------------- Constants ------------------------------
-- Something that happens, most often a keypress
type Event = Game.Event
----------------------------------------------------------------------
-- Handle input by taking a keyCheck function that checks wheter or not
-- a key is being presse
handleInput :: Game.SpecialKey -> (a -> a) -> Event -> a -> a
handleInput key convert ev currentState
| isKey key ev = convert currentState
| otherwise = currentState
-- Compose multiple InputHandlers into one combined InputHandler.
composeInputHandler :: [Event -> a -> a] -> Event -> a -> a
composeInputHandler (ih:ihs) ev a = composeInputHandler ihs ev (ih ev a)
composeInputHandler [] ev a = a
-- Check if the requested key is pressed.
isKey :: Game.SpecialKey -> Event -> Bool
isKey k1 (Game.EventKey (Game.SpecialKey k2) Game.Down _ _) = k1 == k2
isKey _ _ = False
------------------ A couple of default inputhandlers -----------------
handleSpace :: (a -> a) -> Event -> a -> a
handleSpace = handleInput Game.KeySpace
handleEnter :: (a -> a) -> Event -> a -> a
handleEnter = handleInput Game.KeyEnter
handleUp :: (a -> a) -> Event -> a -> a
handleUp = handleInput Game.KeyUp
handleDown :: (a -> a) -> Event -> a -> a
handleDown = handleInput Game.KeyDown
handleLeft :: (a -> a) -> Event -> a -> a
handleLeft = handleInput Game.KeyLeft
handleRight :: (a -> a) -> Event -> a -> a
handleRight = handleInput Game.KeyRight