roguelike/src/Dungeon.hs

48 lines
1.3 KiB
Haskell
Raw Normal View History

2021-02-19 18:52:43 +00:00
{-# LANGUAGE OverloadedStrings #-}
2021-02-11 22:40:00 +00:00
module Dungeon where
2021-02-19 18:52:43 +00:00
import Data.Aeson
import Data.Aeson.Types
2021-02-18 19:35:11 +00:00
import Data.Matrix
import Linear.V2
2021-02-15 19:57:45 +00:00
import Data.Tuple
import Data.Maybe
2021-02-11 22:40:00 +00:00
2021-02-15 19:57:45 +00:00
data Cell = Solid
| Empty
deriving (Eq)
2021-02-11 22:40:00 +00:00
instance Show Cell where
2021-02-18 19:35:11 +00:00
show cell = [fromMaybe '?' (lookup cell cellMapping)]
2021-02-15 19:57:45 +00:00
2021-02-18 19:35:11 +00:00
cellMapping :: [(Cell, Char)]
cellMapping =
2021-02-15 19:57:45 +00:00
[ (Empty, '.')
, (Solid, '#')
]
2021-02-11 22:40:00 +00:00
newtype Dungeon = Dungeon (Matrix Cell)
instance Show Dungeon where
show (Dungeon m) = unlines . map (concatMap show) $ toLists m
2021-02-15 19:57:45 +00:00
makeDungeonFromFile :: String -> IO Dungeon
makeDungeonFromFile f = do
2021-02-19 18:52:43 +00:00
--contents <- readFile f
ef <- eitherDecodeFileStrict f :: IO (Either String Object)
let obj = case ef of (Right o) -> o
(Left l) -> error l
let stringMap = case parse (.: "map") obj :: Result [String] of
(Success m) -> m
(Error s) -> error s
2021-02-18 19:35:11 +00:00
let cellMappingR = map swap cellMapping
charToCell c = fromMaybe (error "Invalid cell in the .map file") (c `lookup` cellMappingR)
2021-02-19 18:52:43 +00:00
cellLists = map charToCell <$> stringMap
2021-02-18 19:35:11 +00:00
return . Dungeon . fromLists $ cellLists
2021-02-11 22:40:00 +00:00
dungeonToLists :: Dungeon -> [[Cell]]
dungeonToLists (Dungeon m) = toLists m
getCell :: V2 Int -> Dungeon -> Cell
getCell (V2 x y) (Dungeon m) = fromMaybe Solid (safeGet (y+1) (x+1) m)