Skip to content

Instantly share code, notes, and snippets.

@Sasszem
Last active December 16, 2020 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sasszem/4679c5fbba48db8f316440f657f5e459 to your computer and use it in GitHub Desktop.
Save Sasszem/4679c5fbba48db8f316440f657f5e459 to your computer and use it in GitHub Desktop.
Super-simple number guessing game in Haskell. Took me a day or so to make... Needs 'random' package!
import Text.Read (readMaybe)
import System.Random
import System.IO
readGuess :: Integer -> IO Integer
readGuess no = do
let str = "Please enter your " ++ show no ++ "th guess:"
putStr str
hFlush stdout -- need that coz we don't print a \n
name <- getLine
case readMaybe name of
Just x -> return x
Nothing -> putStrLn "That's not a number!" >> readGuess no
getMessage x cnt
| x>0 = "That's too big"
| x<0 = "That's too small!"
| x==0 = "Congratulations, you won!\nNo. of tries: " ++ show cnt
doGuess :: Integer -> Integer -> IO Integer
doGuess secret count = do
x<-readGuess count
let d = x - secret
putStrLn $ getMessage d count
case d of
y | y == 0 -> return 0
otherwise -> doGuess secret (count+1)
main = do
secretRaw <- randomIO
let secret = (mod secretRaw 100) + 1
putStrLn "I picked a random number between 1 and 100. Can you guess it?"
doGuess secret 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment