Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. module Mastermind
  2. where
  3.  
  4. import System.Random
  5. import Text.Read
  6. import Data.Maybe
  7. import Data.Char
  8.  
  9. data Color = Red | Green | Blue | Yellow | Brown | Orange | Black | White deriving (Show, Read, Eq, Ord, Bounded, Enum)
  10.  
  11. type Combination = [Color]
  12.  
  13. boolToInt x = if x then 1 else 0
  14.  
  15. checkWhites:: Combination -> Combination -> Int
  16. checkWhites secret guess =
  17. sum $ fmap boolToInt $ fmap (\x -> x `elem` secret) guess
  18.  
  19. checkBlacks:: Combination -> Combination -> Int
  20. checkBlacks secret guess =
  21. let pairs = zip secret guess in
  22. sum $ fmap boolToInt $ [ x == y | (x,y) <- pairs]
  23.  
  24. check:: Combination -> Combination -> (Int, Int)
  25. check secret guess = let blacks = checkBlacks secret guess in
  26. (checkWhites secret guess -blacks, blacks)
  27.  
  28. parse:: String -> Maybe Combination
  29. parse x = sequence $ fmap (\x -> readMaybe ((toUpper $ head x) : tail x) :: Maybe Color) (words x)
  30.  
  31. guess:: Combination -> Int -> Combination -> IO ()
  32. guess secret moves guess = do
  33. let (whites, blacks) = check secret guess
  34. if blacks == length secret then
  35. putStrLn "You win! 🎉"
  36. else do
  37. putStrLn ("Result: " ++ show whites ++ " whites " ++ show blacks ++ " blacks. Moves " ++ show (moves-1))
  38. turn secret (moves-1)
  39.  
  40. takeNoRepeats:: (Eq a) => Int -> [a] -> [a] -> [a]
  41. takeNoRepeats n [] [] = []
  42. takeNoRepeats 0 x y = x
  43. takeNoRepeats n [] (h:t) = takeNoRepeats (n-1) [h] t
  44. takeNoRepeats n x (y:t)
  45. | y `elem` x = takeNoRepeats (n-1) x t
  46. | otherwise = let taken =
  47. x ++ [y]
  48. in (takeNoRepeats (n-1) taken t)
  49.  
  50. mkguess:: Combination -> Int -> IO ()
  51. mkguess secret moves = do
  52. putStrLn "\nEnter a guess:"
  53. string <- getLine
  54. let userGuess = parse string
  55. if isJust userGuess then
  56. guess secret moves (fromJust userGuess)
  57.  
  58. else
  59. turn secret moves
  60.  
  61.  
  62. randomInList:: StdGen -> [a] -> [a]
  63. randomInList gen allVals = let results = (randomRs (0, (length allVals -1)) gen)
  64. in
  65. [ allVals !! x | x <- results ]
  66.  
  67. turn:: Combination -> Int -> IO ()
  68. turn secret moves = if moves == 0 then
  69. print $ "You lose. 😭 " ++ show secret
  70. else mkguess secret moves
  71.  
  72.  
  73. mastermind:: Int -> Int -> IO()
  74. mastermind len moves = do
  75. gen <- getStdGen
  76. let allColors = [ Red .. White]
  77. putStrLn $ "Available colors: " ++ (show allColors)
  78. let secret = takeNoRepeats len [] $ randomInList gen allColors
  79. in do -- print secret
  80. turn secret moves
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement