roguelike/src/Dungeon.hs

58 lines
1.4 KiB
Haskell
Raw Normal View History

{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
2021-02-11 22:40:00 +00:00
module Dungeon where
2021-02-19 18:52:43 +00:00
import Data.Aeson
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
import Lens.Micro.TH
import Lens.Micro
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
data Dungeon = Dungeon
{ _name :: String
, _layout :: Matrix Cell
}
makeLenses ''Dungeon
2021-02-11 22:40:00 +00:00
instance Show Dungeon where
show dun = unlines . map (concatMap show) $ toLists $ dun ^. layout
2021-02-11 22:40:00 +00:00
instance FromJSON Dungeon where
parseJSON = withObject "Dungeon" $ \v -> do
mapName <- v .: "name"
stringMap <- v .: "layout"
let cellMappingR = map swap cellMapping
charToCell c = fromMaybe (error "Invalid cell in the .map file") (c `lookup` cellMappingR)
cellLists = map charToCell <$> stringMap
return $ Dungeon mapName (fromLists cellLists)
makeDungeonFromFile :: FilePath -> IO Dungeon
2021-02-15 19:57:45 +00:00
makeDungeonFromFile f = do
eithDun <- eitherDecodeFileStrict f
return $ case eithDun of
Left err -> error err
Right dun -> dun
2021-02-11 22:40:00 +00:00
dungeonToLists :: Dungeon -> [[Cell]]
dungeonToLists dun = toLists $ dun ^. layout
getCell :: V2 Int -> Dungeon -> Cell
getCell (V2 x y) dun = fromMaybe Solid (safeGet (y+1) (x+1) $ dun ^. layout)