Files
akbasic/docs/17-tutorial-breakout.md
Tachikoma 36fa1285b4 Update the breakout chapter's scope-pool figure to this branch's 12
The environment pool shrank from 32 to 12 in the memory-reduction work
and the chapter's exhaustion transcript still asserted the old number,
which is a docs_examples failure on every run of this branch.

Co-authored-by: andrew <andrew@aklabs.net>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XiGgpHuXUm2mR4Wzndw3dc
2026-08-04 20:05:41 -04:00

50 KiB

17. Tutorial: Breakout

This chapter builds a complete game from an empty file: three lives, six rows of bricks, three level layouts, a score, a high score, sound, and a title screen that plays itself. Nothing is loaded from disk — the ball and the paddle are drawn from numbers in the listing, and the wall, the HUD and the messages are characters written into the text grid.

This is what you are building:

The finished game: a HUD line across the top, six rows of bricks, the ball resting on the paddle

The finished listing is examples/breakout/characters/breakout.bas. You do not need it to follow along, but it is the same program assembled, and it is worth opening once you have your own running.

Run it with the SDL build:

$ ./build-akgl/basic examples/breakout/characters/breakout.bas
Key Does
left / right move the paddle
space start a game, then launch the ball
P pause
Q or escape quit

What you will do

  • Step 1 — get a program onto the screen, and find out which build you need
  • Step 2 — measure the screen and work the geometry out from what you measured
  • Step 3 — declare every name the program will use, before anything uses it
  • Step 4 — make the ball and the paddle out of sprite data
  • Step 5 — build the brick wall out of characters, and keep a grid saying which bricks are still there
  • Step 6 — write the main loop and the frame pacing
  • Step 7 — read the keyboard without blocking
  • Step 8 — move the paddle and keep it on the screen
  • Step 9 — move the ball and bounce it off the walls
  • Step 10 — find out which brick the ball hit, and break it
  • Step 11 — bounce off the paddle at an angle the player chooses
  • Step 12 — draw the HUD and the messages
  • Step 13 — handle lives, levels and game over
  • Step 14 — add sound, on a machine that may not have any
  • Step 15 — add a title screen that plays itself
  • Step 16 — put the pieces in one file, in the right order

Each step is a piece you can type in and run. Work through them in order, and Step 16 is where they become one program.


Step 1: Get a program onto the screen

Goal: a program that runs, and a build that can draw.

A BASIC program here is a text file. Line numbers are optional, so a file is just statements, one per line:

PRINT "HELLO"
END
HELLO

Save that as first.bas and run it:

$ ./build/basic first.bas

There are two builds and the difference matters for this whole chapter. ./build/basic is the plain one: it reads and writes text and has no graphics device, no sprites and no sound. ./build-akgl/basic opens a window and has all three. A game needs the second.

Ask for something that needs a device and you get a refusal naming what is missing rather than a crash:

PRINT "BEFORE"
SPRITE 1, 1, 2
PRINT "AFTER"
BEFORE
? 2 : RUNTIME ERROR SPRITE needs a sprite device and this runtime has none

That is worth seeing once, because it is how the finished game behaves if you start it with the wrong build: it stops at the first graphics verb and tells you why.

For the rest of this chapter, run everything with ./build-akgl/basic.

Two more things to know before writing anything longer.

Every variable carries a type suffix. A# is an integer, A% is a float, A$ is a string. There is no such thing as a plain A — a bare word is a label. This is different from Commodore BASIC, where A% is the integer.

+ joins a string to a number. "SCORE " + 40 is "SCORE 40", and "" + N# is how you turn a number into a string. There is no STR$.

N# = 40
PRINT "SCORE " + N#
END
SCORE 40

Step 2: Measure the screen

Goal: every position in the game derived from the window's real size, so the game fits whatever window and font the player has.

Do not guess the size of anything. Four functions tell you what you have:

Call Gives
RGR(1) the window's width in pixels
RGR(2) the window's height in pixels
RGR(3) the width of one character cell, in pixels
RGR(4) the height of one character cell
RWINDOW(0) the text grid's height, in rows
RWINDOW(1) the text grid's width, in columns

Put them at the very top of the program:

