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