Guest User

Rock Paper Scissors: Interactive

a guest
Jan 19th, 2012
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import qualified System.Random as R
  2. import Control.Applicative ((<*>), (<$>), pure)
  3. import Control.Monad.State (State, state, evalState)
  4. import Control.Arrow (first)
  5.  
  6. data RPS = Rock | Paper | Scissors deriving (Eq, Show, Read)
  7. type Score = (Int, Int)
  8.  
  9. instance R.Random RPS where
  10.     random = first pick . R.randomR (0,2)
  11.         where pick :: Int -> RPS
  12.               pick 0 = Rock
  13.               pick 1 = Paper
  14.               pick 2 = Scissors
  15.     randomR = error "Unsupported data type"
  16.  
  17. newGame :: Score
  18. newGame = (0,0)
  19.  
  20. beats :: RPS -> RPS -> Bool
  21. beats Rock Scissors  = True
  22. beats Paper Rock     = True
  23. beats Scissors Paper = True
  24. beats _ _ = False
  25.  
  26. play :: RPS -> RPS -> Score -> Score
  27. play ca cb (sa,sb)
  28.     | ca `beats` cb = (sa+1, sb)
  29.     | cb `beats` ca  = (sa, sb+1)
  30.     | otherwise     = (sa, sb)
  31.  
  32. getChoice :: IO RPS
  33. getChoice = fmap read getLine
  34.  
  35. getRandom :: IO RPS
  36. getRandom = do c <- R.randomIO
  37.                putStrLn $ "PC picked " ++ show c
  38.                return c
  39.  
  40. playRound :: Score -> IO Score
  41. playRound s = play <$> getChoice <*> getRandom <*> pure s
  42.  
  43. playLoop :: Score -> IO Score
  44. playLoop s = do r <- playRound s
  45.                 print r
  46.                 playLoop r
  47.  
  48. main = playLoop newGame
Advertisement
Add Comment
Please, Sign In to add comment