SCW# = RGR(1)
SCH# = RGR(2)
CW# = RGR(3)
CH# = RGR(4)
COLS# = RWINDOW(1)
ROWS# = RWINDOW(0)

RGR(1) is first on purpose. It is the first statement in the program that needs a graphics device, so on the wrong build this is the line that refuses, and it refuses before anything else has happened.

Now derive the layout from those numbers rather than writing pixel positions down. The wall is measured in character cells, because it is made of characters:

BRW# = 4
BCOLS# = 10
BROWS# = 6
BTOP# = 4
BLEFT# = (COLS# - (BRW# * BCOLS#)) / 2

A brick is four cells wide and there are ten of them, so the wall is forty cells across. BLEFT# centres those forty in however many columns there turned out to be. BTOP# is the row the wall starts on. Integer division truncates, which is exactly what a column index wants.

The ball and the paddle are sprites, and sprites are positioned in pixels, so the play area is measured in pixels:

TOPY# = 2 * CH#
MAXX# = SCW# - 8
PW# = 144
PY# = 528
LOSEY# = PY# + 32
PSPD# = 10
MSGROW# = 35
TITROW# = 20

TOPY# is the ceiling the ball bounces off, two rows down from the top so it clears the HUD line. MAXX# is as far right as the ball can go — the window less the ball's own eight pixels. PW# is the paddle's width and PY# the row of pixels it sits on. MSGROW# and TITROW# are text rows, counted from the top, for messages.

Cells and pixels are two different coordinate systems, and they meet in exactly one place — Step 5, where each brick's cell is turned into the rectangle SOLID registers. Everywhere else, bricks are in cells and everything that moves is in pixels.

Step 3: Declare every name first

Goal: a subroutine that can hand an answer back to its caller.

A GOSUB gets its own scope. That has one consequence you must design around:

  • Assigning to a name that already exists outside the subroutine walks up and finds it. The change is visible to the caller.
  • Assigning to a name that has never been seen before creates it inside the subroutine. It disappears at RETURN, and the caller reads zero — with no error and no warning of any kind.

So a subroutine cannot answer through a name it invented itself. Declare the names first, at the top of the program, and then any routine can write to them:

X# = 0
GOSUB SUBA
PRINT "THE CALLER SEES " + X#
END

LABEL SUBA
X# = 99
RETURN
THE CALLER SEES 99

Take X# = 0 off the top of that program and it prints 0.

This is why the game opens with a block that names everything before the first GOSUB. Arrays go in the same block. Here is the start of it — the names the later steps refer to most; Step 16 has the finished block, all 66 of them, and you can paste that in now if you would rather not come back to it:

DIM BR#(60)
DIM SB#(63)
DIM SP#(63)
DIM LAY$(6)
DIM BSG$(6)

SCORE# = 0
HIGH# = 0
LIVES# = 3
LEVEL# = 1
LEFTN# = 0
BSPD# = 4
STATE# = 0
HELD# = 0
PX# = 0
BX# = 0
BY# = 0
BVX# = 0
BVY# = 0
HIT# = 0
BI# = 0
BR2# = 0

HIT#, BI# and BR2# are the three the rule is really about: they are how the collision test in Step 10 answers the routine that called it.

DIM belongs at the top and nowhere else. An array declared inside a GOSUB or a loop takes storage from a pool of 4096 elements that is never given back, so a DIM that runs repeatedly will eventually end the program:

X# = 0
FOR T# = 1 TO 6000
  GOSUB SUBA
NEXT T#
PRINT "OK " + X#
END

LABEL SUBA
DIM LOC#(4)
LOC#(0) = 1
X# = X# + LOC#(0)
RETURN
? 8 : RUNTIME ERROR Array of 4 elements does not fit in the 0 remaining value slots

A plain number costs nothing, though, so you can create as many of those inside a routine as you like:

X# = 0
FOR T# = 1 TO 20000
  GOSUB SUBA
NEXT T#
PRINT "OK " + X#
END

LABEL SUBA
LOC# = 1
X# = X# + LOC#
RETURN
OK 20000

Twenty thousand calls, each creating a local, and the program is fine. The rule that survives is the narrow one: DIM at the top, never inside anything.

Two rules about writing expressions

Both apply everywhere in this chapter, so they are worth fixing in your fingers now.

