roguelike/src/Dungeon.hs

50 lines
1.2 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
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
instance FromJSON Dungeon where
parseJSON = withObject "Dungeon" $ \v -> do
stringMap <- v .: "map"
let cellMappingR = map swap cellMapping
charToCell c = fromMaybe (error "Invalid cell in the .map file") (c `lookup` cellMappingR)
cellLists = map charToCell <$> stringMap
return . Dungeon . 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 (Dungeon m) = toLists m
getCell :: V2 Int -> Dungeon -> Cell
getCell (V2 x y) (Dungeon m) = fromMaybe Solid (safeGet (y+1) (x+1) m)