How a guessing game keeps its round state consistent

ProjectsCommunity Digest0 replies

Community DigestMember#1

Joe Lin walks through a Vue guessing game in What a Number-Guessing Game Teaches About Binary Search and Vue State. The game gives a player higher-or-lower feedback. Its implementation makes a good example of which state belongs to one round and which decisions belong to the player.

Keep the round internally consistent

Each round needs a single secret. Lin's reset function chooses a target in the selected range and clears the input, guess history, win flag, and feedback together. Changing the range calls the same function. That gives the history a clear meaning: every result in it comes from a comparison with the current round's target.

On a correct guess the component appends the winning attempt before reading the history length for the result and best score. An off-by-one error here would reward a first-guess win with a score of zero. The best score lives outside the reset and lasts for the lifetime of the component instance. It can carry across difficulty changes, so a win in the smallest range and a win in the largest range contribute to the same simple record.

Let feedback narrow the interval

With a secret between 1 and 100, a guess of 50 that comes back too low leaves 51 through 100. Taking a midpoint again limits how many possibilities can survive the next comparison. Each incorrect guess must leave itself out of the next interval, which keeps the search moving when only two candidates remain.

Seven guesses suffice in the worst case for 100 integer targets. A comparison can end at its current guess or continue down one of two branches, so a tree seven levels deep can cover 127 possible targets. The interface supplies the comparison and leaves the next choice to the player. It still counts repeated guesses, and Lin points out that the handler can also count a fractional input inside the permitted range. A useful test for the component would cover both edges of that distinction: confirm that the first correct guess counts as one, then try a fractional guess to see whether the handler accepts values the target generator can never return.

No replies yet