Task

Write a game (computer program) that follows the following rules:

 The computer chooses a number between given set limits.
 The player is asked for repeated guesses until the the target number is guessed correctly
 At each guess, the computer responds with whether the guess is:
 higher than the target,
 equal to the target, 
 less than the target,   or
 the input was inappropriate. 


Related task

   Guess the number/With Feedback (Player)


read_number = proc (prompt: string) returns (int)
    po: stream := stream$primary_output()
    pi: stream := stream$primary_input()
    while true do   
        stream$puts(po, prompt)
        return(int$parse(stream$getl(pi)))
        except when bad_format:
            stream$putl(po, "Invalid number.")
        end
    end
end read_number
 
read_limits = proc () returns (int,int)
    po: stream := stream$primary_output()
    while true do   
        min: int := read_number("Lower limit? ")
        max: int := read_number("Upper limit? ")
        if min >= 0 cand min < max then return(min,max) end
        stream$putl(po, "Invalid limits, try again.")
    end 
end read_limits
 
read_guess = proc (min, max: int) returns (int)
    po: stream := stream$primary_output()
    while true do
        guess: int := read_number("Guess? ")
        if min <= guess cand max >= guess then return(guess) end
        stream$putl(po, "Guess must be between " 
                || int$unparse(min) || " and " || int$unparse(max) || ".")
    end
end read_guess
 
play_game = proc (min, max, secret: int)
    po: stream := stream$primary_output()
    guesses: int := 0
    while true do
        guesses := guesses + 1
        guess: int := read_guess(min, max)
        if guess = secret then break
        elseif guess < secret then stream$putl(po, "Too low!")
        elseif guess > secret then stream$putl(po, "Too high!")
        end
    end
    stream$putl(po, "Correct! You got it in " || int$unparse(guesses) || " tries.")
end play_game
 
start_up = proc ()
    po: stream := stream$primary_output()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))
 
    stream$putl(po, "Guess the number\n----- --- ------\n")
    min, max: int := read_limits()
    secret: int := min + random$next(max - min + 1)
    play_game(min, max, secret)
end start_up