Placing Mines
Place mines at random positions with collision checking.
The grid is ready. Now fill it with hidden mines. Each mine needs a random position — but two mines can’t share the same cell. That means checking before placing.
The Program
10 CLS
20 PRINT "Placing Mines"
30 PRINT
40 DIM m(8, 8)
50 LET n = 10
60 REM place n mines
70 FOR i = 1 TO n
80 LET r = INT (RND * 8) + 1
90 LET c = INT (RND * 8) + 1
100 IF m(r, c) = 9 THEN GO TO 80
110 LET m(r, c) = 9
120 NEXT i
130 REM display grid
140 FOR r = 1 TO 8
150 FOR c = 1 TO 8
160 IF m(r, c) = 9 THEN PRINT "*";
170 IF m(r, c) = 0 THEN PRINT ".";
180 NEXT c
190 PRINT
200 NEXT r
210 PRINT
220 PRINT n; " mines placed"

How It Works
Line 50 sets the mine count. Ten mines on a 64-cell grid leaves 54 safe cells.
Lines 70-120 place each mine. For each one:
- Pick a random row (1-8) and column (1-8)
- If that cell already has a mine (
m(r,c) = 9), try again —GO TO 80 - If the cell is empty, place the mine:
LET m(r,c) = 9
The value 9 represents a mine. Later, safe cells will hold numbers 0-8 (the count of adjacent mines). Since no cell can have more than 8 neighbours, 9 is unambiguous.
Lines 140-200 display the grid. Stars for mines, dots for empty cells.
The Collision Check
100 IF m(r, c) = 9 THEN GO TO 80
Without this check, a mine could overwrite another mine. The loop would place 10 mines, but the grid might end up with fewer. The GO TO 80 retries with new random coordinates until it finds an empty cell.
This is a common pattern: generate a random position, check if it’s valid, retry if not. You used similar logic in Treasure Hunt for coin placement.
Try This
Count check. After placement, loop through the grid and count cells where m(r,c) = 9. Print the count. It should always equal n.
Different counts. Change n to 5 or 20. With 5 mines, the grid is mostly empty. With 20, nearly a third is mined. Notice how the placement loop takes longer with more mines — there are fewer empty cells to find.
What You’ve Learnt
- Random grid placement —
INT(RND*8)+1gives a position from 1 to 8 - Collision checking — test before placing, retry on conflict
- Sentinel values — 9 means “mine”, distinct from any count value
- Retry loops —
GO TOback to the random generation on failure