…aaaand we’re back. Sorry for the delay, life can get really busy. In yesterday’s Programming Praxis problem we have to create a program that will answer guesses for the game Master Mind. Let’s get to it, shall we?
As usual, some imports:
import Data.List import System.Random
First, we need a function to determine how good the player’s guess was:
match :: [Int] -> [Int] -> String match code guess = concat $ zipWith replicate [bs, ws, ds] "BW." where bs = length . filter id $ zipWith (==) code guess ds = length (foldr delete code guess) ws = length code - bs - ds
Next, we write the guess loop:
go :: [Int] -> IO () go code = do hits <- fmap (match code) readLn if all (== 'B') hits then putStrLn "You Win!" else putStr (hits ++ "\nTry again: ") >> go code
A game can be started either with a predefined code or a random one if none has been provided.
play :: Maybe [Int] -> IO () play code = do putStr "Enter your guess as a list: " rnd <- fmap (take 4 . randomRs (1, 8)) getStdGen go $ maybe rnd id code
To test, start a game with a random code:
main :: IO () main = play Nothing
And that’s it for this week. Have fun playing!