Skip to content

Instantly share code, notes, and snippets.

@jackdalton
Last active March 24, 2016 03:24
Show Gist options
  • Save jackdalton/491f95ba88d6df6cfe91 to your computer and use it in GitHub Desktop.
Save jackdalton/491f95ba88d6df6cfe91 to your computer and use it in GitHub Desktop.
Haskell rock paper scissors game
import System.IO.Unsafe
import System.Random
-- take user input for their choice
-- random number for computer choice
-- return outcome
moves :: [String]
moves = [ "rock"
, "paper"
, "scissors" ]
cChoice :: String
cChoice = moves!!unsafePerformIO (getStdRandom (randomR (0, 2)))
getOut :: String -> String -> String
getOut u c
| u == c = draw
| u == "rock" && c == "paper" = cWin
| u == "rock" && c == "scissors" = uWin
| u == "paper" && c == "rock" = uWin
| u == "paper" && c == "scissors" = cWin
| u == "scissors" && c == "rock" = cWin
| u == "scissors" && c == "paper" = uWin
| otherwise = err
where
draw = "Draw! You both picked " ++ u ++ "."
uWin = "You win! You picked " ++ u ++ " while the computer picked " ++ c ++ "."
cWin = "You lost! You picked " ++ u ++ " while the computer picked " ++ c ++ "."
err = "Error: that move doesn't exist."
main :: IO ()
main = do
putStrLn "Do you pick rock, paper, or scissors?"
uChoice <- getLine
putStrLn (getOut uChoice cChoice)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment