Last active
June 3, 2021 17:07
-
-
Save wout/f99d3878055a867a975e751001aa3418 to your computer and use it in GitHub Desktop.
Haskellmind: A Haskell CLI implementation of Mastermind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Random | |
import Data.Char (isDigit) | |
makeCode :: IO [Char] | |
makeCode = do | |
gen <- newStdGen | |
return $ take 4 (randomRs ('0','9') gen) | |
breakCode :: String -> Int -> IO () | |
breakCode code turns = do | |
putStrLn $ " Turns left: " ++ show turns | |
answer <- getLine | |
if length answer /= 4 || not (all isDigit answer) | |
then requireValidInput code answer turns | |
else provideFeedback code answer turns | |
provideFeedback :: String -> String -> Int -> IO () | |
provideFeedback code guess turns = do | |
let rest = filter (\(x,y) -> x /= y) (zip guess code) | |
let correct = (length code) - (length rest) | |
let present = length (filter (\(x,y) -> x `elem` code) rest) | |
putStr " Feedback: " | |
putStr (take correct (repeat '●')) | |
putStr (take present (repeat '○')) | |
putStrLn (take ((length code) - correct - present) (repeat '-')) | |
turn code guess (turns - 1) | |
requireValidInput :: String -> String -> Int -> IO () | |
requireValidInput code guess turns = do | |
putStrLn " Oops, answer must be four numbers" | |
turn code guess turns | |
turn :: String -> String -> Int -> IO () | |
turn code guess turns = do | |
if turns == 0 | |
then putStrLn "You lose" | |
else if code == guess | |
then putStrLn "You win!" | |
else breakCode code turns | |
haskellmind :: IO () | |
haskellmind = do | |
let turns = 12 | |
code <- makeCode | |
turn code ['-' | x <- code] turns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment