数字猜测游戏错误和保持猜测的数量

时间:2016-05-06 21:08:37

标签: haskell random io

我正在Haskell做一个猜数游戏,我有3个困难 我做了一个菜单,用户选择了什么难度,但是一旦我实施了它,它开始给我一个错误,我无法弄清楚它是什么。
错误:

finalename.hs:5:10:
Parse error in pattern: putStrLn
Possibly caused by a missing 'do'?

另外,如何计算用户猜测所需数量的计数?

import System.Random (randomRIO)     
main :: IO ()
main = do
     putStrLn "Do you want to play 1) Easy, 2) Medium or 3) Hard"
     putStrLn "Select your difficulty by entering a number 1, 2 or 3"
     choice <- readLn
       | choice == 1 = "You selected easy" >> easy
       | choice == 2 = "You selected medium" >> medium
       | choice == 3 = "You selected hard" >> hard
       | otherwiose = "You did not selected a valid choice" >> main

easy :: IO ()
easy = do
     putStrLn "Guess a number between 1 and 13: "
     rNumber <- randomRIO (1, 10) :: IO Int
     loop rNumber

medium :: IO ()
medium = do
     putStrLn "Guess a number between 1 and 25: "
     rNumber <- randomRIO (1, 25) :: IO Int
     loop rNumber

hard :: IO ()
hard = do
     putStrLn "Guess a number between 1 and 50: "
     rNumber <- randomRIO (1, 50) :: IO Int
     loop rNumber

loop :: Int -> IO ()
loop rNumber = do
       userInput <- readLn 
       case compare rNumber userInput of
         EQ -> putStrLn "Correct!" >> main
         LT -> putStrLn "Guess is too low, try again please" >> loop rNumber
         GT -> putStrLn "Guess is too high, try again please" >> loop rNumber

1 个答案:

答案 0 :(得分:3)

您需要更改loop功能,以跟踪猜测的数字和猜测的数量:

loop :: Int -> Int -> IO ()
loop rNumber guesses = do
  putStrLn $ "You have made " ++ show guesses ++ " guesses so far."
  ...
  putStrLn "Too low, guess again"
  loop rNumber (guesses+1)
  ...
  putStrLn "To high, guess again"
  loop rNumber (guesses+1)

请注意,当您以递归方式调用loop时,您可以通过传入旧的猜测次数+ 1来更改猜测次数。