Guest User

Untitled

a guest
May 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. {-# LANGUAGE TemplateHaskell #-}
  2. import Control.Applicative
  3. import Control.Lens hiding (op)
  4. import Control.Monad
  5. import Control.Monad.State
  6. import Data.Char
  7. import System.IO
  8. import System.Random
  9.  
  10. data Game = Game { _values :: [Int], _right :: Int, _rounds :: Int }
  11. makeLenses ''Game
  12.  
  13. gameLoop :: StateT Game IO ()
  14. gameLoop = do
  15. flushPut "Would you like to play? y/n: "
  16. keepPlaying <- ("y" ==) . map toLower <$> liftIO getLine
  17. when keepPlaying $ do
  18. (x:y:r:_) <- values <<%= drop 3
  19. numRounds <- rounds <+= 1
  20.  
  21. let (solution, opStr) = [(x + y, "+") , (x - y, "-")] !! (r `mod` 2)
  22. flushPut $ unwords ["What is", show x, opStr, show y, "? "]
  23. correct <- (solution ==) <$> liftIO readLn
  24. numRight <- right <+= if correct then 1 else 0
  25.  
  26. liftIO . putStrLn $ unwords [message solution correct,
  27. "\nYou have solved", show numRight, "out of", show numRounds]
  28. gameLoop
  29. where
  30. flushPut = liftIO . (>> hFlush stdout) . putStr
  31. message _ True = "Correct!"
  32. message soln _ = unwords ["Sorry! the correct answer is:", show soln]
  33.  
  34. main :: IO ()
  35. main = do
  36. randomValues <- randomRs (1,100) <$> getStdGen
  37. evalStateT gameLoop (Game randomValues 0 0)
Add Comment
Please, Sign In to add comment