Advertisement
Guest User

Untitled

a guest
Jul 20th, 2012
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. import qualified Data.Set as Set
  3. import System.Random
  4. import System.Console.ANSI
  5.  
  6. import System.IO  (stdin, stdout, hSetEcho, hSetBuffering, BufferMode(..))
  7.  
  8.  
  9. type Coord = (Int, Int)
  10.  
  11.  
  12. data Cell = Mine Bool | Empty Bool | Flag deriving (Show)
  13.  
  14.  
  15. data Level = Level {
  16.                     getCursor :: Coord,
  17.                     getField  :: [[Cell]]
  18.                    }
  19.  
  20.  
  21. instance Show Level where
  22.     show level = makeBorder $ unlines $ map (map $ toChr) (getField level)
  23.         where
  24.  
  25.             toChr :: Cell -> Char
  26.             toChr (Mine True)  = 'X'
  27.             -- cheat mode
  28.             toChr (Mine False) = 'X'
  29.             toChr (Empty True) = '.'
  30.             toChr (Flag)       = '|'
  31.             toChr _            = ' '
  32.  
  33.  
  34.  
  35. makeBorder :: String -> String
  36. makeBorder str = unlines $ horizontal : (map addVertical rows) ++ [horizontal]
  37.     where
  38.         rows = lines str
  39.         horizontal = '+' : take (length $ rows !! 0) (repeat '-') ++ "+"
  40.         addVertical row = '|' : row ++ "|"
  41.  
  42.  
  43. --generateLevel :: Int -> Int -> StdGen -> StdGen -> Int -> Level
  44. generateLevel width height gen nrMines =
  45.     Level { getCursor = (0, 0), getField = field }
  46.     where
  47.         xs = randoms gen
  48.         mines = uniqueCoords xs nrMines width height
  49.         getCell :: Int -> Int -> Cell
  50.         getCell x y
  51.             | Set.member (x, y) mines = Mine False
  52.             | otherwise               = Empty False
  53.         field = [ [ getCell x y | y <- [0..height] ] | x <- [0..width] ]
  54.  
  55.  
  56. uniqueCoords :: [Int] -> Int -> Int -> Int -> Set.Set Coord
  57. uniqueCoords randoms count limitX limitY =
  58.     recurse Set.empty randoms
  59.     where
  60.         recurse :: Set.Set Coord -> [Int] -> Set.Set Coord
  61.         recurse coords (randomX:randomY:randoms)
  62.             | Set.size coords == count  =  coords
  63.             | otherwise                 =  recurse (Set.insert (mod randomX limitX, mod randomY limitY) coords) randoms
  64.  
  65.  
  66.  
  67. main :: IO ()
  68. main = do
  69.  
  70.     hSetEcho stdin False
  71.     hSetBuffering stdin NoBuffering
  72.     hSetBuffering stdout NoBuffering
  73.    
  74.     gen <- getStdGen
  75.  
  76.     let level = generateLevel 12 18 gen 10
  77.     print level
  78.  
  79.     setTitle "FOO"
  80.     setCursorPosition 0 0
  81.     t <- getChar
  82.  
  83.     print t
  84.     --gameLoop level
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement