-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.hs
73 lines (64 loc) · 2.48 KB
/
hangman.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
module Hangman where
import Data.Char
import Data.List
hangman :: IO ()
hangman = do
putStrLn "Enter your secret word: "
word <- getWord
putStrLn $ replicate 255 '\n'
play word (confuscate (length word)) 5
getWord :: IO String
getWord = do
word <- ((map toLower) . head . words) <$> getLine
if not $ all (isAlpha) word
then do
putStrLn "Invalid word, please enter again: "
getWord
else
return word
type Life = Int
confuscate :: Int -> String
confuscate n = replicate n '-'
unconfuscate :: [Int] -> Char -> String -> String
unconfuscate [] char confuscated = confuscated
unconfuscate (x:xs) char confuscated = take x confuscated ++ [char] ++
unconfuscate (map (\y -> y - x - 1 ) xs) char (drop (x+1) confuscated)
play :: String -> String -> Life -> IO ()
play _ _ 0 = putStrLn "Unfortunately, you haven't managed to guess the magic word"
play password confuscated life = do
putStrLn confuscated
putStrLn $ show life ++ "/" ++ show 5 ++ " HP left"
putStrLn "Try to guess a character: "
char <- guess
result <- process char password confuscated
case result of
Nothing -> do
putStrLn "You've lost 1 HP!"
play password confuscated (life - 1)
Just occurences -> do
let revealed = unconfuscate occurences char confuscated
if revealed == password then do
putStrLn $ "The answer is " ++ password
putStrLn "You guesed the password and won the game!"
else play password revealed life
indices :: (Eq a) => a -> [a] -> [Int]
indices y xs = [i | (x, i) <- zip xs [0,1..], x == y]
guess :: IO Char
guess = do
char <- toLower <$> getChar
if not $ isAlpha char
then do
putStrLn "Invalid character, please try again: "
guess
else
return char
process :: Char -> String -> String -> IO (Maybe [Int])
process char password confuscated = let occurences = indices char password in
if null occurences then do
putStrLn "The following char doesn't occur"
return Nothing
else if char `elem` confuscated then do
putStrLn "You already guessed this character"
return Nothing
else
return (Just occurences)