aboutsummaryrefslogtreecommitdiff
path: root/src/Game/Utils.hs
blob: e2b320ab923228b4cf5d7a040ab242191cd9723b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module Game.Utils (rect, isPressed, isPressedGamepad) where

import Foreign.C.Types (CInt)
import qualified SDL
import qualified SDL.Input.GameController as SDL
import SDL.Vect (V2 (..))

rect :: Int -> Int -> Int -> Int -> SDL.Rectangle CInt
rect x y w h = SDL.Rectangle (SDL.P $ V2 (fromIntegral x) (fromIntegral y)) (V2 (fromIntegral w) (fromIntegral h))

isPressed :: SDL.Keycode -> [SDL.EventPayload] -> Maybe Bool
isPressed code events
  | any (isEventKey SDL.Pressed code) events = Just True
  | any (isEventKey SDL.Released code) events = Just False
  | otherwise = Nothing
  where
    isEventKey :: SDL.InputMotion -> SDL.Keycode -> SDL.EventPayload -> Bool
    isEventKey expected keycode (SDL.KeyboardEvent (SDL.KeyboardEventData _ motion False ksym)) = expected == motion && SDL.keysymKeycode ksym == keycode
    isEventKey _ _ _ = False

isPressedGamepad :: SDL.ControllerButton -> [SDL.EventPayload] -> Maybe Bool
isPressedGamepad button events
  | any (isEventButton SDL.ControllerButtonPressed button) events = Just True
  | any (isEventButton SDL.ControllerButtonReleased button) events = Just False
  | otherwise = Nothing
  where
    isEventButton :: SDL.ControllerButtonState -> SDL.ControllerButton -> SDL.EventPayload -> Bool
    -- FIXME: may be don't hardcode it to joystick 0
    isEventButton expected bu (SDL.ControllerButtonEvent (SDL.ControllerButtonEventData 0 b state)) = expected == state && bu == b
    isEventButton _ _ _ = False