Task

Write a player for the game that follows the following rules:

The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.



Related tasks

   Guess the number/With Feedback
   Bulls and cows/Player


--
-- demo\rosetta\Guess_the_number2.exw
--
with javascript_semantics -- (spacing not (yet) great...)
include pGUI.e
Ihandle lbl, guess, toohigh, too_low, correct, newgame, dlg

integer Min=0, Max=100, Guess
constant LTHINK = sprintf("Think of a number between %d and %d.",{Min,Max})

procedure set_active(bool bActive)
    IupSetInt({toohigh, too_low, correct},"ACTIVE",bActive)
    IupSetInt(newgame,"ACTIVE",not bActive)
end procedure

procedure set_guess()
    Guess = floor((Max+Min)/2)
    string title = sprintf("My guess is %d, is this too high, too low, or correct?", Guess)
    if Max<Min then
        set_active(false)
        title = "I think something is strange here..."
    end if
    IupSetStrAttribute(guess,"TITLE",title)
    IupRefresh(guess)
end procedure

function click_cb(Ihandle ih)
    switch substitute(IupGetAttribute(ih,"TITLE"),"Too ","")[1] do
        case 'H':   Max = Guess-1  set_guess()
        case 'L':   Min = Guess+1  set_guess()
        case 'C':   IupSetStrAttribute(guess,"TITLE","I did it!")
                    set_active(false)
        case 'N':   Min = 0  Max = 100  set_guess()
                    set_active(true)
    end switch
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    lbl = IupLabel(LTHINK)
    guess = IupLabel("")
    toohigh = IupButton("Too High", Icallback("click_cb"))
    too_low = IupButton("Too Low", Icallback("click_cb"))
    correct = IupButton("Correct", Icallback("click_cb"))
    newgame = IupButton("New Game", Icallback("click_cb"), "ACTIVE=NO")
    dlg = IupDialog(IupVbox({lbl,
                             guess,
                             IupHbox({toohigh,too_low,correct,newgame},
                                     "GAP=10")},
                            `NMARGIN=15x15,GAP=10`),
                    `MINSIZE=300x100,TITLE="Guess the number2"`)
    set_guess()
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure
 
main()