Parenthesise any expression that mixes + and -. Write (A# - B#) + C#, not A# - B# + C#:

A# = 10
B# = 3
C# = 2
PRINT (A# - B#) + C#
END
9

Parenthesise a condition that uses more than one AND or OR. Write IF (A# = 1 AND B# = 2) AND C# = 3 THEN:

A# = 1
B# = 2
C# = 3
IF (A# = 1 AND B# = 2) AND C# = 3 THEN PRINT "ALL THREE"
END
ALL THREE

Both habits are free, and both are being made unnecessary: the parser's additive precedence is TODO.md §6 item 35 and the second AND is item 36 beside it. Once those land, the plain forms will mean what they look like they mean, and parentheses you wrote in the meantime will still be correct.

Step 4: Make the ball and the paddle

Goal: two sprites on the screen, in the right places.

A sprite is a 24-by-21 pattern of pixels. SPRSAV loads one from an integer array of 63 numbers: three bytes per row, twenty-one rows, most significant bit on the left. A bit that is 1 draws; a bit that is 0 is transparent.

       byte 0            byte 1            byte 2
  7 6 5 4 3 2 1 0   7 6 5 4 3 2 1 0   7 6 5 4 3 2 1 0
  ^ column 0                                        ^ column 23

The ball is an 8-by-8 disc drawn in the top-left corner of the pattern. Putting it there means the sprite's position and the ball's pixel rectangle are the same thing, so no part of the game needs to add an offset to work out where the ball actually is:

  . . # # # # . .    60
  . # # # # # # .   126
  # # # # # # # #   255

The paddle is a solid bar, 24 wide and 6 deep — the full width of a sprite. SPRITE's x-expand flag doubles it to 48 pixels, and three of those laid end to end make one 144-pixel paddle with no seam.

DIM SB#(63)
DIM SP#(63)
I# = 0
D# = 0
FOR I# = 0 TO 62
  SB#(I#) = 0
  SP#(I#) = 0
NEXT I#
FOR I# = 0 TO 7
  READ D#
  SB#(I# * 3) = D#
NEXT I#
FOR I# = 0 TO 17
  SP#(I#) = 255
NEXT I#
SPRSAV SB#, 1
SPRSAV SP#, 2
SPRSAV SP#, 3
SPRSAV SP#, 4
SPRITE 1, 1, 2
SPRITE 2, 1, 15, 0, 1, 0
SPRITE 3, 1, 15, 0, 1, 0
SPRITE 4, 1, 15, 0, 1, 0
MOVSPR 1, 108, 40
MOVSPR 2, 48, 80
MOVSPR 3, 96, 80
MOVSPR 4, 144, 80

DATA 60, 126, 255, 255, 255, 255, 126, 60

The ball above three paddle segments meeting with no seam

Read that from the middle. SPRSAV SB#, 1 installs the ball's pattern into slot 1. SPRITE 1, 1, 2 turns slot 1 on in colour 2. SPRITE 2, 1, 15, 0, 1, 0 turns slot 2 on in colour 15 with the fourth argument after the colour — the x-expand flag — set to 1. MOVSPR puts a sprite at a pixel position, measured from its top-left corner.

The finished game writes the same 63 numbers out as DATA, one row per line, with the bit pattern drawn in a comment beside each, and loads them in a routine called once at startup. Step 16 has that routine and both patterns in full; the loops above are the same two patterns spelled shorter so the figure fits on a page.

Moving the four sprites is one routine, and every coordinate is worked out into a variable before it is passed:

LABEL SHOWSPR
MOVSPR 1, BX#, BY#
MOVSPR 2, PX#, PY#
X2# = PX# + 48
MOVSPR 3, X2#, PY#
X3# = PX# + 96
MOVSPR 4, X3#, PY#
RETURN

Do not write MOVSPR 3, PX# + 48, PY#. MOVSPR reads a leading sign as move by this much rather than move to here, and an expression beginning with a sign is the relative form. Computing into X2# first says exactly what you mean. See Chapter 8.

Step 5: Build the brick wall

Goal: a wall on the screen, and a grid in memory saying which bricks are still standing.

Two things are needed and they are separate: the state (which of the sixty bricks are alive) and the picture (what the player sees). Keep them in step by always redrawing the row you just changed.

The layouts

A level is six strings of ten characters, 1 for a brick and 0 for a hole, stored as DATA:

LABEL LAY1
DATA "1111111111"
DATA "1111111111"
DATA "1111111111"
DATA "1111111111"
DATA "1111111111"
DATA "1111111111"

LABEL LAY2
DATA "0011111100"
DATA "0111111110"
DATA "1111111111"
DATA "1111111111"
DATA "0111111110"
DATA "0011111100"

LABEL LAY3
DATA "1010101010"
DATA "0101010101"
DATA "1111001111"
DATA "1100110011"
DATA "1011111101"
DATA "0110110110"

READ takes the next DATA item, and RESTORE moves that cursor to a given place. RESTORE accepts a label, so each layout is simply a named position in the DATA stream and choosing one is three IFs:

LABEL LOADLAY
N# = MOD((LEVEL# - 1), 3)
IF N# = 0 THEN RESTORE LAY1
IF N# = 1 THEN RESTORE LAY2
IF N# = 2 THEN RESTORE LAY3
FOR R# = 0 TO 5
  READ LAY$(R#)
NEXT R#
RETURN

Adding a fourth level is a DATA block and one more IF.

One READ cursor walks every DATA item in the file, in the order they were written, no matter which routine is doing the reading. If you have two things to load — a font and a table, say — the one whose DATA comes first in the file must be loaded first, or use RESTORE to say where to start.

The grid

Turn those strings into a flat array of sixty numbers, and count how many bricks there are while you are at it:

LABEL BUILDW
LEFTN# = 0
FOR R# = 0 TO 5
  S$ = LAY$(R#)
  GOSUB BUILDR
NEXT R#
RETURN

LABEL BUILDR
FOR C# = 0 TO 9
  T$ = MID(S$, C#, 1)
  I# = (R# * BCOLS#) + C#
  BR#(I#) = 0
  IF T$ = "1" THEN BR#(I#) = 1
  IF T$ = "1" THEN LEFTN# = LEFTN# + 1
  SX# = (BLEFT# + (C# * BRW#)) * CW#
  SY# = (BTOP# + R#) * CH#
  IF T$ = "1" THEN SOLID I# + 1, SX#, SY#, SX# + (BRW# * CW#), SY# + CH#
  IF T$ = "0" THEN SOLID I# + 1
NEXT C#
RETURN

Two things happen per cell, and the second is what Step 10 is built on. BR#() is the program's own record of which bricks are left. SOLID tells the interpreter, so it can answer "did the ball hit a brick, and which one" instead of the program working it out.

The id is the array index plus one — SOLID numbers from 1 and the array from 0 — so a rectangle and its array element are the same brick with no lookup between them. A hole retires whatever was there, which matters because a level change reuses the ids.

The rectangle is in pixels, and this is the only place the cell grid and the pixel grid meet: a brick at column C# starts at (BLEFT# + C# * BRW#) * CW# and is BRW# * CW# wide.

MID counts from zero here, unlike Commodore BASIC. BR#(row * 10 + col) is the brick at that cell; LEFTN# is how many are left, so "is the level finished" is a comparison rather than a scan of sixty cells.

Drawing a row

CHAR writes a string into the text grid at a row and column. It has one property that decides how the rest of this section is written: CHAR terminates the row where it stops. Writing at column 12 erases everything from column 13 to the end of the line.

So do not write bricks one at a time. Build the whole row as a string and write it once, from column 0:

DIM LAY$(6)
DIM BSG$(6)
BSG$(0) = "[##]"
BSG$(1) = "[##]"
BSG$(2) = "[==]"
BSG$(3) = "[==]"
BSG$(4) = "[--]"
BSG$(5) = "[--]"
LAY$(0) = "1111111111"
LAY$(1) = "1111111111"
LAY$(2) = "1101111011"
LAY$(3) = "1111111111"
LAY$(4) = "1011110111"
LAY$(5) = "0110110111"
S$ = ""
T$ = ""
R# = 0
C# = 0
FOR R# = 0 TO 5
  GOSUB BUILDROW
  PRINT S$
NEXT R#
END

LABEL BUILDROW
S$ = "     "
FOR C# = 0 TO 9
  T$ = MID(LAY$(R#), C#, 1)
  IF T$ = "1" THEN S$ = S$ + BSG$(R#)
  IF T$ = "0" THEN S$ = S$ + "    "
NEXT C#
RETURN
     [##][##][##][##][##][##][##][##][##][##]
     [##][##][##][##][##][##][##][##][##][##]
     [==][==]    [==][==][==][==]    [==][==]
     [==][==][==][==][==][==][==][==][==][==]
     [--]    [--][--][--][--]    [--][--][--]
         [--][--]    [--][--]    [--][--][--]

A missing brick contributes four spaces, so every row is the same length and the columns line up. That block uses PRINT, so it runs on either build — which makes it a good way to check your layouts before you have a window.

In the game, replace the PRINT S$ with a CHAR, and use the real left margin:

LABEL DRAWBR
S$ = ""
IF BLEFT# > 0 THEN S$ = " " * BLEFT#
BSEG$ = BSG$(BR2#)
FOR CC# = 0 TO 9
  I# = (BR2# * BCOLS#) + CC#
  IF BR#(I#) = 1 THEN S$ = S$ + BSEG$
  IF BR#(I#) = 0 THEN S$ = S$ + "    "
NEXT CC#
R2# = BTOP# + BR2#
CHAR 1, 0, R2#, S$
RETURN

" " * BLEFT# repeats a string, which is how you get a margin of any width.

Tell the rows apart by shape, not by colour. CHAR accepts a colour argument and ignores it — the text layer draws in one colour — so [##], [==] and [--] are what makes a 60-point row look different from a 10-point one.

Drawing the whole wall is then six calls:

LABEL DRAWW
FOR R# = 0 TO 5
  BR2# = R#
  GOSUB DRAWBR
NEXT R#
RETURN

Step 6: Write the main loop

Goal: a loop that runs one frame's worth of work and comes back, for as long as the game lasts.

Write the main loop with LABEL and GOTO:

LABEL TICK
GOSUB READKEY
IF STATE# <> 0 THEN GOTO DISPATCH
IF PAUSED# = 1 THEN GOTO TICKEND
GOSUB MOVEPAD
IF HELD# = 1 THEN GOSUB HOLDBAL
IF HELD# = 0 THEN GOSUB MOVEBAL
GOSUB SHOWSPR
LABEL TICKEND
SLEEP 0.02
GOTO TICK

LABEL DISPATCH
IF STATE# = 1 THEN GOTO LOSTLIF
IF STATE# = 2 THEN GOTO LEVELUP
IF STATE# = 3 THEN GOTO BYE
IF STATE# = 5 THEN GOTO NEWGAME
STATE# = 0
GOTO TICK

A label is one bare word: letters and digits, no underscore. TICKEND is a label; TICK_END is a parse error, and the message you get is UNKNOWN TOKEN _ rather than anything about naming, so it is worth not writing in the first place. The same goes for variable names.

STATE# is a plain number that the rest of the game writes when something has happened: 0 is playing, 1 is "the ball was lost", 2 is "the level is clear", 3 is "quit", 5 is "start a new game". Nothing acts on it where it is set — the loop notices on the next pass and branches. That keeps every state change in one place and out of the middle of the physics.

The branch targets end in GOTO TICK rather than RETURN. Nothing GOSUBs into a state change, so the subroutine stack is empty again by the time the next frame begins.

SLEEP 0.02 is the frame pacing, and it does not block the host. It records a deadline and the interpreter declines to advance your program until the clock reaches it, so the window keeps redrawing and the keyboard keeps being read the whole time. 0.02 seconds asks for fifty frames a second.

Why GOTO rather than DO ... LOOP

A DO ... LOOP around the frame would read better, and it is not usable here: a GOTO that jumps out of a FOR or a DO does not release the loop's scope. There are 12 scopes, so a game that leaves its main loop once per lost life stops on the twelfth one:

N# = 0
LABEL TOP
DO
  N# = N# + 1
  IF N# < 100 THEN GOTO TOP
LOOP UNTIL N# > 99
PRINT "SURVIVED " + N#
? 3 : PARSE ERROR Environment pool exhausted at line 3 (12 in use)

A LABEL/GOTO loop pushes no scope at all, so it can run for as long as the machine is on. Use FOR and DO freely for work that finishes inside a frame — the wall builder in Step 5 is a FOR inside a FOR — and use GOTO for anything you will branch out of. This is TODO.md §6 item 37; when it is fixed, DO ... LOOP will be available for a main loop too, and a GOTO loop will still be correct.

Step 7: Read the keyboard

Goal: a paddle that moves smoothly while a key is held, using the only input verb there is.

GET takes one keystroke from a queue the host fills, and returns 0 if there is nothing waiting. It never blocks. There is no key-up event and no way to ask whether a key is currently down.

What you get instead is the operating system's own key repeat, arriving as ordinary keypresses about once a frame while a key is held. So: drain the queue every frame, and let each keystroke refill a countdown.

LABEL READKEY
FOR KI# = 1 TO 8
  GET K#
  IF K# <> 0 THEN GOSUB HANDKEY
NEXT KI#
RETURN

LABEL HANDKEY
IF K# = 1073741904 THEN PDIR# = 0 - 1
IF K# = 1073741904 THEN PDEC# = 12
IF K# = 1073741903 THEN PDIR# = 1
IF K# = 1073741903 THEN PDEC# = 12
IF K# = 32 THEN GOSUB KEYSPC
IF K# = 112 THEN GOSUB KEYPAU
IF K# = 113 THEN STATE# = 3
IF K# = 27 THEN STATE# = 3
RETURN

Eight GETs a frame is enough to keep the queue from backing up. PDIR# is which way to move and PDEC# is how many more frames to keep moving; a keypress sets both.

The key codes are the host's. 1073741903 and 1073741904 are the right and left arrows, 32 is space, 112 is P, 113 is Q and 27 is escape. Chapter 12 says where they come from. A quick way to find any other key is to print what you get:

LABEL SHOWKEY
GET K#
IF K# <> 0 THEN PRINT "KEY " + K#
GOTO SHOWKEY

Note 0 - 1 rather than -1 in PDIR# = 0 - 1. Both work; writing the subtraction out is the habit that goes with the parenthesising rule from Step 3, and it is what the rest of this chapter does.

Step 8: Move the paddle

Goal: the paddle moves while the countdown lasts, and stops at both edges.

LABEL MOVEPAD
IF PDEC# < 1 THEN GOTO PADCLMP
PDEC# = PDEC# - 1
PX# = PX# + (PDIR# * PSPD#)
LABEL PADCLMP
IF PX# < 0 THEN PX# = 0
M# = SCW# - PW#
IF PX# > M# THEN PX# = M#
RETURN

The countdown is the whole trick. A single tap sets PDEC# to 12 and the paddle coasts for twelve frames; holding the key down refills it faster than it drains, so the paddle keeps going. Held reads as held and tapped reads as a nudge, with no held-key state anywhere.

The clamp is written as a jump to PADCLMP rather than wrapped around the movement, because the paddle has to be pushed back inside the window whether it moved this frame or not.

M# = SCW# - PW# is computed into a variable rather than written inline. Any expression you are about to compare or pass is clearer that way, and it keeps lines short — a line here holds at most 32 tokens, so long conditions want breaking up into named pieces anyway.

Going over 32 currently stops the interpreter rather than raising a BASIC error you could TRAP, which makes a too-long line harder to diagnose than it should be. That is recorded in TODO.md §8, and the fix is to report it as the parse error it is; the limit itself stays either way, so short lines are the habit regardless.

Step 9: Move the ball

Goal: a ball that moves, bounces off three walls, and is lost off the bottom.

The ball has a position (BX#, BY#) and a velocity (BVX#, BVY#) in pixels per frame. Moving it is adding one to the other — but do the two axes separately, and test each move on its own:

LABEL MOVEBAL
BX# = BX# + BVX#
IF BX# < 0 THEN GOSUB WALLL
IF BX# > MAXX# THEN GOSUB WALLR
BY# = BY# + BVY#
IF BY# < TOPY# THEN GOSUB WALLT
GOSUB PADHIT
IF BY# > LOSEY# THEN STATE# = 1
RETURN

Nothing here tests a brick. Step 10 arms a handler that fires when the ball meets one, and it pushes the ball out along the contact rather than restoring a remembered position — so there is no "where was it before" to keep.

A wall bounce puts the ball on the wall and flips the sign of that axis:

LABEL WALLL
BX# = 0
BVX# = 0 - BVX#
RETURN

LABEL WALLR
BX# = MAXX#
BVX# = 0 - BVX#
RETURN

LABEL WALLT
BY# = TOPY#
BVY# = 0 - BVY#
RETURN

There is no wall at the bottom. Below LOSEY# the ball is gone, and the loop's dispatch in Step 6 picks that up.

Draw a visible ceiling once, at startup, so the ball turns against something the player can see:

FRAME$ = "=" * COLS#
CHAR 1, 0, 1, FRAME$

Step 10: Break bricks

Goal: find out which brick the ball hit, and take it out of the wall.

Step 5 registered every brick with SOLID, so this is not arithmetic — it is a question. Arm a handler:

COLLISION 2, BRICKHIT

That line goes in the setup block, once, before the frame loop starts — arming a handler is a standing instruction, not something a frame does.

COLLISION 2 fires when a sprite overlaps one of those rectangles. The handler runs between source lines, exactly like a GOSUB the program did not write, and must end in RETURN.

LABEL BRICKHIT
M# = BUMP(2)
IF (M# AND 1) = 0 THEN RETURN
T# = RCOLLISION(1, 1)
IF T# < 1 THEN RETURN
IF BR#(T# - 1) = 0 THEN RETURN
D% = RCOLLISION(1, 4)
BX# = BX# + (RCOLLISION(1, 2) * D%)
BY# = BY# + (RCOLLISION(1, 3) * D%)
A# = RCOLLISION(1, 7)
IF A# = 1 THEN BVX# = 0 - BVX#
IF A# = 2 THEN BVY# = 0 - BVY#
BI# = T# - 1
BR2# = BI# / BCOLS#
GOSUB KILLBR
RETURN

Read it as four questions and an answer.

BUMP(2) is the mask of which sprites met static geometry, and bit 0 is sprite 1 — the ball. Reading it clears it, so the next hit is news again. BUMP(1) is a separate accumulator for sprite-against-sprite, so this handler never sees the paddle.

RCOLLISION(1, 1) is which rectangle. Because Step 5 registered brick I# as id I# + 1, that number is the array index plus one and nothing has to be looked up. The two guards after it are worth keeping: a program can be told about a brick it has already broken, because the handler runs a line or two after the overlap happened.

Fields 2, 3 and 4 push the ball out. Field 4 is how deep the overlap is and fields 2 and 3 are the direction out of the brick, so adding one times the other puts the ball exactly clear. That is why MOVEBAL in Step 9 keeps no OX#/OY# backup — there is nothing to restore to.

D% is a float variable, and it has to be: field 4 is a float and a # would throw the fraction away. The products land in BX# and BY#, which are integers — and that is safe here for a reason worth knowing rather than assuming. A box against a box gives a normal that is exactly -1, 0 or 1, so the product is a whole number before it is stored. Against a circle it would not be, and the push-out would land a pixel short.

Field 7 is which axis to reverse. It is the one the ball is least far through, which is what makes a ball clipping the end of a row go sideways rather than straight back down. Working it out yourself means comparing two floats, which is exactly where Chapter 13's left-operand rule catches people, so it is computed for you.

Breaking the brick clears its cell, scores it, and redraws just that row:

LABEL KILLBR
BR#(BI#) = 0
SOLID BI# + 1
LEFTN# = LEFTN# - 1
PTS# = (BROWS# - BR2#) * 10
SCORE# = SCORE# + PTS#
GOSUB DRAWBR
GOSUB DRAWHUD
IF LEFTN# < 1 THEN STATE# = 2
RETURN

SOLID BI# + 1 retires the rectangle in the same breath as clearing the array. Miss it and the ball goes on bouncing off a brick that is no longer drawn, which is a bewildering thing to debug and an easy thing to forget.

The top row is worth 60 and the bottom row 10. LEFTN# reaching zero sets the state that Step 6's dispatch turns into a level change.

Step 11: Bounce off the paddle

Goal: a bounce whose angle is decided by where on the paddle the ball landed.

This is the part that makes it a game rather than a demonstration. Divide the paddle into five zones and let the zone choose the horizontal speed: