- Hangman With Haskell
- Imports
- How to play:
- Enter secret word
- sgetLine function
- getCh function
- play function
- match function
Basics of IO programming using a variant of the game Hangman.
import System.IO
- One player secretly enter a word.
- Another player then tries to deduce the word via a series of guesses.
- For each guess, we indicate which letter in the secret word occur in the guess.
- The game end when the guess is correct.
The game will be in a top-down manner:
- Prompts first player to enter the secret word.
- Then ask the second player to guess it.
hangman :: IO ()
hangman = do putStrLn "Think of a word:"
word <- sgetLine
putStrLn "Try to guess it:"
play word
Reads string from keyboard and echos each characters dash symbol โ-โ.
sgetLine = do x <- getCh
if x == '\n' then
do putChar x
return []
else
do putChar '-'
xs <- sgetLine
return (x:xs)
Reads single character from the keyboard without echoing it to the screen.
getCh :: IO Char
getCh = do hSetEcho stdin False
x <- getChar
hSetEcho stdin True
return x
Main loop game.
play :: String -> IO ()
play word = do putStr "? "
guess <- getLine
if guess == word then
putStrLn "You got it!!"
else
do putStrLn (match word guess)
play word
Using list comprehension to indicate which letters is the secret word occur anywhere in the guess.
match :: String -> String -> String
match xs ys = [if elem x ys then x else '-' | x <- xs]