Skip to content

Instantly share code, notes, and snippets.

@mbenke
Created October 29, 2017 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbenke/25b7f8c1315e1be883c269ada55da629 to your computer and use it in GitHub Desktop.
Save mbenke/25b7f8c1315e1be883c269ada55da629 to your computer and use it in GitHub Desktop.
JNP3 Sokoban coordinates and direction handling
data Coord = C Integer Integer
data Direction = R | U | L | D
data World = W Coord Direction Maze
handleEvent :: Event -> World -> World
handleEvent (KeyPress key) (W pos direction maze) = W pos'' dir'' maze where
maybeDir = keyToDir key
(pos', dir'')
| Just dir' <- maybeDir = (moveCoordDir dir' pos, dir')
| otherwise = (pos, direction)
pos'' = if isCoordValidForPlayer pos' maze then pos' else pos
handleEvent _ world = world
type CoordVec = (Integer, Integer)
-- dirToVec d = (round (negate $ sin a), round(cos a)) where a = directionToAngle d
dirToVec :: Direction -> CoordVec
dirToVec R = (1,0)
dirToVec U = (0,1)
dirToVec L = (-1,0)
dirToVec D = (0,-1)
maybeDirToVec :: Maybe Direction -> CoordVec
maybeDirToVec = maybe (0,0) dirToVec
moveCoordVec :: CoordVec -> Coord -> Coord
moveCoordVec (dx, dy) (C x y) = C (x+dx) (y+dy)
moveCoordDir :: Direction -> Coord -> Coord
moveCoordDir = moveCoordVec . dirToVec
keyToDir :: Text -> Maybe Direction
keyToDir "Left" = Just L
keyToDir "Up" = Just U
keyToDir "Right" = Just R
keyToDir "Down" = Just D
keyToDir _ = Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment