Initial commit

This commit is contained in:
Paul-Henri Froidmont 2019-11-24 02:49:57 +01:00 committed by Paul-Henri Froidmont
commit 4e77f37a5f
9 changed files with 289 additions and 0 deletions

66
src/Lib.hs Normal file
View file

@ -0,0 +1,66 @@
module Lib
( flagTile
, printBoard
, Board(..)
, Tile(..)
, TileState(..)
) where
newtype Board =
Board
{ unBoard :: [[Tile]]
}
deriving (Eq, Show)
data Tile
= Value Int TileState
| Bomb TileState
deriving (Eq, Show)
data TileState
= Revealed
| Flagged
| Hidden
deriving (Eq, Show)
type Coordinates = (Int, Int)
flagTile :: Board -> Coordinates -> Board
flagTile (Board board) (x, y) =
case findTile (Board board) (x, y) of
(Just tile) -> flagHiddenTile tile
Nothing -> Board board
where
flagHiddenTile (Value value Hidden) = replaceTile (Board board) (x, y) (Value value Flagged)
flagHiddenTile (Bomb Hidden) = replaceTile (Board board) (x, y) (Bomb Flagged)
flagHiddenTile _ = Board board
replaceTile :: Board -> Coordinates -> Tile -> Board
replaceTile (Board board) (x, y) tile =
let (firstRows, line:lastRows) = splitAt y board
(firstTiles, _:lastTiles) = splitAt x line
in Board $ firstRows ++ (firstTiles ++ tile : lastTiles) : lastRows
findTile :: Board -> Coordinates -> Maybe Tile
findTile (Board board) (x, y) =
if not (coordinatesExists (Board board) (x, y))
then Nothing
else Just $ board !! y !! x
coordinatesExists :: Board -> Coordinates -> Bool
coordinatesExists (Board board) (x, y) = isPositive && isYWithinTheBoard board && isXWithinTheBoard board
where
isPositive = x >= 0 && y >= 0
isYWithinTheBoard = (> y) . length
isXWithinTheBoard = any ((> x) . length)
printBoard :: Board -> String
printBoard (Board board) = concatMap printLine board
where
printLine line = concatMap printTile line ++ "\n"
printTile (Bomb Hidden) = "#"
printTile (Bomb Revealed) = "B"
printTile (Value _ Hidden) = "#"
printTile (Value x Revealed) = show x
printTile (Bomb Flagged) = "F"
printTile (Value _ Flagged) = "F"