-- hangman game -- Lecture 3B part 2, 2016 -- David Sands import System.Random(randomRIO) import Data.List(nub) -- Constants guessLimit :: Int guessLimit = 6 -- number of guesses before you lose dict :: FilePath dict = "/usr/share/dict/words" -- mac OS X only dictLength :: Int dictLength = 235886 -- we could calculate this though -- Non IO part. Some useful functions. -- Given a word and a list of guesses: showWord :: String -> String -> String showWord w gs = [ reveal c | c <- w] where reveal c | c `elem` gs = c | otherwise = '_' lives :: String -> String -> Int lives w gs = guessLimit - length badGuesses where badGuesses = nub [c | c <- gs, c `notElem` w] won,lost :: String -> String -> Bool won w gs = '_' `notElem` showWord w gs lost w gs = lives w gs == 0 -- IO part main :: IO() main = do w <- randomWord play w [] -- get a random word from the dictionary -- start the first round of the game -- with the word and randomWord :: IO String randomWord = do s <- readFile dict i <- randomRIO(0,dictLength-1) return (words s !! i) play :: String -> String -> IO() play w gs | won w gs = putStrLn "Yay you won!" | lost w gs = putStrLn ("You lost. The word was: " ++ w) | otherwise = do putStrLn ("Lives: " ++ show(lives w gs) ) putStrLn (showWord w gs) putStr "Type your next guess: " s <- getLine play w (take 1 s ++ gs) -- A round of the game: -- if player had neither won nor lost -- print number of lives -- print word skeleton -- get a new guess from player -- start next round