You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.2 KiB

  1. {-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
  2. module JSONDeser(readInput) where
  3. import qualified Data.Set as Set
  4. import Data.Maybe
  5. import qualified Data.ByteString.Lazy as BS
  6. import Data.Aeson
  7. import GHC.Generics
  8. import qualified Datatypes as DT
  9. import LCG
  10. data Cell = Cell { x :: Int, y :: Int}
  11. deriving (Show, Generic)
  12. data Unit = Unit { members :: [Cell], pivot :: Cell}
  13. deriving (Show, Generic)
  14. data Input = Input { id :: Int,
  15. units :: [Unit],
  16. width :: Int,
  17. height :: Int,
  18. filled :: [Cell],
  19. sourceLength :: Int,
  20. sourceSeeds :: [Int]
  21. }
  22. deriving (Show, Generic)
  23. instance FromJSON Cell
  24. instance ToJSON Cell
  25. instance FromJSON Unit
  26. instance ToJSON Unit
  27. instance FromJSON Input
  28. instance ToJSON Input
  29. readInput :: BS.ByteString -> (Int,[(Int,DT.Game)])
  30. readInput str = newGame (readInputInternal str)
  31. readInputInternal :: BS.ByteString -> Input
  32. readInputInternal str = if isJust result
  33. then fromJust result
  34. else error "Error during JSON parsing"
  35. where
  36. result = (decode str :: Maybe Input)
  37. newGame :: Input -> (Int,[(Int,DT.Game)])
  38. newGame input = (JSONDeser.id input, zip (sourceSeeds input) (map gameFromSeed (sourceSeeds input)))
  39. where
  40. gameFromSeed seed = DT.Game board (seedUnits seed input) (Set.empty :: Set.Set Int) 0 0
  41. board = DT.Board w h filledel
  42. w = width input
  43. h = height input
  44. filledel = Set.fromList (map cellConvVM (filled input))
  45. seedUnits :: Int -> Input -> [DT.Unit]
  46. seedUnits s input = map (\x -> uinput !! x ) unit_index
  47. where
  48. unit_index = lcg s (length (units input)) (sourceLength input)
  49. uinput = map unitConvVM (units input)
  50. cellConvVM :: Cell -> DT.Cell
  51. cellConvVM (Cell x y) = (x,y)
  52. unitConvVM :: Unit -> DT.Unit
  53. unitConvVM unit = DT.Unit setcell (cellConvVM (pivot unit))
  54. where
  55. setcell = Set.fromList (map cellConvVM (members unit))