Skip to content
Game 12 Unit 3 of 6 1 hr learning time

Distance

A miss should tell the player how close they came — sweep the whole grid, measure the gap to every target, and report the nearest with Manhattan distance.

50% of Sonar

A hit marks a star; a miss, so far, says nothing. The clue that makes Sonar a game is the distance — when the player misses, the program tells them how far the probe was from the nearest target. Cold means keep searching; a small number means you are almost on it.

  10 BORDER 0: PAPER 0: INK 7: CLS
 110 RANDOMIZE
 120 DIM g(8,8)
 130 FOR i = 1 TO 3
 140 LET r = INT (RND * 8) + 1: LET c = INT (RND * 8) + 1
 150 IF g(r,c) = 9 THEN GO TO 140
 160 LET g(r,c) = 9
 170 NEXT i
 190 CLS
 200 LET a$ = "*** SONAR ***": LET y = 0: GO SUB 9000
 240 PRINT AT 3, 11; "12345678"
 250 FOR r = 1 TO 8
 260 PRINT AT 3 + r, 9; r;
 270 FOR c = 1 TO 8
 280 LET v = g(r,c)
 290 IF v = 9 THEN PRINT "X";
 300 IF v = 0 THEN PRINT ".";
 310 IF v = -1 THEN PRINT "*";
 320 IF v >= 1 AND v < 9 THEN PRINT v;
 330 NEXT c
 370 NEXT r
 380 INPUT "Row (1-8): "; r
 390 INPUT "Col (1-8): "; c
 400 IF r < 1 OR r > 8 OR c < 1 OR c > 8 THEN GO TO 380
 460 IF g(r,c) = 9 THEN PRINT AT 13, 2; "HIT!       ": LET g(r,c) = -1: PAUSE 30: GO TO 190
 470 LET dist = 99
 480 FOR a = 1 TO 8: FOR b = 1 TO 8
 490 IF g(a,b) <> 9 THEN GO TO 520
 500 LET d = ABS (r - a) + ABS (c - b)
 510 IF d < dist THEN LET dist = d
 520 NEXT b: NEXT a
 530 IF dist > 8 THEN LET dist = 8
 540 LET g(r,c) = dist
 550 PRINT AT 13, 2; "Distance: "; dist; "  "
 560 PAUSE 30
 570 GO TO 190

9000 PRINT AT y, (32 - LEN a$) / 2; BRIGHT 1; a$
9010 RETURN
ZX Spectrum Sonar: the grid with a probe reporting a distance of 2 to the nearest target
A miss now reports the distance to the nearest target — the lower the number, the closer.

Sweep the whole grid

When the probe misses, lines 480–540 look at every cell to find the targets. The same nested loop that drew the grid — FOR a over rows, FOR b over columns — now reads it, checking IF g(a,b) = 9 for a hidden target. Drawing the grid and searching the grid are the same walk over the same array; only what you do at each cell changes. This is the move that a 2D array makes natural: the state is a grid, so the algorithm is a grid sweep.

Manhattan distance

For each target found, line 510 measures the gap: LET d = ABS(r - a) + ABS(c - b). That is the Manhattan distance — the row difference plus the column difference, each made positive with ABS (which you met in Lucky Number). It counts steps along the grid, not a diagonal line, which is exactly how a player moves between cells. Line 520 keeps the smallest: IF d < dist THEN LET dist = d, starting dist at a large number (line 470) so the first target always replaces it. After the sweep, dist is the distance to the nearest target — the clue the player needs.

The number is the clue, but a bare number is hard to read at a glance. Next: colour it, so warm and cold are visible without reading.