Skip to content
Game 7 Unit 3 of 16 1 hr learning time

Collecting Coins

Place coins on screen and detect when the player walks over them.

19% of Treasure Hunt

A game needs something to do. Let’s scatter coins across the screen and count how many the player picks up.

The Program

10 CLS
20 LET r = 10
30 LET c = 15
40 LET n = 0
50 REM place 5 coins
60 FOR i = 1 TO 5
70 LET y = INT (RND * 20) + 1
80 LET x = INT (RND * 32)
90 INK 6: PRINT AT y, x; "*": INK 0
100 NEXT i
110 PRINT AT 0, 0; "Coins: "; n
120 REM game loop
130 PRINT AT r, c; INK 4; "O"
140 LET k$ = INKEY$
150 IF k$ = "" THEN GO TO 140
160 PRINT AT r, c; " "
170 IF k$ = "q" AND r > 1 THEN LET r = r - 1
180 IF k$ = "a" AND r < 20 THEN LET r = r + 1
190 IF k$ = "o" AND c > 0 THEN LET c = c - 1
200 IF k$ = "p" AND c < 31 THEN LET c = c + 1
210 REM check for coin
220 IF ATTR (r, c) = 49 THEN LET n = n + 1: BEEP 0.05, 20: PRINT AT 0, 7; n
230 PRINT AT r, c; INK 4; "O"
240 GO TO 140

Coins scattered on screen with HUD

Placing Coins

Lines 60-100 place 5 coins at random positions. INT (RND * 20) + 1 gives a row from 1 to 20. INT (RND * 32) gives a column from 0 to 31. Each coin is a yellow *INK 6 sets yellow, then INK 0 resets to black.

Detecting Collection

Line 220 is the key line:

220 IF ATTR (r, c) = 49 THEN LET n = n + 1: BEEP 0.05, 20: PRINT AT 0, 7; n

ATTR (r, c) reads the colour attribute of the cell the player just moved to. If it’s 49, that cell contains a yellow character on a white background — a coin. The formula is INK + 8 * PAPER: yellow (6) + 8 * white (7) = 6 + 56 = 62. But wait — the default paper is white (7) and the default ink is black (0), giving 56. A yellow coin on white paper gives 6 + 56 = 62… except the coin was printed with INK 6 while the global ink was 0, so the cell’s attribute is actually 6 + 8*0 + 64*0

Actually, the value depends on the current PAPER when the coin was printed. With default PAPER 7, INK 6 gives 6 + 8*7 = 62. But line 220 checks for 49. Let’s explore this properly in the next unit.

The important thing: ATTR lets you check what’s already on screen without storing positions in an array. The screen is your data structure.

Try This

More coins. Change FOR i = 1 TO 5 to FOR i = 1 TO 15. The screen fills with more coins.

Different sound. Change BEEP 0.05, 20 to BEEP 0.05, 30 for a higher-pitched collection sound.

What You’ve Learnt

  • Random placementINT (RND * range) + offset for random positions
  • ATTR — reads the colour of a screen cell
  • Screen as data — the display itself stores the game state
  • BEEP — short sound for game feedback