Skip to content

Instantly share code, notes, and snippets.

@pragdave
Last active March 16, 2021 00:47
Show Gist options
  • Select an option

  • Save pragdave/9abb976d1fec651a4a7c53fa23b8f0b9 to your computer and use it in GitHub Desktop.

Select an option

Save pragdave/9abb976d1fec651a4a7c53fa23b8f0b9 to your computer and use it in GitHub Desktop.

Revisions

  1. pragdave renamed this gist Mar 14, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. pragdave created this gist Mar 14, 2021.
    66 changes: 66 additions & 0 deletions Baby's first hangman
    Original 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