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

Probing

Read a row and a column, check them, and look up that cell in the grid — a hit marks the target with a star.

33% of Sonar

The board exists; now the player searches it. A probe is two numbers — a row and a column — and the whole point of a 2D array is that those two numbers index straight into it: g(r, c) is the cell the player just named.

  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 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 PRINT AT 13, 2; "Miss       "
 490 PAUSE 30
 510 GO TO 190

9000 PRINT AT y, (32 - LEN a$) / 2; BRIGHT 1; a$
9010 RETURN
ZX Spectrum Sonar: the grid with a star at row 2 column 4 where a target was hit
Probe a target's cell and it is marked with a star — a hit.

Two numbers into one cell

Lines 380–400 read the coordinates: INPUT r, INPUT c, then a validity check that sends the player back if either is outside 1–8. Those two numbers are all it takes to reach the cell — g(r, c). A one-dimensional array needed one index; the grid needs two, and a coordinate guess maps onto them exactly. That is why a 2D array fits a grid game so naturally: the player thinks "row 2, column 4", and the program reads g(2, 4).

Hit detection

Line 460 checks the probed cell: IF g(r,c) = 9 — a target sits there, so it is a hit. The cell is marked -1 (a found target) and redrawn as a star, distinct from both an untouched dot and a hidden target. The grid now carries three kinds of state in one array: 0 unprobed, 9 a hidden target, -1 a found one. Storing several meanings as different values in the same array is how a board game keeps everything it needs in one place.

A hit is the straightforward case. A miss is more interesting — it should tell the player how close they came. That clue is the next unit.

Next: turn a miss into a distance.