A hidden word and a partly revealed word are different pieces of information. Start by keeping both. This first program inspects a fixed guess; it does not read the keyboard yet.
Use Sinclair BASIC on a stock 48K Spectrum. Begin with a new program. Meet BASIC gives a slower introduction to entering and editing listings if you need it. BASIC line numbers determine execution order; the gaps leave room for later additions.
10 BORDER 0: PAPER 0: INK 7: BRIGHT 0: CLS
200 LET w$="BOTTLE": LET g$="T"
250 LET d$="": LET found=0
260 FOR i=1 TO LEN w$: LET d$=d$+"_": NEXT i
400 FOR i=1 TO LEN w$
410 IF w$(i)=g$ THEN LET d$(i TO i)=g$: LET found=found+1
420 NEXT i
500 PRINT "Word: ";d$
510 PRINT "Matches: ";found
520 STOPRUN should display Word: __TT__ and Matches: 2, followed by the STOP report. The report is deliberate: there is nothing else to do yet. The word BOTTLE stays in w$, while d$ contains only what the guess revealed.
Keep the answer separate
A variable ending in $ holds text, called a string. Quotation marks surround literal text; they are not part of the stored word. LET assigns a value. At line 250, "" makes an empty string. Adding "_" joins another underscore to its end.
LEN returns the number of characters. The FOR/NEXT loop at 260 builds six underscores because BOTTLE has six letters. Its counter i visits 1 through 6. Colons separate several statements on one numbered line.
The second loop examines the answer. w$(i) reads one character; string positions begin at one. IF compares it with g$, the guessed letter. When they match, LET d$(i TO i)=g$ replaces that one-character slice of the revealed string. The rest stays intact. THEN runs the remaining statements on that line only when the comparison is true.
The loop keeps going after a match. Both Ts are therefore revealed, and found increases twice. A search that stopped at the first match would hide information the player had earned.
If the fixed guess becomes L, what should the two output lines show?
Show the explanation
They should show Word: ____L_ and Matches: 1. L occupies position five. The length remains six because replacing one character does not insert a new position.
Replace the "T" in line 200 with "L", then RUN. Try "Z": all six underscores remain and the count is zero. Restore "T" afterwards. Each RUN rebuilds d$ from empty, so these experiments do not preserve an earlier reveal.
Keyboard notes
Enter keywords with their Spectrum keys. LET uses L and PRINT uses P in keyword mode. FOR uses F; NEXT uses N. LEN uses K in extended mode, entered with Caps Shift and Symbol Shift together. TO is Symbol Shift with F. The ROM supplies spaces around keyword tokens; preserve the spaces inside quoted text.
Sources
Run it here
This unit's program, built for you.
- Program
- cipher.tap
- Machine
- ZX Spectrum 48K (PAL)