Last active
March 16, 2021 00:47
-
-
Save pragdave/9abb976d1fec651a4a7c53fa23b8f0b9 to your computer and use it in GitHub Desktop.
Revisions
-
pragdave renamed this gist
Mar 14, 2021 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
pragdave created this gist
Mar 14, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ import Data.List (sort, intersperse, union) import Data.Function ( (&) ) import System.Random (Random(randomRIO)) (|>) = (&) -- 'cos I'm too old to switch... pickRandomWord :: [ String ] -> IO String pickRandomWord words = do rand <- randomRIO (0, length words - 1) return (words !! rand) displayLetter :: String -> Char -> Char displayLetter guessed letter | letter `elem` guessed = letter | otherwise = '_' summaryLine :: String -> String -> Int -> String summaryLine secret guessed turnsLeft = "\n" ++ wordTemplate ++ turnsLeftMsg ++ "\n" ++ alreadyGuessedMsg where wordTemplate = secret |> map (displayLetter guessed) |> intersperse ' ' turnsLeftMsg = " (turns left: " ++ show turnsLeft ++ ")" alreadyGuessedMsg = "Guessed so far: " ++ guessed |> sort |> intersperse ' ' scoreGuess :: String -> String -> Int -> Char -> IO () scoreGuess secret guessed turnsLeft guess | guess `elem` guessed = do putStrLn $ "You've already guessed " ++ show guess playGame secret guessed turnsLeft | guess `elem` secret = do putStrLn "Good guess!" playGame secret (guess:guessed) turnsLeft | otherwise = playGame secret (guess:guessed) (turnsLeft - 1) playGame :: String -> String -> Int -> IO () playGame secret guessed turnsLeft | turnsLeft == 0 = do putStrLn $ "Sorry, the word was: " ++ secret | guessed `union` secret == guessed = do putStrLn $ "Congratulations! The word was " ++ secret | otherwise = do summaryLine secret guessed turnsLeft |> putStrLn putStr "Your guess: " guess <- getLine scoreGuess secret guessed turnsLeft (head guess) main :: IO () main = do dictionary <- readFile "../assets/17kwords.txt" let words = lines dictionary secret <- pickRandomWord words playGame secret [] 8