minesweeper-haskell/app/Main.hs

63 lines
1.8 KiB
Haskell
Raw Normal View History

2019-12-10 00:09:55 +01:00
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
2019-11-24 02:49:57 +01:00
module Main where
import Lib
2019-12-10 00:09:55 +01:00
import Options.Generic
2019-12-04 00:13:57 +01:00
import System.Random
2019-12-07 02:51:12 +01:00
import Text.Read
2019-11-24 02:49:57 +01:00
2019-12-10 00:09:55 +01:00
data Parameters w =
Parameters
{ width :: w ::: Int <?> "Width of the board"
, length :: w ::: Int <?> "Length of the board"
, bombs :: w ::: Int <?> "Number of bombs to be placed"
}
deriving (Generic)
instance ParseRecord (Parameters Wrapped)
deriving instance Show (Parameters Unwrapped)
2019-11-24 02:49:57 +01:00
main :: IO ()
2019-12-04 00:13:57 +01:00
main = do
2019-12-10 00:09:55 +01:00
(Parameters boardWidth boardLength bombsCount) <- unwrapRecord "Minesweeper"
2019-12-04 00:13:57 +01:00
generator <- newStdGen
2019-12-07 02:51:12 +01:00
gameStep . createBoard boardWidth boardLength $
2019-12-10 00:09:55 +01:00
generateRandomCoordinates (boardWidth - 1) (boardLength - 1) bombsCount generator
2019-12-07 02:51:12 +01:00
gameStep :: Board -> IO ()
gameStep board = do
putStrLn . convertBoardToString $ board
coordinates <- getCoordinates
let nextBoard = revealTile coordinates board
if isGameLost nextBoard
then gameLost nextBoard
else if isGameWon nextBoard
then gameWon nextBoard
else gameStep nextBoard
getCoordinates :: IO (Int, Int)
getCoordinates = do
putStrLn "Enter the coordinates of the tile to reveal (X then Y, zero indexed):"
xString <- getLine
yString <- getLine
case (readMaybe xString, readMaybe yString) of
2019-12-10 00:09:55 +01:00
(Just x, Just y) -> return (x, y)
_ -> putStrLn "Invalid coordinates!" >> getCoordinates
2019-12-07 02:51:12 +01:00
gameLost :: Board -> IO ()
gameLost board = do
putStrLn . convertBoardToString . revealAll $ board
putStrLn "Boom! You lost!"
gameWon :: Board -> IO ()
gameWon board = do
putStrLn . convertBoardToString $ board
putStrLn "You won! All the bombs were found!"