Created
April 19, 2021 12:46
-
-
Save bennypowers/f27ef46ce83c6feea528d0a19633893d to your computer and use it in GitHub Desktop.
Starman game from Functional Programming in Haskell Course at U of Glasgow, Slightly Improved
This file contains 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 System.IO | |
import System.Random | |
-- The game | |
check :: String -> String -> Char -> (Bool,String) | |
check word display c = | |
(c `elem` word, | |
[if x == c then c else y | (x, y) <- zip word display]) | |
outcome :: String -> String -> String | |
outcome word x = "You " ++ x ++ "! The word was " ++ word | |
turn :: String -> String -> Int -> IO () | |
turn word display n | |
| n == 0 = putStrLn $ outcome word "lose" | |
| word == display = putStrLn $ outcome word "win" | |
| otherwise = | |
mkguess word display n | |
mkguess :: String -> String -> Int -> IO () | |
mkguess word display n = | |
do putStrLn (display ++ " " ++ replicate n '*') | |
putStr " Enter your guess: " | |
q <- getLine | |
let (correct, display') = check word display (head q) | |
let n' = if correct then n else n-1 | |
turn word display' n' | |
starman :: String -> Int -> IO () | |
starman word = turn word ['-' | _ <- word] | |
-- IO | |
main :: IO () | |
main = do | |
handle <- openFile "dictionary.txt" ReadMode | |
dict <- hGetContents handle | |
let size = length $ lines dict | |
idx <- getStdRandom (randomR (0, size)) | |
let word = lines dict !! idx | |
starman (head (words word)) 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment