56 lines
1.9 KiB
Haskell
56 lines
1.9 KiB
Haskell
|
module Main where
|
||
|
|
||
|
import System.Random
|
||
|
|
||
|
main :: IO ()
|
||
|
main = do
|
||
|
rng <- newStdGen
|
||
|
putStrLn (printBoard $ createBoard 12 0.2 rng)
|
||
|
|
||
|
type Square = (Int, Int)
|
||
|
type Grid = [[Bool]]
|
||
|
|
||
|
data Board = Board { size :: Int
|
||
|
, mines :: Grid
|
||
|
, uncovered :: Grid
|
||
|
, flagged :: Grid
|
||
|
} deriving (Show)
|
||
|
|
||
|
-- Creates a board given a size (width/height), mine ratio and random generator
|
||
|
createBoard :: Int -> Float -> StdGen -> Board
|
||
|
createBoard size mineRatio rng = Board size (seedGrid rng mineRatio (createGrid size)) (createGrid size) (createGrid size)
|
||
|
|
||
|
-- Creates a 2D list of booleans of given size, initialised to False
|
||
|
createGrid :: Int -> Grid
|
||
|
createGrid size = replicate size (replicate size False)
|
||
|
|
||
|
-- Seeds True statuses to a 2D grid randomly with a given probability, requires a random generator
|
||
|
seedGrid :: StdGen -> Float -> Grid -> Grid
|
||
|
seedGrid _ _ [] = []
|
||
|
seedGrid rng p (l:ls) = newL : seedGrid newRng p ls
|
||
|
where (newL, newRng) = seedList rng p l
|
||
|
|
||
|
seedList :: StdGen -> Float -> [Bool] -> ([Bool], StdGen)
|
||
|
seedList rng p (l:ls) = (newBool : seedListDiscard newRng p ls, newRng)
|
||
|
where (newBool, newRng) = randomlyTrue rng p
|
||
|
|
||
|
seedListDiscard :: StdGen -> Float -> [Bool] -> [Bool]
|
||
|
seedListDiscard _ _ [] = []
|
||
|
seedListDiscard rng p (l:ls) = newBool : seedListDiscard newRng p ls
|
||
|
where (newBool, newRng) = randomlyTrue rng p
|
||
|
|
||
|
randomlyTrue :: StdGen -> Float -> (Bool, StdGen)
|
||
|
randomlyTrue rng p = let (generatedFloat, newRng) = randomR (0.0, 1.0) rng
|
||
|
in (generatedFloat <= p, newRng)
|
||
|
|
||
|
printBoard :: Board -> String
|
||
|
printBoard b = printBoardGrid (mines b)
|
||
|
|
||
|
printBoardGrid :: Grid -> String
|
||
|
printBoardGrid [] = ""
|
||
|
printBoardGrid (l:ls) = printBoardLine l ++ "\n" ++ printBoardGrid ls
|
||
|
|
||
|
printBoardLine :: [Bool] -> String
|
||
|
printBoardLine [] = ""
|
||
|
printBoardLine (x:xs) = (if x then " x" else " .") ++ printBoardLine xs
|