app-2: Guess a number between 1 and MAX_VALUE (Code)

by shian ⌂ @, Israel, Friday, February 07, 2020, 11:06 (19 days ago) @ shian


-- app-2: Guess a number between 1 and MAX_VALUE


-- include the standard routine 'prompt_number()' from library get.e
include get.e


-- constants are read-only variables (usually using capital letters)

-- you can set the maximum (integer) value from 1 to 1073741823
constant MAX_VALUE = 1000

-- create a random number (integer) between 1 to MAX_VALUE
constant SECRET_NUMBER = rand(MAX_VALUE)


constant TRUE = 1, -- in Euphoria FALSE is 0; TRUE is 1 (or non-zero)
       SCREEN = 1  -- the screen device-number is always 1


-- these are variables (not constants)
sequence prompt -- sequence is a sequence of numbers (see manual)
atom number     -- atom is any number
integer counter -- integer is a fast (but limited) atom

counter = 0     -- initialize the counter for user's guesses


-- clean the hostile black-box
clear_screen()


-- run the program in an endless loop (TRUE is always true...),
-- until user find the secret number.
-- (control-C will stop the program. In Linux use control-D to stop.)
while TRUE do

    -- prompt the user to enter a number (sprintf() and printf() are used
    -- to format numbers and convert numbers to strings)

    prompt = sprintf("Guess a number between 1 to %d: ", MAX_VALUE)
    number = prompt_number(prompt, {1, MAX_VALUE})

    -- round down the user's number, e.g. 1.34 --> 1
    number = floor(number)

    -- test the user's guess
    if number > SECRET_NUMBER then
        puts(SCREEN, "\tToo high!\n\n") -- ( '\t' is tab character )

    elsif number < SECRET_NUMBER then
        puts(SCREEN, "\tToo low!\n\n")  -- ( '\n' is new-line character )

    else -- number = SECRET_NUMBER
        puts(SCREEN, "\n---------------------------------------\n")

        printf(SCREEN,
            "Congratulations! the secret number is %d.\n\n", SECRET_NUMBER)

        printf(SCREEN,
            "But you know... you've missed %d times... just for the record.\n",
            counter)

            exit -- exit the while-loop (end of program)
    end if

    -- OK, user is wrong again... add 1 to counter
    counter = counter + 1   -- ( counter += 1 )
end while

-- end of program.

--
"Everyone knows the truth about himself, except the fool who considers himself wise". (www.y-dat.com).


Complete thread:

 RSS Feed of thread

powered by my little forum