Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {-# LANGUAGE TemplateHaskell #-}
- import Control.Applicative
- import Control.Lens hiding (op)
- import Control.Monad
- import Control.Monad.State
- import Data.Char
- import System.IO
- import System.Random
- data Game = Game { _values :: [Int], _right :: Int, _rounds :: Int }
- makeLenses ''Game
- gameLoop :: StateT Game IO ()
- gameLoop = do
- flushPut "Would you like to play? y/n: "
- keepPlaying <- ("y" ==) . map toLower <$> liftIO getLine
- when keepPlaying $ do
- (x:y:r:_) <- values <<%= drop 3
- numRounds <- rounds <+= 1
- let (solution, opStr) = [(x + y, "+") , (x - y, "-")] !! (r `mod` 2)
- flushPut $ unwords ["What is", show x, opStr, show y, "? "]
- correct <- (solution ==) <$> liftIO readLn
- numRight <- right <+= if correct then 1 else 0
- liftIO . putStrLn $ unwords [message solution correct,
- "\nYou have solved", show numRight, "out of", show numRounds]
- gameLoop
- where
- flushPut = liftIO . (>> hFlush stdout) . putStr
- message _ True = "Correct!"
- message soln _ = unwords ["Sorry! the correct answer is:", show soln]
- main :: IO ()
- main = do
- randomValues <- randomRs (1,100) <$> getStdGen
- evalStateT gameLoop (Game randomValues 0 0)
Add Comment
Please, Sign In to add comment