Hello everyone,
I was just playing around with Haskell and I’ve realized a simple Hangman game.
I’m very new with Haskell, so I’ve certainly made some mistakes 🙂
Here’s the code:
import System.IO revealChar (x:[]) secretWord partialWord = zipWith (\ s p -> if x == s then s else p) secretWord partialWord revealChar xs secretWord partialWord = if xs == secretWord then secretWord else partialWord getSecretWord = do sBuff <- openFile "secretWords.txt" ReadMode inpStr <- hGetLine sBuff hClose sBuff return inpStr playGame 0 secret partial = do putStrLn "I'm sorry, you have lose!" playGame t secret partial = do putStrLn $ "=> " ++ partial putStrLn $ "Tell the a single letter or the entire word. " ++ (show t) ++ " tries left." charStr <- getLine if secret == partial then putStrLn "You have win!" else playGame (t-1) secret (revealChar charStr secret partial) main = do secretWord <- getSecretWord let partialWord = foldl1 (++) (replicate (length secretWord) "_") putStrLn "Welcome to the useless Hangman Game!" putStrLn ("Today's word is: " ++ partialWord) playGame (length partialWord) secretWord partialWord</pre>
I must confess, I begin to like Haskell and his weird syntax. This version is very readable and compact in my opinion. There are some tricks of FP I want to show you in this code:
- The pattern matching magic allows the revealChar function to be reusable to both guess entire word or check a single character. Maybe revealChar it’s a violation of the FP pure functions?
- Anonimous functions are in my opinion a very elegant way to make your code smaller and cleaner.
- The secret word is stored in a separate file, so no spoiler at all 🙂
- You can run this saving it into a .hs file and running runghc <yourfile>
I’m looking forward to go deeper in Haskell 🙂
Bye,
Alfredo