; file:   gui-enable.lsp
; url:    http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
; author: oofoe 2012-02-02

; Load library and initialize GUI server:
(load (append (env "NEWLISPDIR") "/guiserver.lsp"))
(gs:init)

; The "interlock" function maintains GUI consistency by disabling all
; controls, then selectively re-enabling them depending on the value
; in the textbox.
(define (interlock)
  (gs:disable 'value 'increment 'decrement)
  (let ((v (int (gs:get-text 'value))))
    (if (= 0 v)  (gs:enable 'value))
    (if (< v 10) (gs:enable 'increment))
    (if (< 0 v)  (gs:enable 'decrement))
    ))

; Callbacks.
(define (update f)
  (gs:set-text 'value (string (f (int (gs:get-text 'value)) 1)))
  (interlock))

(define (incrementing id) (update +))

(define (decrementing id) (update -))

(define (valuing id)      (interlock))

; Create main window frame and set layout direction.
(gs:frame 'main 100 100 200 75 "GUI Enable")
(gs:set-flow-layout 'main "center" 4 4)

; Create and add widgets.
(gs:button 'decrement 'decrementing "-" 30)
(gs:text-field 'value 'valuing 8)
(gs:set-text 'value "0")
(gs:button 'increment 'incrementing "+" 30)
(gs:add-to 'main 'decrement 'value 'increment)

; Show main window.
(gs:set-visible 'main true)

; Start event loop.
(gs:listen)

(exit)


import gtk2, strutils, glib2

var valu: int = 0

proc thisDestroy(widget: PWidget, data: Pgpointer){.cdecl.} =
  main_quit()

nim_init()
var window = window_new(gtk2.WINDOW_TOPLEVEL)
var content = vbox_new(true,10)
var hbox1 = hbox_new(true,10)
var entry_fld = entry_new()
entry_fld.set_text("0")
var btn_quit = button_new("Quit")
var btn_inc = button_new("Increment")
var btn_dec = button_new("Decrement")
add(hbox1,btn_inc)
add(hbox1,btn_dec)
pack_start(content, entry_fld, true, true, 0)
pack_start(content, hbox1, true, true, 0)
pack_start(content, btn_quit, true, true, 0)
set_border_width(window, 5)
add(window, content)

proc thisCheckBtns =
   set_sensitive(btn_inc, valu < 10)
   set_sensitive(btn_dec, valu > 0)
   set_sensitive(entry_fld, valu == 0)

proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =
  inc(valu)
  entry_fld.set_text($valu)
  thisCheckBtns()

proc thisDec(widget: PWidget, data: Pgpointer){.cdecl.} =
  dec(valu)
  entry_fld.set_text($valu)
  thisCheckBtns()

proc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} =
  try:
     valu = parseInt($entry_fld.get_text())
  except ValueError:
     entry_fld.set_text($valu)
  thisCheckBtns()

discard signal_connect(window, "destroy",
                   SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_quit, "clicked",
                   SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_inc, "clicked",
                   SIGNAL_FUNC(thisInc), nil)
discard signal_connect(btn_dec, "clicked",
                   SIGNAL_FUNC(thisDec), nil)
discard signal_connect(entry_fld, "changed",
                   SIGNAL_FUNC(thisTextChanged), nil)

show_all(window)
thisCheckBtns()
main()


#!/usr/bin/perl

use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;

my $value = 0;

my $mw = MainWindow->new;
$mw->title( 'GUI component enable/disable' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
my $entry = $lf->Entry( -width => 10, -textvariable => \$value,
  -validate => 'key', -validatecommand => sub {
  $_[0] =~ /^\d{1,9}\z/ ? do{setenable($_[0]); 1} : 0
  },
  )->pack(-fill => 'x', -expand => 1);
my $inc = $mw->Button( -text => 'increment',
  -command => sub { $value++; setenable($value) },
  )->pack( -side => 'left' );
my $dec = $mw->Button( -text => 'decrement',
  -command => sub { $value--; setenable($value) },
  )->pack( -side => 'right' );

setenable($value);

MainLoop;

sub setenable
  {
  $inc and $inc->configure( -state => $_[0] < 10 ? 'normal' : 'disabled' );
  $dec and $dec->configure( -state => $_[0] > 0 ? 'normal' : 'disabled' );
  $entry and $entry->configure( -state => $_[0] == 0 ? 'normal' : 'disabled' );
  }


include pGUI.e

Ihandle txt, inc, dec, hbx, vbx, dlg

function activate(integer v)
    IupSetInt(txt,"VALUE",v)
    IupSetAttribute(inc,"ACTIVE",iff(v<10,"YES":"NO"))
    IupSetAttribute(dec,"ACTIVE",iff(v>0,"YES":"NO"))
    IupSetAttribute(txt,"ACTIVE",iff(v=0,"YES":"NO"))
    return IUP_CONTINUE
end function

function valuechanged_cb(Ihandle /*ih*/)
    return activate(IupGetInt(txt,"VALUE"))
end function

function inc_cb(Ihandle /*ih*/)
    return activate(IupGetInt(txt,"VALUE")+1)
end function

function dec_cb(Ihandle /*ih*/)
    return activate(IupGetInt(txt,"VALUE")-1)
end function

function esc_close(Ihandle /*ih*/, atom c)
    return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE)
end function

IupOpen()
txt = IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"FILTER=NUMBER, EXPAND=YES")
inc = IupButton("increment",Icallback("inc_cb"))
dec = IupButton("decrement",Icallback("dec_cb"),"ACTIVE=NO")
hbx = IupHbox({inc,dec},"MARGIN=0x10, GAP=20")
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
dlg = IupDialog(vbx)
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")

(de start ()
   (and (app) (zero *Number))
   (action
      (html 0 "Enable/Disable" "@lib.css" NIL
         (form NIL
            (gui '(+Var +Able +NumField) '*Number '(=0 *Number) 20 "Value")
            (gui '(+Able +JS +Button) '(> 10 *Number) "increment"
               '(inc '*Number) )
            (gui '(+Able +JS +Button) '(gt0 *Number) "decrement"
               '(dec '*Number) ) ) ) ) )

(server 8080 "!start")
(wait)


dialog('GUI_Interaction',
       [ object        :=
	   GUI_Interaction,
	 parts         :=
	   [ GUI_Interaction :=
	       dialog('Rosetta Code'),
	     Name      := label(name, 'Value :'),
	     Input_field     :=
	       text_item(input_field, '0'),
	     Increment       :=
	       button(increment),
	     Decrement          :=
	       button(decrement)
	   ],
	 modifications :=
	   [ Input_field := [ label  := 'Value :',
			      length := 28,
			      show_label := @off
			    ],
	     Decrement := [active := @off]
	   ],
	 layout        :=
	   [ area(Name,
		  area(50, 26, 25, 24)),
	     area(Input_field,
		  area(95, 24, 200, 24)),
	     area(Increment,
		  area(50, 90, 80, 24)),
	     area(Decrement,
		  area(230, 90, 80, 24))
	   ],
	 behaviour     :=

	   [
	     Increment := [
			 message := message(@prolog,
					    increment,
					    Increment,
					    Decrement,
					    Input_field )
		       ],
	     Decrement := [
			 message := message(@prolog,
					    decrement,
					    Increment,
					    Decrement,
					    Input_field)
			  ],
	     Input_field := [
			 message := message(@prolog,
					    input,
					    Increment,
					    Decrement,
					    @receiver,
					    @arg1)
			  ]
	   ]

       ]).

gui_component :-
	make_dialog(S, 'GUI_Interaction'),
	send(S, open).

increment(Incr, Decr, Input) :-
	get(Input, selection, V),
	atom_number(V, Val),
	Val1 is Val + 1,
	send(Input, selection, Val1),
	test(Val1, Incr, Decr, Input).

decrement(Incr, Decr, Input) :-
	get(Input, selection, V),
	atom_number(V, Val),
	Val1 is Val - 1,
	send(Input, selection, Val1),
	test(Val1, Incr, Decr, Input).

input(Incr, Decr, Input, Selection) :-
	catch( (term_to_atom(T, Selection), number(T)),
	       _,
	       (   send(@display, inform, 'Please type a number !'),
		   T = 0,
		   send(Input,selection, T))),
	test(T, Incr, Decr, Input).

test(V, Incr, Decr, Input) :-
	(   V = 0 -> send(Input, active, @on); send(Input, active, @off)),
	send(Incr, active, @on),
	send(Decr, active, @on),
	(   V < 1
	->  send(Decr, active, @off)
	;   V > 9
	->  send(Incr, active, @off)).


Enumeration
  #TextGadget
  #AddButton
  #SubButton
EndEnumeration

Procedure UpdateGadgets(Value,UpdateValue=0)
  Overmax=0: UnderMin=0
  If Value>=10
    Overmax=1
  ElseIf Value<=0
    UnderMin=1
  EndIf
  DisableGadget(#AddButton,Overmax)
  DisableGadget(#SubButton,UnderMin)
  If UpdateValue
    SetGadgetText(#TextGadget,Str(Value))
  EndIf
EndProcedure

If OpenWindow(0,#PB_Ignore,#PB_Ignore,110,70,"PB-GUI",#PB_Window_SystemMenu)
  StringGadget(#TextGadget,10,10,90,20,"")
  ButtonGadget(#AddButton,10,40,30,20,"+")
  ButtonGadget(#SubButton,70,40,30,20,"-")
  UpdateGadgets(Value,1)
  Repeat
    Event=WaitWindowEvent()
    If Event=#PB_Event_Gadget
      Gadget=EventGadget()
      Select Gadget
        Case #AddButton
          Value+1
          UpdateGadgets(Value,1)
        Case #SubButton
          Value-1
          UpdateGadgets(Value,1)
        Default
          EType=EventType()
          If EType=#PB_EventType_Change
            Value=Val(GetGadgetText(#TextGadget))
            UpdateGadgets(Value)
          EndIf
      EndSelect
    EndIf
    Until Event=#PB_Event_CloseWindow
EndIf


#!/usr/bin/env python3

import tkinter as tk

class MyForm(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack(expand=True, fill="both", padx=10, pady=10)
        self.master.title("Controls")
        self.setupUI()

    def setupUI(self):
        self.value_entry = tk.Entry(self, justify=tk.CENTER)
        self.value_entry.grid(row=0, column=0, columnspan=2,
                              padx=5, pady=5, sticky="nesw")
        self.value_entry.insert('end', '0')
        self.value_entry.bind("<KeyPress-Return>", self.eventHandler)

        self.decre_btn = tk.Button(self, text="Decrement", state=tk.DISABLED)
        self.decre_btn.grid(row=1, column=0, padx=5, pady=5)
        self.decre_btn.bind("<Button-1>", self.eventHandler)

        self.incre_btn = tk.Button(self, text="Increment")
        self.incre_btn.grid(row=1, column=1, padx=5, pady=5)
        self.incre_btn.bind("<Button-1>", self.eventHandler)

    def eventHandler(self, event):
        value = int(self.value_entry.get())
        if event.widget == self.value_entry:
            if value > 10:
                self.value_entry.delete("0", "end")
                self.value_entry.insert("end", "0")
            elif value == 10:
                self.value_entry.config(state=tk.DISABLED)
                self.incre_btn.config(state=tk.DISABLED)
                self.decre_btn.config(state=tk.NORMAL)
            elif value == 0:
                self.value_entry.config(state=tk.NORMAL)
                self.incre_btn.config(state=tk.NORMAL)
                self.decre_btn.config(state=tk.DISABLED)
            elif (value > 0) and (value < 10):
                self.value_entry.config(state=tk.DISABLED)
                self.incre_btn.config(state=tk.NORMAL)
                self.decre_btn.config(state=tk.NORMAL)
        else:
            if event.widget == self.incre_btn:
                if (value >= 0) and (value < 10):
                    value += 1
                    self.value_entry.config(state=tk.NORMAL)
                    self.value_entry.delete("0", "end")
                    self.value_entry.insert("end", str(value))
                if value > 0:
                    self.decre_btn.config(state=tk.NORMAL)
                    self.value_entry.config(state=tk.DISABLED)
                if value == 10:
                    self.incre_btn.config(state=tk.DISABLED)
            elif event.widget == self.decre_btn:
                if (value > 0) and (value <= 10):
                    value -= 1
                    self.value_entry.config(state=tk.NORMAL)
                    self.value_entry.delete("0", "end")
                    self.value_entry.insert("end", str(value))
                    self.value_entry.config(state=tk.DISABLED)
                if (value) < 10:
                    self.incre_btn.config(state=tk.NORMAL)
                if (value) == 0:
                    self.decre_btn.config(state=tk.DISABLED)
                    self.value_entry.config(state=tk.NORMAL)

def main():
    app = MyForm()
    app.mainloop()

if __name__ == "__main__":
    main()


library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2

w <- gwindow("Disable components")

g <- ggroup(cont=w, horizontal=FALSE)
e <- gedit("0", cont=g, coerce.with=as.numeric)
bg <- ggroup(cont=g)

down_btn <- gbutton("-", cont=bg)
up_btn <- gbutton("+", cont=bg)

update_ctrls <- function(h,...) {
  val <- svalue(e)
  enabled(down_btn) <- val >= 0
  enabled(up_btn) <- val <= 10
}

rement <- function(h,...) {
  svalue(e) <- svalue(e) + h$action
  update_ctrls(h,...)
}

addHandlerChanged(e, handler=update_ctrls)
addHandlerChanged(down_btn, handler=rement, action=-1)
addHandlerChanged(up_btn, handler=rement, action=1)


#lang racket/gui

(define frame (new frame% [label "Interaction Demo"]))

(define (changed . _)
  (define s (send inp get-value))
  (define v (string->number s))
  (unless v (set! v (or (string->number (regexp-replace* #rx"[^0-9]+" s "")) 0))
            (send inp set-value (~a v)))
  (send inc-b enable (< v 10))
  (send dec-b enable (> v 0))
  (send inp enable (zero? v)))
(define ((change-value f) . _)
  (send inp set-value (number->string (f (string->number (send inp get-value)))))
  (changed))

(define inp
  (new text-field% [label "Value"] [parent frame] [init-value "0"] [callback changed]))

(define buttons (new horizontal-pane% [parent frame]))
(define inc-b
  (new button% [parent buttons] [label "Increment"] [callback (change-value add1)]))
(define dec-b
  (new button% [parent buttons] [label "Decrement"] [callback (change-value sub1)]))

(send frame show #t)


use GTK::Simple;
use GTK::Simple::App;

my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );

$app.set-content(
    my $box = GTK::Simple::HBox.new(
        my $inc   = GTK::Simple::Button.new( label => ' + ' ),
        my $value = GTK::Simple::Entry.new,
        my $dec   = GTK::Simple::Button.new( label => ' - ' )
    )
);

$app.border-width = 10;
$box.spacing = 10;

$value.changed.tap: {
    $value.text.=subst(/\D/, '');
    $inc.sensitive = $value.text < 10;
    $dec.sensitive = $value.text > 0;
}

$value.text = '0';

$inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str }
$dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str }

$app.run;


Red[]

enable: does [
    f/enabled?: 0 = n
    i/enabled?: 10 > n
    d/enabled?: 0 < n
]

view [
    f: field "0" [either error? try [n: to-integer f/text] [f/text: "0"] [enable]]
    i: button "increment" [f/text: mold n: add to-integer f/text 1 enable]
    d: button "decrement" disabled [f/text: mold n: subtract to-integer f/text 1 enable]
]


Load "guilib.ring"

MyApp = New qApp {
        num = 0
        win1 = new qWidget() {
               setwindowtitle("Hello World")
               setGeometry(100,100,370,250)

               btn1 = new qpushbutton(win1) {
                      setGeometry(50,200,100,30)
                      settext("Increment")
                      setclickevent("Increment()")}

               btn2 = new qpushbutton(win1) {
                      setGeometry(200,200,100,30)
                      settext("Decrement")
                      setclickevent("Decrement()")}

               lineedit1 = new qlineedit(win1) {
                           setGeometry(10,100,350,30)
                           settext("0")}
               show()}
exec()}

func Increment
     lineedit1{ num = text()}
     num = string(number(num)+1)
     lineedit1.settext(num)
     if number(num)>9 btn1.setDisabled(True) ok

func Decrement
     lineedit1{ num = text()}
     num = string(number(num)-1)
     lineedit1.settext(num)
     if number(num)<0 btn2.setDisabled(True) ok


Shoes.app do
  @number = edit_line
  @number.change {update_controls}

  @incr = button('Increment') {update_controls(@number.text.to_i + 1)}
  @decr = button('Decrement') {update_controls(@number.text.to_i - 1)}

  def update_controls(value = @number.text.to_i)
    @number.text = value
    @incr.state = value.to_i >= 10 ? "disabled" : nil
    @decr.state = value.to_i <=  0 ? "disabled" : nil
  end

  update_controls 0
end


import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField }
import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }

object Enabling extends swing.SimpleSwingApplication {
  def top = new swing.MainFrame {
    title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala"

    val numberField = new TextField {
      text = "0" // start at 0
      horizontalAlignment = swing.Alignment.Right
    }

    val (incButton, decButton) = (new Button("Increment"), // Two variables initialized
      new Button("Decrement") { enabled = false })

    // arrange buttons in a grid with 1 row, 2 columns
    val buttonPanel = new GridPanel(1, 2) { contents ++= List(incButton, decButton) }

    // arrange text field and button panel in a grid with 2 row, 1 column
    contents = new BoxPanel(Orientation.Vertical) { contents ++= List(numberField, buttonPanel) }

    val specialKeys = List(Key.BackSpace, Key.Delete)

    // listen for keys pressed in numberField and button clicks
    listenTo(numberField.keys, incButton, decButton)
    reactions += {
      case kt: KeyTyped =>
        if (kt.char.isDigit) // if the entered char is a digit ...
          Swing.onEDT(switching) // ensure GUI-updating
        else kt.consume // ... eat the event (i.e. stop it from being processed)
      case KeyPressed(_, kp, _, _) if (!specialKeys.contains(kp)) =>
        Swing.onEDT(switching) // ensure GUI-updating
      case ButtonClicked(`incButton`) =>
        numberField.text = (numberField.text.toLong + 1).toString
        switching
      case ButtonClicked(`decButton`) =>
        numberField.text = (numberField.text.toLong - 1).toString
        switching
    }

    def switching = {
      val n = (if (numberField.text.isEmpty()) "0" else numberField.text).toLong
      numberField.text = n.toString
      numberField.enabled = n == 0
      incButton.enabled = n < 10
      decButton.enabled = n > 0
    }
    centerOnScreen()
  } // def top(
}


|top input vh incButton decButton|

vh := ValueHolder with:0.

top := StandardSystemView label:'Rosetta GUI interaction'.
top extent:300@100.
top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40).
top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40).
input model:(TypeConverter onNumberValue:vh).
input enableChannel:(BlockValue with:[:v | v = 0] argument:vh).

top add:((incButton := Button label:'Inc') origin: 10 @ 50 corner: 100 @ 80).
top add:((decButton := Button label:'Dec') origin: 110 @ 50 corner: 210 @ 80).

incButton action:[ vh value: (vh value + 1) ].
incButton enableChannel:(BlockValue with:[:v | v < 10] argument:vh).
decButton action:[ vh value: (vh value - 1) ].
decButton enableChannel:(BlockValue with:[:v | v > 0] argument:vh).

top open


package require Tk

# Model
set field 0

# View
place [ttk::frame .bg] -relwidth 1 -relheight 1; # Hack to make things look nice
pack [ttk::labelframe .val -text "Value"]
pack [ttk::entry .val.ue -textvariable field \
	-validate key -invalidcommand bell \
	-validatecommand {string is integer %P}]
pack [ttk::button .inc -text "increment" -command up]
pack [ttk::button .dec -text "decrement" -command down]

# Controller
proc up {} {
    global field
    incr field
}
proc down {} {
    global field
    incr field -1
}
# Attach this controller to the Model; easier than manual calling
trace add variable field write updateEnables
proc updateEnables {args} {
    global field
    .inc state [expr {$field < 10 ? "!disabled" : "disabled"}]
    .dec state [expr {$field > 0 ? "!disabled" : "disabled"}]
}
updateEnables; # Force initial state of buttons


bool validate_input(Gtk.Window window, string str){
    int64 val;
    bool ret = int64.try_parse(str,out val);;

    if(!ret || str == ""){
        var dialog = new Gtk.MessageDialog(window,
                                           Gtk.DialogFlags.MODAL,
                                           Gtk.MessageType.ERROR,
                                           Gtk.ButtonsType.OK,
                                           "Invalid value");
        dialog.run();
        dialog.destroy();
    }
    if(str == ""){
        ret = false;
    }

    return ret;
}

int main (string[] args) {
    Gtk.init (ref args);

    var window = new Gtk.Window();
    window.title = "Rosetta Code";
    window.window_position = Gtk.WindowPosition.CENTER;
    window.destroy.connect(Gtk.main_quit);
    window.set_default_size(0,0);

    var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1);
    box.set_border_width(1);

    var label = new Gtk.Label("Value:");
    var entry = new Gtk.Entry();
    var ib = new Gtk.Button.with_label("inc");
    var db = new Gtk.Button.with_label("dec");

    ib.set_sensitive(true);  //enable the inc button
    db.set_sensitive(false); //disable the dec button

    entry.set_text("0");   //initialize to zero

    entry.activate.connect(() => {
        var str = entry.get_text();

        if(!validate_input(window, str)){
            entry.set_text("0");   //initialize to zero on wrong input
        }else{
            int num = int.parse(str);
            if(num != 0){
                entry.set_sensitive(false); //disable the field
            }
            if(num > 0 && num < 10){
                ib.set_sensitive(true);   //enable the inc button
                db.set_sensitive(true);   //enable the dec button
            }
            if(num > 9){
                ib.set_sensitive(false);  //disable the inc button
                db.set_sensitive(true);   //enable the dec button
            }
        }
    });

    ib.clicked.connect(() => {
        // read and validate the entered value
        if(!validate_input(window, entry.get_text())){
            entry.set_text("0");   //initialize to zero on wrong input
        }else{
            int num = int.parse(entry.get_text()) + 1;
            entry.set_text(num.to_string());
            if(num > 9){
                ib.set_sensitive(false); //disable the inc button
            }
            if(num != 0){
                db.set_sensitive(true); //enable the dec button
                entry.set_sensitive(false); //disable the field
            }
            if(num == 0){
                entry.set_sensitive(true); //enable the field
            }
            if(num < 0){
                db.set_sensitive(false);   //disable the dec button
            }
        }
    });

    db.clicked.connect(() => {
        // read and validate the entered value
        int num = int.parse(entry.get_text()) - 1;
        entry.set_text(num.to_string());
        if(num == 0){
            db.set_sensitive(false); //disable the dec button
            entry.set_sensitive(true); //enable the field
        }
        if(num < 10){
            ib.set_sensitive(true); //enable the inc button
        }
    });

    box.pack_start(label, false, false, 2);
    box.pack_start(entry, false, false, 2);
    box.pack_start(ib, false, false, 2);
    box.pack_start(db, false, false, 2);

    window.add(box);

    window.show_all();

    Gtk.main();
    return 0;
}


VERSION 5.00
Begin VB.Form Form1
   Caption         =   "Form1"
   ClientHeight    =   2265
   ClientLeft      =   60
   ClientTop       =   600
   ClientWidth     =   2175
   LinkTopic       =   "Form1"
   ScaleHeight     =   2265
   ScaleWidth      =   2175
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton cmdDec
      Caption         =   "Decrement"
      Enabled         =   0   'False
      Height          =   495
      Left            =   120
      TabIndex        =   2
      Top             =   1680
      Width           =   1215
   End
   Begin VB.CommandButton cmdInc
      Caption         =   "Increment"
      Height          =   495
      Left            =   120
      TabIndex        =   1
      Top             =   1080
      Width           =   1215
   End
   Begin VB.TextBox txtValue
      Height          =   495
      Left            =   120
      TabIndex        =   0
      Text            =   "0"
      Top             =   240
      Width           =   1215
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'-----user-written code begins here; everything above this line is hidden in the GUI-----
Private Sub cmdDec_Click()
    If Val(txtValue.Text) > 0 Then txtValue.Text = Val(txtValue.Text) - 1
End Sub

Private Sub cmdInc_Click()
    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub

Private Sub txtValue_Change()
    Select Case Val(txtValue.Text)
        Case Is < 0
            txtValue.Enabled = False
            cmdInc.Enabled = True
            cmdDec.Enabled = False
        Case Is > 9
            txtValue.Enabled = False
            cmdInc.Enabled = False
            cmdDec.Enabled = True
        Case 0
            txtValue.Enabled = True
            cmdInc.Enabled = True
            cmdDec.Enabled = False
        Case Else
            txtValue.Enabled = False
            cmdInc.Enabled = True
            cmdDec.Enabled = True
    End Select
End Sub


import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "./polygon" for Polygon

class Button {
    construct new(x, y, w, h, legend, c, oc, lc) {
        var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
        _rect = Polygon.quick(vertices)
        _x = x
        _y = y
        _w = w
        _h = h
        _legend = legend
        _c = c
        _oc = oc
        _lc = lc
        _enabled = true
    }

    enabled     { _enabled }
    enabled=(e) { _enabled = e }

    draw() {
        _rect.drawfill(_c)
        _rect.draw(_oc)
        var l = Canvas.getPrintArea(_legend)
        var lx = ((_w - l.x)/2).truncate
        lx = (lx > 0) ? _x + lx : _x + 1
        var ly = ((_h - l.y)/2).truncate
        ly = (ly > 0) ? _y + ly : _y + 1
        var col = _enabled ? _lc : Color.darkgray
        Canvas.print(_legend, lx, ly, col)
    }

    justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) }
}

class TextBox {
    construct new(x, y, w, h, label, c, oc, lc) {
        var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
        _rect = Polygon.quick(vertices)
        _x = x
        _y = y
        _w = w
        _h = h
        _label = label
        _c = c
        _oc = oc
        _lc = lc
        _text = ""
        _enabled = true
    }

    text     { _text }
    text=(t) { _text = t }

    enabled     { _enabled }
    enabled=(e) { _enabled = e }

    draw() {
        _rect.drawfill(_c)
        _rect.draw(_oc)
        var l = Canvas.getPrintArea(_label).x
        var lx = _x - l - 7
        if (lx < 1) {
             lx = 1
             _label = _label[0..._x]
        }
        var col = _enabled ? _lc : Color.darkgray
        Canvas.print(_label, lx, _y, col)
        Canvas.getPrintArea(_label).x
        Canvas.print(_text, _x + 3, _y + 1, Color.black)
    }
}

class GUIControlEnablement {
    construct new() {
        Window.title = "GUI control enablement"
        _btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white)
        _btnDecrement = Button.new(180, 40, 80, 80, "Decrement", Color.green, Color.blue, Color.white)
        _txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white)
        _txtValue.text = "0"
        Keyboard.handleText = true
    }

    init() {
        _btnDecrement.enabled = false
        drawControls()
    }

    update() {
        if (_btnIncrement.enabled && _btnIncrement.justClicked) {
            var number = Num.fromString(_txtValue.text) + 1
            _btnIncrement.enabled = (number < 10)
            _btnDecrement.enabled = true
            _txtValue.enabled = (number == 0)
            _txtValue.text = number.toString
        } else if (_btnDecrement.enabled && _btnDecrement.justClicked) {
            var number = Num.fromString(_txtValue.text) - 1
            _btnDecrement.enabled = (number > 0)
            _btnIncrement.enabled = true
            _txtValue.enabled = (number == 0)
            _txtValue.text = number.toString
        } else if (_txtValue.enabled && "0123456789".any { |d| Keyboard[d].justPressed }) {
            _txtValue.text = Keyboard.text
            _txtValue.enabled = (_txtValue.text == "0")
            _btnIncrement.enabled = true
            _btnDecrement.enabled = (_txtValue.text != "0")
        }
    }

    draw(alpha) {
        drawControls()
    }

    drawControls() {
        Canvas.cls()
        _btnIncrement.draw()
        _btnDecrement.draw()
        _txtValue.draw()
    }
}

var Game = GUIControlEnablement.new()


V (target_min, target_max) = (1, 10)
V (mn, mx) = (target_min, target_max)

print(
‘Think of a number between #. and #. and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =
’.format(target_min, target_max))

V i = 0
L
   i++
   V guess = (mn + mx) I/ 2
   V txt = input(‘Guess #2 is: #2. The score for which is (h,l,=): ’.format(i, guess)).trim(‘ ’).lowercase()[0]
   I txt !C ‘hl=’
      print(‘  I don't understand your input of '#.' ?’.format(txt))
      L.continue
   I txt == ‘h’
      mx = guess - 1
   I txt == ‘l’
      mn = guess + 1
   I txt == ‘=’
      print(‘  Ye-Haw!!’)
      L.break
   I (mn > mx) | (mn < target_min) | (mx > target_max)
      print(‘Please check your scoring as I cannot find the value’)
      L.break

print("\nThanks for keeping score.")


PROC Main()
  BYTE n,min=[1],max=[100]
  CHAR c

  PrintF("Think a number in range %B-%B%E",min,max)
  DO
    n=(max+min) RSH 1
    PrintF("My guess is %B%E",n)
    PrintF("Is it (E)qual, (L)ower or (H)igher?")
    c=GetD(7)
    Put(c) PutE()
    IF c='E THEN
      Print("I guessed!")
      EXIT
    ELSEIF c='L THEN
      max=n-1
    ELSEIF c='H THEN
      min=n+1
    FI
    IF max<min THEN
      Print("You are cheating...")
      EXIT
    FI
  OD
RETURN


with Ada.Text_IO;
procedure Guess_Number_Player is
   procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
      type Feedback is (Lower, Higher, Correct);
      package Feedback_IO is new Ada.Text_IO.Enumeration_IO (Feedback);
      My_Guess : Integer := Lower_Limit + (Upper_Limit - Lower_Limit) / 2;
      Your_Feedback : Feedback;
   begin
      Ada.Text_IO.Put_Line ("Think of a number!");
      loop
         Ada.Text_IO.Put_Line ("My guess: " & Integer'Image (My_Guess));
         Ada.Text_IO.Put ("Your answer (lower, higher, correct): ");
         Feedback_IO.Get (Your_Feedback);
         exit when Your_Feedback = Correct;
         if Your_Feedback = Lower then
            My_Guess := Lower_Limit + (My_Guess - Lower_Limit) / 2;
         else
            My_Guess := My_Guess + (Upper_Limit - My_Guess) / 2;
         end if;
      end loop;
      Ada.Text_IO.Put_Line ("I guessed well!");
   end Guess_Number;
   package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
   Lower_Limit : Integer;
   Upper_Limit : Integer;
begin
   loop
      Ada.Text_IO.Put ("Lower Limit: ");
      Int_IO.Get (Lower_Limit);
      Ada.Text_IO.Put ("Upper Limit: ");
      Int_IO.Get (Upper_Limit);
      exit when Lower_Limit < Upper_Limit;
      Ada.Text_IO.Put_Line ("Lower limit must be lower!");
   end loop;
   Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Player;


BEGIN
    INT    lower    :=    1;
    INT    upper    :=  100;
    print( ( "Think of a number between ", whole( lower, 0 ), " and ", whole( upper, 0 ), newline ) );
    print( ( "Please enter Y if I guess correctly, L is it is lower, G if it is greater or Q if you've had enough", newline ) );
    WHILE
        INT mid = lower + ( ( upper - lower ) OVER 2 );
        CHAR reply;
        WHILE
            print( ( "Is it ", whole( mid, 0 ), "?    Y/L/G/Q: " ) );
            read( ( reply, newline ) );
            NOT char in string( reply, NIL, "YLGQylgq" )
        DO SKIP OD;
        IF   reply = "Q" OR reply = "q" OR reply = "Y" OR reply = "y"
        THEN FALSE
        ELIF lower >= upper THEN
            print( ( "Based on your answers so far, it must be ", whole( lower, 0 ), newline ) );
            FALSE
        ELSE
            IF   reply = "L" OR reply = "l" THEN upper := mid - 1
            ELIF reply = "G" OR reply = "g" THEN lower := mid + 1
            FI;
            TRUE
        FI
    DO SKIP OD
END


-- defining the range of the number to be guessed
property minLimit : 1
property maxLimit : 100

on run
	-- ask the user to think of  a number in the given range
	display dialog "Please think of a number between " & minLimit & " and " & maxLimit

	-- prepare a variable for the lowest guessed value
	set lowGuess to minLimit
	-- prepare a variable for the highest guessed value
	set highGuess to maxLimit

	repeat
		-- guess a number inside the logical range
		set computersGuess to (random number from lowGuess to highGuess)
		-- ask the user to check my guess
		set guessResult to button returned of (display dialog "I guess " & computersGuess & "!" & return & "What do you think?" buttons {"Lower", "Correct", "Higher"})
		if guessResult = "Lower" then
			-- the number is less than the guess, switch the upper limit to the guess
			set highGuess to computersGuess
		else if guessResult = "Higher" then
			-- the number is greater than the guess, switch the lower limit to the guess
			set lowGuess to computersGuess
		else if guessResult = "Correct" then
			-- the computer guessed the number, beep and exit
			beep
			exit repeat
		end if
	end repeat
end run


print {:
Think of a number between 1 and 10 and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =
:}

rmin: 1
rmax: 10

while ø [
    guess: random rmin rmax
    print ["My guess is:" guess]
    inputOk: false
    while [not? inputOk][
        hle: strip input "How did I do? (h)igh, (l)ow, (=): "
        case [hle]
            when? [="h"][
                if? rmin =< dec guess [rmax: dec guess, inputOk: true]
                else -> print "\tThat doesn't make any sense. I cannot find the number..."
            ]
            when? [="l"][
                if? (inc guess) =< rmax [rmin: inc guess, inputOk: true]
                else -> print "\tThat doesn't make any sense. I cannot find the number..."
            ]
            when? [="="][
                print ""
                print "Great! I found it! :)"
                print "Thanks for keeping the score."
                exit
            ]
            else [
                print "\tPlease, check your input; it doesn't appear to be correct!"
            ]
    ]
    print ""
]


MaxGuesses = 50

GetParams(LowerBound,UpperBound)
If Not GuessNum(LowerBound,UpperBound,MaxGuesses)
 MsgBox, 16, Error, Could not guess number within %MaxGuesses% guesses.

GetParams(ByRef LowerBound,ByRef UpperBound)
{
 WinWait, Number Guessing ahk_class #32770
 Sleep, 100
 WinGet, InputID, ID
 ControlGetText, Temp1, Static1, ahk_id %InputID%
 Temp2 := InStr(Temp1,A_Space,False,32)
 LowerBound := SubStr(Temp1,31,Temp2 - 31)
 UpperBound := SubStr(Temp1,Temp2 + 5,-1)
}

GuessNum(LowerBound,UpperBound,MaxGuesses)
{
 Loop, %MaxGuesses%
 {
  Guess := LowerBound + ((UpperBound - LowerBound) // 2)
  Temp1 := SendGuess(Guess)
  ToolTip % Temp1
  If Temp1 = Too Low
   LowerBound = %Guess%
  Else If Temp1 = Too High
   UpperBound = %Guess%
  Else
   Return, 1
 }
}

SendGuess(Guess)
{
 WinGet, InputID, ID, Number Guessing ahk_class #32770
 ControlSetText, Edit1, %Guess%, ahk_id %InputID%
 ControlSend, Button1, {Enter}, ahk_id %InputID%
 Loop
 {
  Sleep, 50
  IfWinExist, Correct ahk_class #32770
   Return
  Else IfWinExist, Incorrect ahk_class #32770
   Break
 }
 ControlGetText, Temp1, Static2
 WinClose
 WinWaitClose
 IfInString, Temp1, low
  Return, "Too Low"
 Else
  Return, "Too High"
}


@echo off

:: Player is prompted to give a number between %min% and %max%. If the input is out of those limits they are prompted to choose again
:choose
set min=0
set max=100

set /p "number=Choose a number [%min%-%max%]: "
if %number% gtr %max% goto choose
if %number% lss %min% goto choose
set attempts=0

:: Loops the guessing process until completed
:comp
set /a attempts+=1
set /a guess=(%max%-%min%)/2+%min%
choice /c "HLE" /n /m "Guess: %guess% - [H]igher, [L]ower or [E]qual"
if errorlevel 3 goto end
if errorlevel 2 (
  set max=%guess%
  goto comp
)
if errorlevel 1 (
  set min=%guess%
  goto comp
)

:end
echo Guesses: %attempts%
pause>nul


10 DEFINT A-Z
20 INPUT "Lower limit? ",L
30 INPUT "Upper limit? ",H
40 IF L>H THEN PRINT "Invalid input": END
50 PRINT "My guess is ";(H-L)\2+L
55 T=T+1
60 INPUT "Too low (L), too high (H), or correct (C)? ",R$
70 ON INSTR("LlHhCc",R$) GOTO 90,90,100,100,110,110
80 PRINT "Invalid input": GOTO 50
90 L=(H-L)\2+L: GOTO 40
100 H=(H-L)\2+L: GOTO 40
110 PRINT "It took";T;"tries."


      min% = 1
      max% = 100
      PRINT "Think of a number between "; min% " and " ;max%
      PRINT "I will try to guess your number."
      REPEAT
        guess% = (min% + max%) DIV 2
        PRINT "My guess is " ; guess%
        INPUT "Is it higher than, lower than or equal to your number", answer$
        CASE LEFT$(answer$,1) OF
          WHEN "L","l": min% = guess% + 1
          WHEN "H","h": max% = guess% - 1
          WHEN "E","e": EXIT REPEAT
          OTHERWISE: PRINT "Sorry, I didn't understand your answer."
        ENDCASE
      UNTIL FALSE
      PRINT "Goodbye."
      END


get "libhdr"

let reads(s) = valof
$(  s%0 := 0
    $(  let c = rdch()
        if c = endstreamch resultis false
        if c = '*N' resultis true
        s%0 := s%0 + 1
        s%(s%0) := c
    $) repeat
$)

let choose(chs) = valof
$(  let ans = vec 80
    writef("[%S]? ",chs)
    unless reads(ans) finish
    unless ans%0=1 loop
    for i=1 to chs%0
        if (ans%1|32) = (chs%i|32) resultis chs%i
$) repeat

let tantrum() be
$(  writes("Cheater!*N")
    finish
$)

let guess(lo, hi, t) = valof
$(  let ans = vec 80
    test hi<lo do tantrum()
    or test hi=lo
    $(  writef("Is the number %N ",lo)
        test choose("yn")='y' resultis t or tantrum()
    $)
    or
    $(  let g = (hi-lo)/2+lo
        writef("My guess is %N. Too low, too high, or correct ",g)
        switchon choose("lhc") into
        $(  case 'l': resultis guess(g, hi, t+1)
            case 'h': resultis guess(lo, g, t+1)
            case 'c': resultis t
        $)
    $)
$)

let start() be
$(  let min = ? and max = ?
    writes("Lower bound? ") ; min := readn()
    writes("Upper bound? ") ; max := readn()
    writef("It took %N attempts.*N", guess(min, max, 1))
$)


#include <stdio.h>

int main(){
  int bounds[ 2 ] = {1, 100};
  char input[ 2 ] = "  ";
    /* second char is for the newline from hitting [return] */
  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
    /* using a binary search */

  printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );

  do{
    switch( input[ 0 ] ){
      case 'H':
        bounds[ 1 ] = choice;
        break;
      case 'L':
        bounds[ 0 ] = choice;
        break;
      case 'Y':
        printf( "\nAwwwright\n" );
        return 0;
    }
    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;

    printf( "Is the number %d? (Y/H/L) ", choice );
  }while( scanf( "%1s", input ) == 1 );

  return 0;
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //Remember to add this if you want the game to pause in RealisticGuess.Start()

namespace ConsoleApplication1
{
    class RealisticGuess //Simulates a guessing game between two people. Guessing efficiency is not a goal.
    {
        private int max;
        private int min;
        private int guess;

        public void Start()
        {
            Console.Clear();
            string input;

            try
            {
                Console.WriteLine("Please enter the lower boundary");
                input = Console.ReadLine();
                min = Convert.ToInt32(input);
                Console.WriteLine("Please enter the upper boundary");
                input = Console.ReadLine();
                max = Convert.ToInt32(input);
            }
            catch (FormatException)
            {
                Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again.");
                Console.ReadKey(true);
                Start();
            }
            Console.WriteLine("Think of a number between {0} and {1}.", min, max);
            Thread.Sleep(2500);
            Console.WriteLine("Ready?");
            Console.WriteLine("Press any key to begin.");
            Console.ReadKey(true);
            Guess(min, max);
        }
        public void Guess(int min, int max)
        {
            int counter = 1;
            string userAnswer;
            bool correct = false;
            Random rand = new Random();

            while (correct == false)
            {
                guess = rand.Next(min, max);
                Console.Clear();
                Console.WriteLine("{0}", guess);
                Console.WriteLine("Is this number correct? {Y/N}");
                userAnswer = Console.ReadLine();
                if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N")
                {
                    Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'");
                    Console.WriteLine("Is the number correct? {Y/N}");
                    userAnswer = Console.ReadLine();
                }
                if (userAnswer == "y" || userAnswer == "Y")
                {
                    correct = true;
                }
                if (userAnswer == "n" || userAnswer == "N")
                {
                    counter++;
                    if (max == min)
                    {
                        Console.WriteLine("Error: Range Intersect. Press enter to restart the game.");  //This message should never pop up if the user enters good data.
                        Console.ReadKey(true);                                                          //It handles the game-breaking exception that occurs
                        Guess(1, 101);                                                                  //when the max guess number is the same as the min number.
                    }
                    Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
                    userAnswer = Console.ReadLine();
                    if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H")
                    {
                        Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'");
                        Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
                        userAnswer = Console.ReadLine();
                    }
                    if (userAnswer == "l" || userAnswer == "L")
                    {
                        max = guess;
                    }
                    if (userAnswer == "h" || userAnswer == "H")
                    {
                        min = guess;
                    }
                }
            }
            if (correct == true)
            {
                EndAndLoop(counter);
            }
        }

        public void EndAndLoop(int iterations)
        {
            string userChoice;
            bool loop = false;
            Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations);
            while (loop == false)
            {
                Console.WriteLine("Would you like to play again? {Y/N}");
                userChoice = Console.ReadLine();
                if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n")
                {
                    Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.");
                }
                if (userChoice == "Y" || userChoice == "y")
                {
                    Start();
                }
                if (userChoice == "N" || userChoice == "n")
                {
                    Environment.Exit(1);
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Random Number";
            RealisticGuess game = new RealisticGuess();
            game.Start();
        }
    }
}


#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>

struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
  int i;
  GuessNumberIterator() { }
  GuessNumberIterator(int _i) : i(_i) { }
  GuessNumberIterator& operator++() { ++i; return *this; }
  GuessNumberIterator operator++(int) {
    GuessNumberIterator tmp = *this; ++(*this); return tmp; }
  bool operator==(const GuessNumberIterator& y) { return i == y.i; }
  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
  int operator*() {
    std::cout << "Is your number less than or equal to " << i << "? ";
    std::string s;
    std::cin >> s;
    return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
  }
  GuessNumberIterator& operator--() { --i; return *this; }
  GuessNumberIterator operator--(int) {
    GuessNumberIterator tmp = *this; --(*this); return tmp; }
  GuessNumberIterator& operator+=(int n) { i += n; return *this; }
  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
  GuessNumberIterator operator+(int n) {
    GuessNumberIterator tmp = *this; return tmp += n; }
  GuessNumberIterator operator-(int n) {
    GuessNumberIterator tmp = *this; return tmp -= n; }
  int operator-(const GuessNumberIterator &y) { return i - y.i; }
  int operator[](int n) { return *(*this + n); }
  bool operator<(const GuessNumberIterator &y) { return i < y.i; }
  bool operator>(const GuessNumberIterator &y) { return i > y.i; }
  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }

const int lower = 0;
const int upper = 100;

int main() {
  std::cout << "Instructions:\n"
	    << "Think of integer number from " << lower << " (inclusive) to "
	    << upper << " (exclusive) and\n"
	    << "I will guess it. After each guess, I will ask you if it is less than\n"
	    << "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
  std::cout << "Your number is " << answer << ".\n";
  return 0;
}


shared void run() {
    while(true) {
        variable value low = 1;
        variable value high = 10;
        variable value attempts = 1;
        print("Please choose a number between ``low`` and ``high``.
               Press enter when ready.");
        process.readLine();
        while(true) {
            if(low > high) {
                print("Something is wrong. I give up.");
                break;
            }
            variable value guess = (low + high) / 2;
            print("Is ``guess`` (e)qual, (h)igher or (l)ower to your number?
                   (enter q to quit)");
            value answer = process.readLine()?.trimmed?.lowercased;
            switch(answer)
            case("e") {
                print("I got it in only ``attempts`` ``attempts == 1 then "try" else "tries"``!");
                break;
            }
            case("h") {
                high = guess - 1;
                attempts++;
            }
            case("l") {
                low = guess + 1;
                attempts++;
            }
            case("q") {
                return;
            }
            else {
                print("Please enter an e, h, l or q");
            }
        }
    }
}


(require '[clojure.string :as str])

(defn guess-game [low high]
  (printf "Think of a number between %s and %s.\n (use (h)igh (l)ow (c)orrect)\n" low high)
  (loop [guess (/ (inc (- high low)) 2)
         [step & more] (next (iterate #(/ % 2) guess))]
    (printf "I guess %s\n=> " (Math/round (float guess)))
    (flush)
    (case (first (str/lower-case (read)))
      \h (recur (- guess step) more)
      \l (recur (+ guess step) more)
      \c (println "Huzzah!")
      (do (println "Invalid input.")
          (recur guess step)))))


(defun guess-the-number (&optional (max 1000) (min 0))
  (flet ((get-feedback (guess)
           (loop
              initially (format t "I choose ~a.~%" guess)
              for answer = (read)
              if (member answer '(greater lower correct))
              return answer
              else do (write-line "Answer greater, lower, or correct."))))
    (loop
       initially (format t "Think of a number between ~a and ~a.~%" min max)
       for guess  = (floor (+ min max) 2)
       for answer = (get-feedback guess)
       until (eq answer 'correct)
       if (eq answer 'greater) do (setf min guess)
       else do (setf max guess)
       finally (write-line "I got it!"))))


import std.stdio, std.string;

void main() {
    immutable mnOrig = 1, mxOrig = 10;
    int mn = mnOrig, mx = mxOrig;

    writefln(
    "Think of a number between %d and %d and wait for me to guess it.
    On every guess of mine you should state whether the guess was
    too high, too low, or equal to your number by typing h, l, or =",
            mn, mx);

    LOOP: for (int i = 1; ; i++) {
        immutable guess = (mn + mx) / 2;
        writef("Guess %2d is: %2d. The score for which is (h,l,=): ",
               i, guess);
        immutable string txt = readln().strip().toLower();

        switch (txt) {
            case "h":
                mx = guess - 1;
                break;
            case "l":
                mn = guess + 1;
                break;
            case "=":
                writeln("  Yeehaw!!");
                break LOOP;
            default:
                writefln("  I don't understand your input '%s'.",
                         txt);
                continue LOOP;
        }

        if (mn > mx || mn < mnOrig || mx > mxOrig) {
            writeln("Please check your scoring as" ~
                    " I cannot find the value");
            break;
        }
    }
    writeln("\nThanks for keeping score.");
}


program Guess_the_number;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  system.console;

type
  TCharSet = set of char;

var
  PlayerNumber, CPUNumber: word;
  CPULow: word = 0;
  CPUHi: word = 1000;
  PlayerLow: word = 0;
  PlayerHi: word = 1000;
  CPUWin, PlayerWin: boolean;
  CPUGuessList: string = 'Previus guesses:'#10;
  PlayerGuessList: string = 'Previus guesses:'#10;

function WaitKey(validSet: TCharSet): char;
begin
  repeat
    Result := Console.ReadKey.KeyChar;
  until (Result in validSet);
end;

function QueryNumber(msg: string): Integer;
var
  buf: string;
begin
  repeat
    Console.WriteLine(msg);
    buf := Console.ReadLine.Replace(#10, '').Replace(#13, '');
  until TryStrToInt(buf, result);
end;

procedure Wait;
begin
  Console.ForegroundColor := TConsoleColor.Yellow;
  Console.WriteLine(#10'Press Enter to continue');
  WaitKey([#13]);
  Console.ForegroundColor := TConsoleColor.White;
end;

function PlayLuck: integer;
var
  cpu, player: double;
begin
  cpu := CPUHi - CPULow + 1;
  player := PlayerHi - PlayerLow + 1;

  Result := round(100 * cpu / (cpu + player));
end;

function PlayerTurn: boolean;
var
  guess: word;
begin
  Console.Clear;
  Console.WriteLine('Player Turn({0}%%):'#10, [PlayLuck]);
  Console.ForegroundColor := TConsoleColor.Gray;
  console.WriteLine(PlayerGuessList + #10);

  console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [PlayerLow, PlayerHi]);
  Console.ForegroundColor := TConsoleColor.Red;

  guess := QueryNumber('Enter your guess number:');
  Console.ForegroundColor := TConsoleColor.White;

  if guess > CPUNumber then
  begin
    Console.WriteLine('{0} is to high', [guess]);
    PlayerGuessList := PlayerGuessList + '   ' + guess.tostring + ' is to high'#10;
    PlayerHi := guess - 1;
  end;

  if guess < CPUNumber then
  begin
    Console.WriteLine('{0} is to Low', [guess]);
    PlayerGuessList := PlayerGuessList + '   ' + guess.tostring + ' is to low'#10;
    PlayerLow := guess + 1;
  end;

  Result := guess = CPUNumber;
  if Result then
    Console.WriteLine('Your guess is correct, you rock!')
  else
    Wait;
end;

function CPUTurn: boolean;
var
  guess: word;
  ans: char;
begin
  guess := ((CPUHi - CPULow) div 2) + CPULow;

  Console.Clear;
  Console.WriteLine('CPU Turn({0}%%):'#10, [100 - PlayLuck]);
  Console.ForegroundColor := TConsoleColor.Gray;
  console.WriteLine(CPUGuessList + #10);
  console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [CPULow, CPUHi]);
  Console.ForegroundColor := TConsoleColor.Red;
  Console.WriteLine('My guess number is {0}'#10, [guess]);
  Console.ForegroundColor := TConsoleColor.White;

  Console.WriteLine('Press "l" = too low, "h" = too high, "c" = correct', [guess]);
  ans := WaitKey(['l', 'h', 'c']);

  Result := false;
  case ans of
    'l':
      begin
        CPULow := guess + 1;
        Console.WriteLine(#10'Then my guess is to low'#10);
        CPUGuessList := CPUGuessList + '   ' + guess.tostring + ' is to low'#10;
      end;
    'h':
      begin
        CPUHi := guess - 1;
        Console.WriteLine(#10'Then my guess is to high'#10);
        CPUGuessList := CPUGuessList + '   ' + guess.tostring + ' is to high'#10;
      end
  else
    Result := True;
  end;

  if Result then
    Console.WriteLine(#10'My guess is correct, Good luck in the next time')
  else
    Wait;
end;

begin
  Randomize;
  CPUNumber := Random(1001);
  Console.WriteLine('Press Enter and I will start to guess the number.');

  repeat
    PlayerWin := PlayerTurn();
    if PlayerWin then
      Break;
    CPUWin := CPUTurn();
    if CPUWin then
      Break;
  until false;

  Console.ForegroundColor := TConsoleColor.Green;

  if PlayerWin then
    Console.WriteLine('Player win!')
  else
  begin
    Console.WriteLine('CPU win!');
    Console.WriteLine('If you wanna know, my number was {0}', [CPUNumber]);
  end;

  readln;
end.


defmodule Game do
  def guess(a..b) do
    x = Enum.random(a..b)
    guess(x, a..b, div(a+b, 2))
  end

  defp guess(x, a.._b, guess) when x < guess do
    IO.puts "Is it #{guess}? Too High."
    guess(x, a..guess-1, div(a+guess, 2))
  end
  defp guess(x, _a..b, guess) when x > guess do
    IO.puts "Is it #{guess}? Too Low."
    guess(x, guess+1..b, div(guess+b+1, 2))
  end
  defp guess(x, _, _) do
    IO.puts "Is it #{x}?"
    IO.puts " So the number is: #{x}"
  end
end
Game.guess(1..100)


% Implemented by Arjun Sunel
-module(guess_game).
-export([main/0]).

main() ->
	L = 1 ,	 	% Lower Limit
	U = 100, 	  % Upper Limit

	io:fwrite("Player 1 : Guess my number between ~p and ", [L]),
	io:fwrite("and ~p until you get it right.\n", [U]),
	N = random:uniform(100),
	guess(L,U,N).

guess(L,U,N) ->
	K = (L+U) div 2,
	io:format("Player 2 : Number guessed : ~p~n",[K]),
	if
		K=:=N ->
			io:format("Well guessed!! by Player 2\n");
		true ->
			if
				K > N ->
					io:format("Player 1 : Your guess is too high!\n"),
					guess(L,K,N);
				true ->
					io:format("Player 1 : Your guess is too low!\n"),
					guess(K,U,N)
			end
	end.


include get.e
include wildcard.e

sequence Respons
integer min, max, Guess
min = 0
max = 100

printf(1,"Think of a number between %d and %d.\n",{min,max})
puts(1,"On every guess of mine you should state whether my guess was\n")
puts(1,"too high, too low, or equal to your number by typing 'h', 'l', or '='\n")

while 1 do
    if max < min then
        puts(1,"I think something is strange here...\n")
        exit
    end if
    Guess = floor((max-min)/2+min)
    printf(1,"My guess is %d, is this correct? ", Guess)
    Respons = upper(prompt_string(""))
    if Respons[1] = 'H' then
        max = Guess-1
    elsif Respons[1] = 'L' then
        min = Guess+1
    elsif Respons[1] = '=' then
        puts(1,"I did it!\n")
        exit
    else
        puts(1,"I do not understand that...\n")
    end if
end while


USING: binary-search formatting io kernel math.ranges words ;

: instruct ( -- )
    "Think of a number between 1 and 100." print
    "Score my guess with +lt+ +gt+ or +eq+." print nl ;

: score ( n -- <=> )
    "My guess is %d. " printf readln "math.order" lookup-word ;

: play-game ( -- n )
    100 [1,b] [ score ] search nip nl ;

: gloat ( n -- )
    "I did it. Your number was %d!\n" printf ;

instruct play-game gloat


class Main
{
  public static Void main ()
  {
    Int lowerLimit := 1
    Int higherLimit := 100

    echo ("Think of a number between 1 and 100")
    echo ("Press 'enter' when ready")
    Env.cur.in.readLine

    while (true)
    {
      if (higherLimit < lowerLimit)
      { // check that player is not cheating!
        echo ("Something has gone wrong ... I give up")
        break
      }
      myGuess := (higherLimit + lowerLimit) / 2
      echo ("My guess is $myGuess")
      echo ("Enter 'H' if your number is higher, 'L' if lower, or 'E' if equal")
      switch (Env.cur.in.readLine.trim.upper)
      {
        case "E":
          echo ("I got it correct - thankyou!")
          break // game over
        case "H":
          lowerLimit = myGuess + 1
        case "L":
          higherLimit = myGuess - 1
        default:
          echo ("Pardon? Let's try that again")
      }
    }
  }
}


program Guess_a_number_Player
  implicit none

  integer, parameter :: limit = 100
  integer :: guess, mx = limit, mn = 1
  real :: rnum
  character(1) :: score

  write(*, "(a, i0, a)") "Think of a number between 1 and ", limit, &
                         " and I will try to guess it."
  write(*, "(a)")  "You score my guess by entering: h if my guess is higher than that number"
  write(*, "(a)")  "                                l if my guess is lower than that number"
  write(*, "(a/)") "                                c if my guess is the same as that number"

  call random_seed
  call random_number(rnum)
  guess = rnum * limit + 1
  do
    write(*, "(a, i0, a,)", advance='no') "My quess is: ", guess, "   Score(h, l or c)?: "
    read*, score
    select case(score)
      case("l", "L")
        mn = guess
        guess = (mx-guess+1) / 2 + mn

      case("h", "H")
        mx = guess
        guess = mx - (guess-mn+1) / 2

      case("c", "C")
        write(*, "(a)") "I solved it!"
        exit

      case default
        write(*, "(a)") "I did not understand that"
    end select
  end do
end program


' FB 1.05.0 Win64

Dim hle As String
Dim lowest As Integer = 1
Dim highest As Integer = 20
Dim guess As Integer = 10
Print "Please choose a number between 1 and 20 but don't tell me what it is yet"
Print
Do
  Print "My guess is"; guess
  Do
    Input "Is this higher/lower or equal to your chosen number h/l/e : "; hle
    hle = LCase(hle)
    If hle = "l" AndAlso guess = highest Then
      Print "It can't be more than"; highest; ", try again"
      hle = "i" '' invalid
    ElseIf hle = "h" AndAlso guess = lowest Then
      Print "It can't be less than"; lowest; ", try again"
      hle = "i"
    End If
  Loop Until hle = "h" OrElse hle = "l" OrElse hle = "e"
  If hle = "e" Then
    Print "Good, thanks for playing the gaame with me!"
    Exit Do
  ElseIf hle = "h" Then
    If highest > guess - 1 Then highest = guess - 1
  Else
    If lowest < guess + 1  Then lowest = guess + 1
  End If
  guess = (lowest + highest)\2
Loop
End


package main

import (
    "fmt"
    "sort"
)

func main() {
    lower, upper := 0, 100
    fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
    answer := sort.Search(upper-lower, func (i int) bool {
        fmt.Printf("Is your number less than or equal to %d? ", lower+i)
        s := ""
        fmt.Scanf("%s", &s)
        return s != "" && s[0] == 'y'
    })
    fmt.Printf("Your number is %d.\n", lower+answer)
}


main :: IO ()
main = do
    putStrLn "Please enter the range:"
    putStr   "From: "
    from <- getLine
    putStr   "To: "
    to   <- getLine
    case (from, to) of
         (_) | [(from', "")] <- reads from
             , [(to'  , "")] <- reads to
             , from'         < to' -> loop from' to'
         (_)  -> putStrLn "Invalid input." >> main

loop :: Integer -> Integer -> IO ()
loop from to = do
    let guess = (to + from) `div` 2
    putStrLn $ "Is it " ++ show guess ++ "? ((l)ower, (c)orrect, (h)igher)"
    answer <- getLine
    case answer of
        "c" -> putStrLn "Awesome!"
        "l" -> loop from  guess
        "h" -> loop guess to
        (_) -> putStrLn "Invalid answer." >> loop from to


procedure main ()
  lower_limit := 1
  higher_limit := 100

  write ("Think of a number between 1 and 100")
  write ("Press 'enter' when ready")
  read ()

  repeat {
    if (higher_limit < lower_limit)
      then { # check that player is not cheating!
        write ("Something has gone wrong ... I give up")
        exit ()
      }
    my_guess := (higher_limit + lower_limit) / 2
    write ("My guess is ", my_guess)
    write ("Enter 'H' if your number is higher, 'L' if lower, or 'E' if equal")
    reply := map(trim(read ()))
    case (reply) of {
      "e" : {
        write ("I got it correct - thankyou!")
        exit () # game over
      }
      "h" : lower_limit := my_guess + 1
      "l" : higher_limit := my_guess - 1
      default : write ("Pardon? Let's try that again")
    }
  }
end


100 PROGRAM "GuessIt.bas"
110 LET N=100
120 TEXT 80
130 PRINT "Choose a number between 1 and;" N:PRINT "I will start guess the number."
140 LET BL=1:LET UL=100:LET NR=0
150 DO
160   LET GUESS=INT((BL+UL)/2):LET NR=NR+1
170   SET #102:INK 3:PRINT :PRINT "My";NR;". guess: ";GUESS:SET #102:INK 1
180   LET ANSWER=QUESTION
190   SELECT CASE ANSWER
200   CASE 1
210     LET UL=GUESS-1
220   CASE 2
230     LET BL=GUESS+1
240   CASE ELSE
250   END SELECT
260   IF BL>UL THEN PRINT "You are cheating!":LET ANSWER=9
270 LOOP UNTIL ANSWER=0 OR ANSWER=9
280 PRINT "So the number is:" GUESS
290 DEF QUESTION
300   PRINT "Your number:  1 - Is lower?;  2 - Is higher?;  0 - Is equal?"
310   DO
320     LET K$=INKEY$
330   LOOP UNTIL K$>="0" AND K$<="3"
340   LET QUESTION=VAL(K$)
350 END DEF


require 'misc'
guess=:3 :0
  'lo hi'=.y
  while.lo < hi do.
    smoutput 'guessing a number between ',(":lo),' and ',":hi
    guess=.lo+?hi-lo
    select.{.deb tolower prompt 'is it ',(":guess),'? '
      case.'y'do. smoutput 'Win!' return.
      case.'l'do. lo=.guess+1
      case.'h'do. hi=.guess-1
      case.'q'do. smoutput 'giving up' return.
      case.   do. smouput 'options: yes, low, high, quit'
    end.
  end.
)


import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;

public class GuessNumber {
    public static final int LOWER = 0, UPPER = 100;
    public static void main(String[] args) {
	System.out.printf("Instructions:\n" +
			  "Think of integer number from %d (inclusive) to %d (exclusive) and\n" +
			  "I will guess it. After each guess, you respond with L, H, or C depending\n" +
			  "on if my guess was too low, too high, or correct.\n",
			  LOWER, UPPER);
	int result = Collections.binarySearch(new AbstractList<Integer>() {
		private final Scanner in = new Scanner(System.in);
		public int size() { return UPPER - LOWER; }
		public Integer get(int i) {
		    System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
		    String s = in.nextLine();
		    assert s.length() > 0;
		    switch (Character.toLowerCase(s.charAt(0))) {
		    case 'l':
			return -1;
		    case 'h':
			return 1;
		    case 'c':
			return 0;
		    }
		    return -1;
		}
	    }, 0);
	if (result < 0)
	    System.out.println("That is impossible.");
	else
	    System.out.printf("Your number is %d.\n", result);
    }
}


#!/usr/bin/env js

var DONE = RIGHT = 0, HIGH = 1, LOW = -1;

function main() {
    showInstructions();
    while (guess(1, 100) !== DONE);
}

function guess(low, high) {
    if (low > high) {
        print("I can't guess it. Perhaps you changed your number.");
        return DONE;
    }

    var g = Math.floor((low + high) / 2);
    var result = getResult(g);
    switch (result) {
        case RIGHT:
            return DONE;
        case LOW:
            return guess(g + 1, high);
        case HIGH:
            return guess(low, g - 1);
    }
}

function getResult(g) {
    while(true) {
        putstr('Is it ' + g + '? ');
        var ans = readline().toUpperCase().replace(/^\s+/, '') + ' ';
        switch (ans[0]) {
            case 'R':
                print('I got it! Thanks for the game.');
                return RIGHT;
            case 'L':
                return LOW;
            case 'H':
                return HIGH;
            default:
                print('Please tell me if I am "high", "low" or "right".');
        }
    }
}

function showInstructions() {
    print('Think of a number between 1 and 100 and I will try to guess it.');
    print('After I guess, type "low", "high" or "right", and then press enter.');
    putstr("When you've thought of a number press enter.");
    readline();
}

main();


print("Enter an upper bound: ")
lower = 0
input = readline()
upper = parse(Int, input)

if upper < 1
    throw(DomainError)
end

attempts = 1
print("Think of a number, ", lower, "--", upper, ", then press ENTER.")
readline()
const maxattempts = round(Int, ceil(-log(1 / (upper - lower)) / log(2)))
println("I will need at most ", maxattempts, " attempts ",
    "(⌈-log(1 / (", upper, " - ", lower, ")) / log(2)⌉ = ",
    maxattempts, ").\n")
previous = -1
guess = -1

while true
    previous = guess
    guess = lower + round(Int, (upper - lower) / 2, RoundNearestTiesUp)

    if guess == previous || attempts > maxattempts
        println("\nThis is impossible; did you forget your number?")
        exit()
    end

    print("I guess ", guess, ".\n[l]ower, [h]igher, or [c]orrect? ")
    input = chomp(readline())

    while input ∉ ["c", "l", "h"]
        print("Please enter one of \"c\", \"l\", or \"h\". ")
        input = chomp(readline())
    end

    if input == "l"
        upper = guess
    elseif input == "h"
        lower = guess
    else
        break
    end

    attempts += 1
end

println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")


// version 1.0.5-2

fun main(args: Array<String>) {
    var hle: Char
    var lowest  = 1
    var highest = 20
    var guess   = 10
    println("Please choose a number between 1 and 20 but don't tell me what it is yet\n")

    while (true) {
        println("My guess is $guess")

        do {
            print("Is this higher/lower than or equal to your chosen number h/l/e : ")
            hle = readLine()!!.first().toLowerCase()
            if (hle == 'l' && guess == highest) {
                println("It can't be more than $highest, try again")
                hle = 'i' // signifies invalid
            }
            else if (hle == 'h' && guess == lowest) {
                println("It can't be less than $lowest, try again")
                hle = 'i'
            }
        }
        while (hle !in "hle")

        when (hle) {
            'e' -> { println("Good, thanks for playing the game with me!") ; return }
            'h' ->   if (highest > guess - 1) highest = guess - 1
            'l' ->   if (lowest  < guess + 1) lowest  = guess + 1
        }

        guess = (lowest + highest) / 2
    }
}


mini=0
maxi=100

print "Think of a number between ";mini;" and ";maxi
print "Each time I guess a number you must state whether my"
print "guess was too high, too low, or equal to your number."
print

while response$<>"="
   if not(mini<=maxi) then
		print "Error"
		exit while
	end if
	guess=int((maxi-mini)/2)+mini
	print "My guess is ";guess;". Type L for low, H for high, = for correct."
	input response$
	response$=upper$(response$)
	select case response$
		case "L"
			mini=guess+1
		case "H"
         maxi=guess-1
		case "="
			print guess;" is correct."
			exit while
		case else
			print "Your response was not helpful."
	end select
 wend
print "Thanks for playing."


function wait(waittime)--wait function is used so that app will not quit immediately
  local timer = os.time()
  repeat until os.time() == timer + waittime
end

upperBound = 100
lowerBound = 0
print("Think of an integer between 1 to 100.")
print("I will try to guess it.")
while true do
	upper1 = upperBound+1
	upper2 = upperBound-1
	if upperBound == lowerBound or upper1 == lowerBound or upper2 == lowerBound or lowerBound > upperBound then--make sure player is not cheating
		io.write("You're cheating! I'm not playing anymore. Goodbye.")
		wait(3)
		break
	else
		Guess = math.floor((upperBound + lowerBound)/2)--guessing mechanism
		print("My guess is: "..Guess..". Is it too high, too low, or correct? (h/l/c)")
		input = io.read()

	if input == "h" then --higher
		upperBound = Guess
	elseif input == "l" then --lower
		lowerBound = Guess
	elseif input == "c" then --correct
		io.write("So I win? Thanks for playing with me.")
		wait(3)
		break
	else
		print("Invalid input. Please try again. ")
		end
	end
end


guessnumber[min0_, max0_] :=
  DynamicModule[{min = min0, max = max0, guess, correct = False},
   guess[] := [email protected]@{min, max};
   [email protected][correct, [email protected]{"Your number is ", guess[], "."},
     [email protected]{[email protected]{"I guess ", guess[], "."},
       [email protected]{Button["too high", max = guess[]],
         Button["too low", min = guess[]],
         Button["correct", correct = True]}}]];
guessnumber[1, 100]


function GuessNumberFeedbackPlayer

    lowVal = input('Lower limit: ');
    highVal = input('Upper limit: ');
    fprintf('Think of your number. Press Enter when ready.\n')
    pause
    nGuesses = 1;
    done = false;
    while ~done
        guess = floor(0.5*(lowVal+highVal));
        score = input(sprintf( ...
            'Is %d too high (H), too low (L), or equal (E)? ', guess), 's');
        if any(strcmpi(score, {'h' 'hi' 'high' 'too high' '+'}))
            highVal = guess-1;
            nGuesses = nGuesses+1;
        elseif any(strcmpi(score, {'l' 'lo' 'low' 'too low' '-'}))
            lowVal = guess+1;
            nGuesses = nGuesses+1;
        elseif any(strcmpi(score, {'e' 'eq' 'equal' 'right' 'correct' '='}))
            fprintf('Yay! I win in %d guesses.\n', nGuesses)
            done = true;
        else
            fprintf('Unclear response. Try again.\n')
        end
        if highVal < lowVal
            fprintf('Incorrect scoring. No further guesses.\n')
            done = true;
        end
    end
end


inclusiveRange = [1,100]
lowRange = inclusiveRange.x
maxRange = inclusiveRange.y
guesses = 1
inf =  "Think of a number between % and % and I will try to guess it.\n" +\
		"Type -1 if the guess is less than your number,\n"+\
		"0 if the guess is correct, " +\
		"or 1 if it's too high.\nPress esc to exit.\n"
clearListener()
format inf (int lowRange) (int maxRange)
while not keyboard.escpressed do
(
	local chosen = ((lowRange + maxRange) / 2) as integer
	if lowRange == maxRange do format "\nHaving fun?"
	format "\nI choose %.\n" chosen
	local theAnswer = getKBValue prompt:"Answer? "
	case theAnswer of
	(
		(-1): (lowRange = chosen; guesses += 1)
		(0): (format "\nYay. I guessed your number after % %.\n" \
				guesses (if guesses == 1 then "try" else "tries")
				exit with OK)
		(1): (maxRange = chosen; guesses += 1)
		default: (format "\nI don't understand your input.")
	)
)


MODULE raden;

IMPORT  InOut;

VAR     done, ok                : BOOLEAN;
        guess, upp, low         : CARDINAL;
        res                     : CHAR;

BEGIN
  InOut.WriteString ("Choose a number between 0 and 1000.");
  InOut.WriteLn;
  InOut.WriteLn;
  upp := 1000;
  low := 0;
  REPEAT
    ok := FALSE;
    guess := ( ( upp - low ) DIV 2 ) + low;
    InOut.WriteString ("My guess is");  InOut.WriteCard (guess, 4);     InOut.Write (11C);
    InOut.WriteString ("How did I score? 'L' = too low, 'H' = too high, 'Q' = OK : ");
    InOut.WriteBf;
    REPEAT
      InOut.Read (res);
      res := CAP (res)
    UNTIL  (res = 'Q') OR (res = 'L') OR (res = 'H');
    CASE  res  OF
      'L'       : low := guess  |
      'H'       : upp := guess
    ELSE
      ok := TRUE
    END;
  UNTIL ok;
  InOut.WriteString ("So the number is");       InOut.WriteCard (guess, 4);
  InOut.WriteLn;
  InOut.WriteString ("Thanks for letting me play with you.");
  InOut.WriteLn
END raden.


import strutils

let oRange = 1..10
var iRange = oRange

echo """Think of a number between $# and $# and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =""".format(iRange.a, iRange.b)

var i = 0
while true:
  inc i
  let guess = (iRange.a + iRange.b) div 2
  stdout.write "Guess $# is: $#. The score for which is (h,l,=): ".format(i, guess)
  let txt = stdin.readLine()

  case txt
  of "h": iRange.b = guess - 1
  of "l": iRange.a = guess + 1
  of "=":
    echo "  Ye-Haw!!"
    break
  else: echo "  I don't understand your input of '%s'?".format(txt)

  if iRange.a > iRange.b or iRange.a < oRange.a or iRange.b > oRange.b:
    echo "Please check your scoring as I cannot find the value"
    break

echo "Thanks for keeping score."


10 PRINT "THINK OF A NUMBER BETWEEN 1 AND";" 9, AND I'LL TRY TO GUESS IT."
20 ISVALID=0
30 GUESS=5
40 PRINT "I GUESS"GUESS"."
50 INPUT "IS THAT HIGHER THAN, LOWER THAN OR EQUAL TO YOUR NUMBER? ",ANSWER$
60 IF ANSWER$="LOWER THAN" THEN ISVALID=1:IF GUESS<9 THEN GUESS=GUESS+1
70 IF ANSWER$="HIGHER THAN" THEN ISVALID=1:IF GUESS>1 THEN GUESS=GUESS-1
80 IF ANSWER$="EQUAL TO" THEN PRINT "OH YES! I GUESSED CORRECTLY!":END
90 IF ISVALID=0 THEN PRINT "SORRY";", BUT THAT ANSWER IS INVALID."
100 GOTO 40


#import <Foundation/Foundation.h>

@interface GuessNumberFakeArray : NSArray {
  int lower, upper;
}
- (instancetype)initWithLower:(int)l andUpper:(int)u;
@end

@implementation GuessNumberFakeArray
- (instancetype)initWithLower:(int)l andUpper:(int)u {
  if ((self = [super init])) {
    lower = l;
    upper = u;
  }
  return self;
}
- (NSUInteger)count { return upper-lower; }
- (id)objectAtIndex:(NSUInteger)i {
  printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", lower + (int)i);
  char input[2] = " ";
  scanf("%1s", input);
  switch (tolower(input[0])) {
    case 'l':
      return @-1;
    case 'h':
      return @1;
    case 'c':
      return @0;
  }
  return nil;
}
@end

#define LOWER 0
#define UPPER 100

int main(int argc, const char *argv[]) {
  @autoreleasepool {

    printf("Instructions:\n"
           "Think of integer number from %d (inclusive) to %d (exclusive) and\n"
           "I will guess it. After each guess, you respond with L, H, or C depending\n"
           "on if my guess was too low, too high, or correct.\n",
           LOWER, UPPER);
    NSUInteger result = [[[GuessNumberFakeArray alloc] initWithLower:LOWER andUpper:UPPER]
                         indexOfObject:[NSNumber numberWithInt: 0]
                         inSortedRange:NSMakeRange(0, UPPER - LOWER)
                               options:0
                       usingComparator:^(id x, id y){ return [x compare: y]; }];
    if (result == NSNotFound)
      printf("That is impossible.\n");
    else
      printf("Your number is %d.", LOWER + (int)result);

  }
  return 0;
}


guessnumber2(b)={
my(c=0,d=b,a=0);
for(x=1,b,
    for(y=1,b,
        if(a<c||a==c||a==d||a>d,
           a=random(b),
           break()
          )
     );
     print("I guess "a" am I h,l,or e ?");
     g=input();
     if(g==h,
     d=a,
     if(g==l,
        c=a,
        if(g==e,
           break()
        )
     )
  )
 );
}


Program GuessIt(input, output);

var
  done, ok:        boolean;
  guess, upp, low: integer;
  res:             char;

begin
  writeln ('Choose a number between 0 and 1000.');
  write ('Press Enter and I will start to guess the number.');
  readln;
  upp := 1000;
  low := 0;
  repeat
    ok := false;
    guess := ( ( upp - low ) div 2 ) + low;
    write ('My guess is: ', guess:4);
    write ('. How did i score? ''l'' = too low, ''h'' = too high, ''c'' = correct : ');
    repeat
      readln (res);
      res := lowercase(res);
    until (res = 'c') or (res = 'l') or (res = 'h');
    case  res  of
      'l': low := guess;
      'h': upp := guess;
    else
      ok := true
    end;
  until ok;
  writeln ('So the number is: ', guess:4);
  writeln ('It was nice to play with you.');
end.


#!/usr/bin/perl

my $min = 1;
my $max = 99;
my $guess = int(rand $max) + $min;
my $tries = 0;

print "=>> Think of a number between $min and $max and I'll guess it!\n
Press <ENTER> when are you ready... ";

<STDIN>;

{
    do {

        $tries++;
        print "\n=>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e)\n> ";

        my $score = <STDIN>;

        if ($max <= $min) {
            print "\nI give up...\n" and last;
        } elsif ($score =~ /^h/i) {
            $min = $guess + 1;
        } elsif ($score =~ /^l/i) {
            $max = $guess;
        } elsif ($score =~ /^e/i) {
            print "\nI knew it! It took me only $tries tries.\n" and last;
        } else {
            print "error: invalid score\n";
        }

        $guess = int(($max + $min) / 2);

    } while(1);
}


--
-- 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()


(de guessTheNumber (Min Max)
   (prinl "Think of a number between " Min " and " Max ".")
   (prinl "On every guess of mine you should state whether my guess was")
   (prinl "too high, too low, or equal to your number by typing 'h', 'l', Or '='")
   (use Guess
      (loop
         (NIL (> Max Min)
            (prinl "I think somthing is strange here...") )
         (prin
            "My guess is "
            (setq Guess (+ Min (/ (- Max Min) 2)))
            ",is this correct? " )
         (flush)
         (NIL
            (case (uppc (car (line)))
               ("H" (setq Max Guess))
               ("L" (setq Min Guess))
               ("=" (nil (prinl "I did it!")))
               (T (prinl "I do not understand that...")) ) ) ) ) )


min(1). max(10).

pick_number(Min, Max) :-
    min(Min), max(Max),
    format('Pick a number between ~d and ~d, and I will guess it...~nReady? (Enter anything when ready):', [Min, Max]),
    read(_).

guess_number(Min, Max) :-
    Guess is (Min + Max) // 2,
    format('I guess ~d...~nAm I correct (c), too low (l), or too high (h)? ', [Guess]),
    repeat,
        read(Score),
        ( Score = l -> NewMin is Guess + 1, guess_number(NewMin, Max)
        ; Score = h -> NewMax is Guess - 1, guess_number(Min, NewMax)
        ; Score = c -> writeln('I am correct!')
        ; writeln('Invalid input'),
          false
        ).

play :-
    pick_number(Min, Max),
    guess_number(Min, Max).


min=0
max=100

If OpenConsole()
  PrintN("Think of a number between "+Str(min)+" and "+Str(max)+".")
  PrintN("On every guess of mine you should state whether my guess was")
  PrintN("too high, too low, or equal to your number by typing 'h', 'l', Or '='")
  Repeat
    If max<=min
      PrintN("I think somthing is strange here...")
      Break
    EndIf
    Guess=(max-min)/2+min
    Print("My guess is "+Str(Guess)+",is this correct? "): Respons.s=UCase(Input())
    If Respons="H":     max=Guess-1
    ElseIf Respons="L": min=Guess+1
    ElseIf Respons="="
      PrintN("I did it!")
      Break
    Else
      PrintN("I do not understand that...")
    EndIf
  ForEver
EndIf


inclusive_range = mn, mx = (1, 10)

print('''\
Think of a number between %i and %i and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =
''' % inclusive_range)

i = 0
while True:
    i += 1
    guess = (mn+mx)//2
    txt = input("Guess %2i is: %2i. The score for which is (h,l,=): "
                % (i, guess)).strip().lower()[0]
    if txt not in 'hl=':
        print("  I don't understand your input of '%s' ?" % txt)
        continue
    if txt == 'h':
        mx = guess-1
    if txt == 'l':
        mn = guess+1
    if txt == '=':
        print("  Ye-Haw!!")
        break
    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):
        print("Please check your scoring as I cannot find the value")
        break

print("\nThanks for keeping score.")


  [ [ $ "lower higher equal" nest$ ]
    constant ]                       is responses (   --> $ )

  [  trim reverse
     trim reverse
     $ "" swap witheach
       [ lower join ] ]              is cleanup   ( $ --> $ )

  [ $ "Think of a number from 1 to"
    $ " 100 and press enter." join
    input drop
    0 temp put
    [] 100 times [ i 1+ join ]
    [ dup size 0 = iff
        [ say "Impossible!" cr 0 ]
        done
      dup size 2 / split behead
      dup temp replace
      say "I guess " echo say "." cr
      $ "lower, higher or equal? "
      input cleanup responses find
      [ table
        [ nip false ]
        [ drop false ]
        [ say "I guessed it!"
          cr true ]
        [ say "I do not understand."
          temp share swap join join
          cr false ] ]
      do until ]
  2drop temp release ]               is play      (   -->   )


guessANumberPlayer <- function(low, high)
{
  boundryErrorCheck(low, high)
  repeat
  {
    guess <- floor(mean(c(low, high)))
    #Invalid inputs to this switch will simply cause the repeat loop to run again, breaking nothing.
    switch(guessResult(guess),
           l = low <- guess + 1,
           h = high <- guess - 1,
           c = return(paste0("Your number is ", guess, ".", " I win!")))
  }
}

#Copied from my solution at https://rosettacode.org/wiki/Guess_the_number/With_feedback#R
boundryErrorCheck <- function(low, high)
{
  if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
  if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
  if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
  if(low == high) stop("This game is impossible to lose. Try again.")
  invisible()
}

guessResult <- function(guess) readline(paste0("My guess is ", guess, ". If it is too low, submit l. If it is too high, h. Otherwise, c. "))


#lang racket

(define (guess low high)
  (define (input-loop available)
    (define input (car (string->list (symbol->string (read)))))
    (if (member input available)
        input
        (begin
          (printf "Invalid Input\n") (input-loop available))))

  (define (guess-loop low high)
    (define guess (floor (/ (+ low high) 2)))
    (printf "My guess is ~a.\n" guess)
    (define input (input-loop (list #\c #\l #\h)))
    (case input
      ((#\c) (displayln "I knew it!\n"))
      ((#\l) (guess-loop low (sub1 guess)))
      ((#\h) (guess-loop (add1 guess) high))))

  (printf "Think of a number between ~a and ~a.
Use (h)igh, (l)ow and (c)orrect to guide me.\n" low high)
  (guess-loop low high))


multi sub MAIN() { MAIN(0, 100) }
multi sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {
    say "Think of a number between $min and $max and I'll guess it!";
    while $min <= $max {
        my $guess = (($max + $min)/2).floor;
        given lc prompt "My guess is $guess. Is your number higher, lower or equal? " {
            when /^e/ { say "I knew it!"; exit }
            when /^h/ { $min = $guess + 1      }
            when /^l/ { $max = $guess          }
            default   { say "WHAT!?!?!"        }
        }
    }
    say "How can your number be both higher and lower than $max?!?!?";
}


Red[]

lower: 1
upper: 100
print ["Please think of a number between" lower "and" upper]

forever [
    guess: to-integer upper + lower / 2
    print ["My guess is" guess]
    until [
        input: ask "Is your number (l)ower, (e)qual to, or (h)igher than my guess? "
        find ["l" "e" "h"] input
    ]
    if "e" = input [break]
    either "l" = input [upper: guess] [lower: guess]
]

print ["I did it! Your number was" guess]


/*REXX program plays  guess─the─number  (with itself)  with  positive integers.         */
parse arg low high seed .                        /*obtain optional arguments from the CL*/
if  low=='' |  low=="," then  low=    1          /*Not specified?  Then use the default.*/
if high=='' | high=="," then high= 1000          /* "      "         "   "   "     "    */
if datatype(seed, 'W')  then call random ,,seed  /*Useful seed?  Then use a random seed.*/
?= random(low, high)                             /*generate random number from low->high*/
$= "──────── Try to guess my number  (it's between  "        /*part of a prompt message.*/
g=                                                           /*nullify the first guess. */
    do #=1;                        oldg= g       /*save the guess for later comparison. */
    if pos('high', info)\==0  then high= g       /*test if the guess is too  high.      */
    if pos('low' , info)\==0  then low = g       /*  "   "  "    "    "  "   low.       */
    say                                          /*display a blank line before prompt.  */
    say $ low  '  and  '   high  "  inclusive):" /*issue the prompt message to terminal.*/
    say                                          /*display a blank line  after prompt.  */
    g= (low +  (high - low) / 2)   / 1           /*calculate the next guess & normalize.*/
    if g=oldg   then g= g + 1                    /*bump guess by one 'cause we're close.*/
    say 'My guess is'       g                    /*display computer's guess to the term.*/
    if g=?  then leave                           /*this guess is correct; leave & inform*/
    if g>?  then info= right(' Your guess is too high.', 60, "─")
            else info= right(' Your guess is too low.' , 60, "─")
    say info
    end   /*try*/
say                                              /*stick a fork in it,  we're all done. */
say 'Congratulations!   You guessed the secret number in'    #    "tries."


min = 1
max = 100
see "think of a number between " + min + " and " + max + nl
see "i will try to guess your number." + nl
while true
      guess =floor((min + max) / 2)
      see "my guess is " + guess + nl
      see "is it higher than, lower than or equal to your number " give answer
      ans = left(answer,1)
      switch ans
             on "l" min = guess + 1
             on "h" max = guess - 1
             on "e" exit
             other see "sorry, i didn't understand your answer." + nl
      off
end
see "goodbye." + nl


def play(low, high, turns=1)
  num = (low + high) / 2
  print "guessing #{num}\t"
  case is_it?(num)
  when 1
    puts "too high"
    play(low, num - 1, turns + 1)
  when -1
    puts "too low"
    play(num + 1, high, turns + 1)
  else
    puts "found the number in #{turns} turns."
  end
end

def is_it?(num)
  num <=> $number
end

low, high = 1, 100
$number = rand(low .. high)

puts "guess a number between #{low} and #{high}"
play(low, high)


use std::io::stdin;

const MIN: isize = 1;
const MAX: isize = 100;

fn main() {
    loop {
        let mut min = MIN;
        let mut max = MAX;
        let mut num_guesses = 1;
        println!("Please think of a number between {} and {}", min, max);
        loop {
            let guess = (min + max) / 2;
            println!("Is it {}?", guess);
            println!("(type h if my guess is too high, l if too low, e if equal and q to quit)");

            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) {
                Some('H') => {
                    max = guess - 1;
                    num_guesses += 1;
                },
                Some('L')=> {
                    min = guess + 1;
                    num_guesses += 1;
                },
                Some('E') => {
                    if num_guesses == 1 {
                        println!("\n*** That was easy! Got it in one guess! ***\n");
                    } else {
                        println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses);
                    }
                    break;
                },
                Some('Q') => return,
                _ => println!("Sorry, I didn't quite get that. Please try again.")
            }
        }
    }
}


object GuessNumber extends App {
  val n = 1 + scala.util.Random.nextInt(20)

  println("Guess which number I've chosen in the range 1 to 20\n")
  do println("Your guess, please: ")
  while (io.StdIn.readInt() match {
    case `n` => println("Correct, well guessed!"); false
    case guess if (n + 1 to 20).contains(guess) => println("Your guess is higher than the chosen number, try again"); true
    case guess if (1 until n).contains(guess) => println("Your guess is lower than the chosen number, try again"); true
    case _ => println("Your guess is inappropriate, try again"); true
  })

}


(define minimum 1)   (define maximum 100)

(display "Enter a number from ")(display minimum)
(display " to ")(display maximum)(display ": ")
(define number (read))

(define input "")

(do ((guess (round (/ (+ maximum minimum) 2))  (round (/ (+ maximum minimum) 2))))
                ((string= input "="))
        (display "Is it ")(display guess)(display "?\n(h/l/=) > ")
        (set! input (symbol->string (read)))
        (if (string= input "h") (begin (display "OK...")
                (set! maximum (- guess 1))))
        (if (string= input "l") (begin (display "OK...")
                (set! minimum (+ guess 1)))))
(display "I was RIGHT!\n")


$ include "seed7_05.s7i";
$ include "keybd.s7i";

const proc: main is func
  local
    var boolean: okay is FALSE;
    var boolean: quit is FALSE;
    var integer: low is 1;
    var integer: high is 1000;
    var integer: guess is 0;
    var char: command is ' ';
  begin
    writeln("Choose a number between 1 and 1000.");
    write("Press Enter and I will start to guess the number.");
    readln;
    repeat
      guess := low + (high - low) div 2;
      write("My guess is: " <& guess);
      write(". How did I score (l=too low, h=too high, c=correct, q=quit)? ");
      flush(OUT);
      repeat
        command := lower(getc(KEYBOARD));
      until command in {'l', 'h', 'c', 'q'};
      writeln(command);
      case command of
        when {'l'}: low := succ(guess);
        when {'h'}: high := pred(guess);
        when {'c'}: okay := TRUE;
        when {'q'}: quit := TRUE;
      end case;
    until quit or okay or low > high;
    if not quit then
      writeln("So the number is: " <& guess);
      if low > high then
        writeln("Why did you cheat?");
      end if;
    end if;
    writeln("It was nice to play with you.");
  end func;


var min = 1
var max = 99
var tries = 0
var guess = pick(min..max)

print <<"EOT".chomp
\n=>> Think of a number between #{min} and #{max} and I'll guess it!\n
Press <ENTER> when are you ready...
EOT

STDIN.readline

loop {
    print <<-EOT.chomp
    \n=>> My guess is: #{guess} Is your number higher, lower, or equal? (h/l/e)
    >#{' '}
    EOT

    ++tries
    given (STDIN.readline) {
        case (max <= min) {
            say "\nI give up..."
            break
        }
        when (/^h/i) {
            min = guess+1
        }
        when (/^l/i) {
            max = guess
        }
        when (/^e/i) {
            say "\nI knew it! It took me only #{tries} tries."
            break
        }
        default {
            say "error: invalid score"
            next
        }
    }

    guess = ((min+max) // 2)
}


Object subclass: #NumberGuesser
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'Rosettacode'


structure GuessNumberHelper : MONO_ARRAY = struct
  type elem = order
  type array = int * int
  fun length (lo, hi) = hi - lo
  fun sub ((lo, hi), i) =
    let
      val n = lo + i
    in
      print ("My guess is: " ^ Int.toString (lo+i) ^ ". Is it too high, too low, or correct? (H/L/C) ");
      let
        val str = valOf (TextIO.inputLine TextIO.stdIn)
      in
        case Char.toLower (String.sub (str, 0)) of
          #"l" => GREATER
        | #"h" => LESS
        | #"c" => EQUAL
      end
    end

  (* dummy implementations for not-needed functions *)
  type vector = unit
  val maxLen = Array.maxLen
  fun update _ = raise Domain
  fun array _ = raise Domain
  fun fromList _ = raise Domain
  fun tabulate _ = raise Domain
  fun vector _ = raise Domain
  fun copy _ = raise Domain
  fun copyVec _ = raise Domain
  fun appi _ = raise Domain
  fun app _ = raise Domain
  fun modifyi _ = raise Domain
  fun modify _ = raise Domain
  fun foldli _ = raise Domain
  fun foldl _ = raise Domain
  fun foldri _ = raise Domain
  fun foldr _ = raise Domain
  fun findi _ = raise Domain
  fun find _ = raise Domain
  fun exists _ = raise Domain
  fun all _ = raise Domain
  fun collate _ = raise Domain
end

structure GuessNumberBSearch = BSearchFn (GuessNumberHelper)

val lower = 0
val upper = 100;

print ("Instructions:\n" ^
       "Think of integer number from " ^ Int.toString lower ^
       " (inclusive) to " ^ Int.toString upper ^ " (exclusive) and\n" ^
       "I will guess it. After each guess, you respond with L, H, or C depending\n" ^
       "on if my guess was too low, too high, or correct.\n");

case GuessNumberBSearch.bsearch (fn (_, x) => x) ((), (lower, upper)) of
  NONE => print "That is impossible.\n"
| SOME (result, _) => print ("Your number is " ^ Int.toString result ^ ".\n")


import Cocoa

var found = false
let fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter an integer between 1 and 100 for me to guess: ")
let data = fh.availableData
var num:Int!
var low = 0.0
var high = 100.0
var lastGuess:Double!

if let numFromData = NSString(data: data, encoding: NSUTF8StringEncoding)?.intValue {
    num = Int(numFromData)
}

func guess() -> Double? {
    if (high - low == 1) {
        println("I can't guess it. I think you cheated.");
        return nil
    }

    return floor((low + high) / 2)
}

while (!found) {
    if let guess = guess() {
        lastGuess = guess

    } else {
        break
    }
    println("My guess is: \(Int(lastGuess))")
    println("How was my guess? Enter \"higher\" if it was higher, \"lower\" if it was lower, and \"correct\" if I got it")
    let data = fh.availableData
    let str = NSString(data: data, encoding: NSUTF8StringEncoding)
    if (str == nil) {
        continue
    }
    if (str! == "correct\n") {
        found = true
        println("I did it!")
    } else if (str! == "higher\n") {
        low = lastGuess
    } else if (str! == "lower\n") {
        high = lastGuess
    }
}


set from 1
set to 10
fconfigure stdout -buffering none
while 1 {
    set guess [expr {($from+$to) / 2}]
    puts -nonewline "Guess: $guess\tWas it lower (<) equal (=) or higher (>)? "
    switch -- [gets stdin] {
	< { set from [expr {$guess + 1}] }
	> { set to [expr {$guess - 1}] }
	= {
	    puts "Found it: $guess"
	    break
	}
	default {
	    puts "What sort of a response was that?!"
	}
    }
    if {$to < $from} {
	puts "No answer possible?!"
	break
    }
}


read -p "Lower bound: " lower
read -p "Upper bound: " upper
moves=0
PS3="> "
while :; do
    ((moves++))
    guess=$(( lower + (upper-lower)/2 ))
    echo "Is it $guess?"
    select ans in "too small" "too big" "got it!"; do
        case $ans in
            "got it!")   break 2 ;;
            "too big")   upper=$(( upper==guess ? upper-1 : guess )); break ;;
            "too small") lower=$(( lower==guess ? lower+1 : guess )); break ;;
        esac
    done
    ((lower>upper)) && echo "you must be cheating!"
done
echo "I guessed it in $moves guesses"


Sub GuessNumberPlayer()
Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer
Dim vSolved As Variant
On Error GoTo ErrHandler
MsgBox "Pick a number between 1 and 100. I will guess it!", vbInformation + vbOKOnly, "Rosetta Code | Guess the Number Player"
iCount = 0
iLow = 1
iHigh = 100
Do While Not vSolved = "Y"
    iGuess = Application.WorksheetFunction.RandBetween(iLow, iHigh)
    iCount = iCount + 1
CheckGuess:
    vSolved = InputBox("My guess: " & iGuess & vbCr & vbCr & "Y = Yes, correct guess" & vbCr & _
        "H = your number is higher" & vbCr & "L = your number is lower" & vbCr & "X = exit game", "Rosetta Code | Guess the Number Player | Guess " & iCount)
    Select Case vSolved
        Case "Y", "y":              GoTo CorrectGuess
        Case "X", "x":              Exit Sub
        Case "H", "h":              iLow = iGuess + 1
        Case "L", "l":              iHigh = iGuess - 1
        Case Else:                  GoTo CheckGuess
    End Select
Loop
CorrectGuess:
    MsgBox "I guessed number " & iGuess & " in just " & iCount & " attempts!", vbExclamation + vbOKOnly, "Rosetta Code | Guess the Number Player"
    Exit Sub
ErrHandler:
    MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!"
End Sub