Skip to content

Instantly share code, notes, and snippets.

@macabeus
Created September 2, 2018 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macabeus/38819a4c26cff243cadce18f67228041 to your computer and use it in GitHub Desktop.
Save macabeus/38819a4c26cff243cadce18f67228041 to your computer and use it in GitHub Desktop.
Hangman game written in Haskell
import qualified Data.Set as Set
import Data.Random
import Data.Random.Extras
data State = State { word :: String, typed :: [Char] }
randomWords :: [String]
randomWords = ["banana", "uva", "abacaxi"]
getRandomWord :: IO String
getRandomWord = runRVar (choice randomWords) StdRandom
-- Logic
charState :: (Char, [Char]) -> Char
charState (char, typedChars)
| char `elem` typedChars = char
| otherwise = '_'
isEndGame :: State -> Bool
isEndGame (State { word = w, typed = t }) = do
Set.fromList w `Set.isSubsetOf` Set.fromList t
-- IO
showWordGame :: (String, [Char]) -> [Char]
showWordGame (word, tc) = map(\x -> charState(x, tc)) word
printWordGame :: (String, [Char]) -> IO ()
printWordGame (word, tc) = print(showWordGame (word, tc))
printState :: State -> IO ()
printState (State { word = w, typed = t }) = do
printWordGame(w, t)
print(["Chars typeds: ", t])
print("Is end of game?")
print(isEndGame State {word = w, typed = t})
-- gameLoop
gameLoop :: State -> IO ()
gameLoop (State { word = w, typed = t }) = do
input <- getLine
printState(State {word = w, typed = head input : t})
gameLoop (State {word = w, typed = head input : t})
main = do
w <- getRandomWord
let initialState = State {word = w, typed = []}
printState initialState
gameLoop initialState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment