Created
September 2, 2018 15:01
-
-
Save macabeus/38819a4c26cff243cadce18f67228041 to your computer and use it in GitHub Desktop.
Hangman game written in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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