main.hs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. -- Mine Sweeper Lab
  2. -- Import section
  3. import Data.Char
  4. import Data.Set ( Set )
  5. import qualified Data.Set as S
  6. -- Types
  7. data Cell = Covered Int Bool Bool -- number of bombs around ; has bomb ; has flag
  8. | Uncovered Int -- number of bombs around
  9. | Selected
  10. data Grid = Grid [[Cell]]
  11. data StdGen = SG -- TODO : replace
  12. type Mat = [[Int]]
  13. -- Methods
  14. instance Show Cell where
  15. show ( Covered _ _ hasFlag ) = if hasFlag then "[F]" else "[ ]"
  16. show ( Uncovered n ) = ['(', intToDigit n, ')']
  17. show Selected = ">x<"
  18. instance Show Grid where
  19. show (Grid a) = unlines $ map (unwords . map show) a
  20. -- Functions
  21. randSet::Int -> StdGen -> StdGen -> Int -> Int -> Set (Int, Int)
  22. randSet n sg1 sg2 h w =
  23. let byl = randomRs (0, h - 1) sg1 in
  24. let bxl = randomRs (0, w - 1) sg2 in
  25. let bl = zip byl bxl in
  26. let biggerSets = scanl (flip S.insert) S.empty bl in
  27. head (dropWhile (\s -> S.size s < n) biggerSets)
  28. grid::Int -> Int -> Set (Int, Int) -> Grid
  29. grid h w s = Grid [ [Covered 0 (S.member (y, x) s) False | x <- [0..w-1] ] | y <- [0..h-1] ]
  30. randomRs (x, y) sg = [x + mod k (y - x) | k <- [1..y] ] -- TODO : replace
  31. mineIndic::Cell -> Int
  32. mineIndic c = let Covered _ b _ = c in if b then 1 else 0
  33. mines::Grid -> Mat
  34. mines g = let Grid m = g in map (map mineIndic) m
  35. moveUp::Mat -> Mat
  36. moveUp m = concat [tail m, [[0 | _ <- [1..length (m!!0)]]]]
  37. moveDown::Mat -> Mat
  38. moveDown m = concat [[[0 | _ <- [1..length (m!!0)]]], init m]
  39. moveRight::Mat -> Mat
  40. moveRight m = map (\l -> 0 : init l) m
  41. moveLeft::Mat -> Mat
  42. moveLeft m = map (\l -> concat [tail l, [0]]) m
  43. -- Testing data
  44. dtTinyGrid = Grid [
  45. [Covered 2 True False, Uncovered 2, Covered 2 True False],
  46. [Selected, Uncovered 0, Covered 2 True True]
  47. ]
  48. dtRS = randSet 3 SG SG 4 5
  49. dtGridCover = grid 4 5 dtRS
  50. dtMines = mines dtGridCover