I dont know C++, but someone's done Haskell already so I'll port my Haskell solution to Elm
{-
import System.IO (hSetBuffering, hSetEcho, stdin, BufferMode(..))
import Data.Char (toLower, isLower)
main :: IO ()
main = do hSetBuffering stdin NoBuffering
hSetEcho stdin False
hangman "supercalifragilisticexpialidocious" 7 ""
hangman :: String -> Int -> String -> IO ()
hangman secret tries gs =
let hasLost = misses > tries
-- read: all are (element of guesses) inside secret
hasWon = all (`elem` gs) secret
-- read: how many are (not element of secret) inside guesses
misses = length $ filter (`notElem` secret) gs
showGuesses = gs ++ replicate (tries - misses) '.'
showSecret = map (\c -> if c `elem` gs then c else '_') secret
showState =
if hasWon then "You won! Word was " ++ secret
else if hasLost then "You lost!"
else showSecret ++ " " ++ showGuesses
validateInput c = gs ++ (if isLower c && notElem c gs then [c] else [])
in do -- all IO is done below
putStrLn showState
if hasLost || hasWon
then return ()
else hangman secret tries . validateInput . toLower =<< getChar
-}
module Main exposing (..)
{- elm-package install elm-lang/html elm-lang/keyboard && elm-reactor -}
import Html
import Html.App as Html
import Keyboard
import Char
import List
import String
secret =
String.toList "supercalifragilisticexpialidocious"
tries =
7
hasLost model =
misses model > tries
hasWon model =
List.all (\c -> List.member c model) secret
misses model =
List.length <| List.filter (\c -> not <| List.member c secret) model
showGuesses model =
String.fromList model ++ String.repeat (tries - misses model) "."
showSecret model =
String.fromList <|
List.map
(\c ->
if List.member c model then
c
else
'_'
)
secret
showState model =
if hasWon model then
"You won! Word was " ++ String.fromList secret
else if hasLost model then
"You lost!"
else
showSecret model ++ " " ++ showGuesses model
main =
Html.program
{ init = [] ! []
, view =
\model ->
Html.text <| showState model
, update =
\msg model ->
if Char.isLower msg && not (List.member msg model) then
(model ++ [ msg ]) ! []
else
model ! []
, subscriptions =
\model ->
if hasWon model || hasLost model then
Sub.none
else
(Keyboard.downs (Char.toLower << Char.fromCode))
}
I was gonna try Prolog but I forgot I never bothered learning IO/user input in it :(