librarygames/guess/NumberGuess.xtl

Guess the number's rules, a library: guess.xtl (scripted games), play.xtl (at the terminal) and the web page all use these. The computer thinks of a number from 1 to 100; each guess is answered higher, lower or correct.

source

ˡtop : Int

value · line 8

The largest number the player may pick.

ˡtop ← 100

ˡn̲ew : Int -> Int

function · line 11

A new game: the secret, 1 to n.

ˡn̲ew ← { n → r̲oll! n }
Used in: t, t

ˡm̲ove : (Ord a, Num b, Truthy b) => a -> a -> b

function · line 16

The answer to guess g for secret t: -1 the secret is higher, 1 lower, 0 right; the sign of the difference as a fork, (t < g) - (t > g). Item by item, so it answers many guesses (or games) at once.

ˡm̲ove ← { t g → t [< − >] g }

ˡs̲tatus : (Eq a, Truthy b) => a -> a -> b

function · line 19

1 once the guess is right.

ˡs̲tatus ← { t g → t = g }

ˡr̲eply : Int -> Char

function · line 22

The answer as the BASIC printed it.

ˡr̲eply ← { r → d̲isclose (2 + r) s̲elect "HIGHER!" "CORRECT! YOU GUESSED IT." "LOWER!" }

ˡg̲uess : Int -> Int

function · line 27

The halving player: the range still possible, low and high, as a 2-row matrix with a column per game; its guess is the middle.

ˡg̲uess ← { b → ('+ r̲/ b) d̲iv 2 }

ˡn̲arrow : Num a => Int -> a -> Int

function · line 32

Narrow every range by the answers to its guess: a higher answer raises the low end past the guess, a lower one drops the high end below it (a max and a min that leave the other answers alone).

ˡn̲arrow ← { b r →
  g ← ˡg̲uess b
  lo ← (1 s̲elect b) m̲ax (g + 1) × r = -1
  hi ← (2 s̲elect b) m̲in (g − 1) + ˡtop × r ≠ 1
  (2 c̲at s̲hape lo) r̲eshape lo c̲at hi
}

ˡp̲ossible : Truthy a => Int -> Int -> a

function · line 44

The secrets still possible after guesses gs were answered for secret t: every candidate 1 to 100 against every guess at once (a table of answers, candidates by guesses), kept where its whole row agrees with the answers t got: a 0/1 vector of 100.

ˡp̲ossible ← { t gs →
  m ← (r̲ange ˡtop) 'ˡm̲ove t̲able gs
  '∧ r̲/₂ m = (s̲hape m) r̲eshape ˡtop 'r̲ight t̲able t ˡm̲ove gs
}