Showing posts with label 6502. Show all posts
Showing posts with label 6502. Show all posts

Sunday, 1 November 2026

Cosmic Snake - Writing Code Without Using Zero

In the previous post, I looked at Cosmic Snake for the VIC20, a game which was partly written in BASIC, and partly in assembler, with the code hidden in REM statements at the start of the program.

This is a technique used a lot on the ZX81, but rarely in Commodore BASIC as it has one major limitation - you cannot use zero.

If any of the code assembles to a binary $00, it will be seen as the end-of-line marker and the code after will be truncated.

That also means you cannot JSR, JMP, read or write to any addresses containing zero, (i.e. $9600, $1E00, $0042, etc.). There are ways around this, as we will see, but it complicates some things and leads to some convoluted code to avoid it.

If you have any variables or tables in this space, you also need to make sure they will never contain zero.

I guess this must be what it was like to write VMDII assembler for your VIC XX if you were a Roman.

Aiming For Zero

Here are three lines of code just to get A to $00, because you can't do LDA #$00.

Four bytes seems a bit unnecessary.

This is not a Z80, so you can't do XOR A, which would set A to zero.

If it not later 65C02, so we cannot use the nice STZ opcode which stores a zero.

It is going to need at least two bytes, which is what LDA #$00 would have been anyway.

There are many places in memory which will already contain $00.

It is defined that the start of BASIC memory should be zero, so $1000 would always be zero, you could read that

LDA $1000

The first line number is 0, so $00 $00 is stored at $1003 and $1004, you could read one of those

LDA $1003

But those are three bytes (still less that four), so to get down to two bytes needs a read operation from zero page.

There are various unused locations there that could be set to zero, POKE the address from BASIC, set it once to $01 and decrement it, or find one that would always be zero, for example:

  *0099     153      Input device (normally 0)

and then

LDA $99

Although giving that a name would be clearer

LDA ZP_ZERO

would assemble to two bytes, the same size as LDA #$00.

But it seems that none of those are used, instead we have lots of alternative workarounds.

Reverse Engineering

I find this an interesting challenge. Looking at the code as it currently is, there is a whole bunch of bytes. Some are code, some are data, some are BASIC line structure, and some are just padding.

I like working through and finding a variable and trying to work out what it is being used for. Where is is written to? when is it read from? what values will it contain?

The process was just a case of divide and conquer, breaking things down into functions and blocks and trying to work out what each one does.

As the code is a mixture of BASIC line structure, code, possible variables or tables and padding, I can't just run it through a disassembler as a whole.

Instead, I am using the disassembler in Vice.

I start at each REM statement line and look for valid code.

This section looks like a function.

The two bytes before are CLI, $58, the "X" character that fills the REM statements, so I think it is safe to assume that the function starts at $18C8.

The only jump, a BNE is to an address within the function, so I think it finishes at the RTS.

I cut and paste that section into Visual Studio Code, which I am using as an editor.

I don't need all the address and bytes on the left, so I can use the block select, which is quite handy to have in VS Code and is something I used to like about Notepad++.

Hold down SHIFT + ALT and you can select just that block that I need to remove, and then press TAB to set the code in it's normal location 4 characters from the left hand edge.

The *=$18C8 sets the address, so when the file is assembled, this code will overwrite what is currently at $18C8, which is a run of $58, the "X" padding characters. Overwriting the file like this means I don't need to worry about line formatting or padding, just blocks of code.

This is a local label, for local people. There is nothing for you here.

I am starting to split it up into sections, the first being the slightly convoluted way to make A=0.

As mentioned before, the BNE instruction branches back into this function, so I can replace that with a local label.

The - branches back to the nearest - label before the branch instruction, and a + will branch the next + label after the branch. You can do -- and ++ etc. to nest these on some assemblers, but I tend to switch to names at that point to avoid confusion, but for simple loops like this and "skip over the next few lines", they are ideal.

That just cleans things up a bit, my aim is to get rid of as many of the magic numbers as I can, and replace everything with named values or local labels where appropriate, etc.

Don't Keep Asking Me Why Reg

One of those is in the range $900x, which is the VIC chip.

It looks like it is writing A (which is zero) to $9009, which is the paddle Y register? Y Reg? Why?

Ah, but X starts at $01, so the instruction

STA $9009,X

Will actually write $00 to $9009 + 1, which is $900A. This is the register which controls the frequency of oscillator 1, which is more likely to be what we want here.

Then X is incremented, and checked against 6, if it is not 6, it loop back around.

The second time around, X is 2, so it writes to $900B, the frequency of oscillator 2.

Then $900C, the frequency of oscillator 3, then $900D, the frequency of the noise source.

The last time around the loop, it writes to $9009+5 ($900E), setting the VIC volume to 0.

That makes more sense, this is basically a "stop making sounds" function.

To make that clearer, rather than

STA VIC_PADDLE_Y, X

I have written that as

STA VIC_OSC1_FREQ-1,X

$900A-1 is $9009, so the code assembles to the same thing, but it is hopefully clearer what is intended rather than leaving it as just the number $9009 or changing it confusingly to VIC_PADDLE_Y.

Continuing on with the next section, and I can see in there are several calls to $18B6, which can now be updated.

There Has to be Another Way

It is interesting to note that there is no reason for this one-based confusion. It is used throughout the code, in many cases because it is just easier to avoid zero that way. But in this case, it is almost confusing for confusing sake, or maybe just a desire to keep everything one based rather than a mix of zero- and one-based?

The code actually starts by setting X to 0, and then sets it back to 1. It could have been left as zero, and then the function would read more logically.

Or, start with X as 5, and decrement until it gets to 0, we need it to keep going for that last loop, so you can change the branch instruction to BPL -, branch is the number is positive, which will be correct for 5 down to 0, but when it rolls around to $FF, the test will fail and it will move on to the RTS.

Going backwards is not always an option, but in this case, i would actually be better to start by setting the volume to 0 first.

You might also consider using X as an offset to the VIC base address $9000, and run the loop from $09 to $0E.

But the VIC base address is $9000, and that would assemble as $9D, $00, $90, which contains $00 and would cause the rest of this line to be truncated.

For now, I am leaving all the code as is, so I can continue to build a binary identical version.

Line 0

The first line is line 0, ironically you can use zero as a line number. This does not appear to start with valid code?

It seems to be rubbish until $1080 where it looks to be a valid function.

This fits with the BASIC code, which calls SYS 4224, which is $1080.

I worked that out to be a function that copies the data from $1006 onwards into RAM at $1D88, which is later set to be user defined graphics.

It is a little more than a straight copy.

It reads the data, byte by byte, and checks each one to see if it equals $01. If it does, it subtracts $01 to get the otherwise unobtainable $00 value. Presumably there was no need for any $01s in the character data.

You can see the results after the copy, the source first, then the destination, with all the $01 bytes changed to $00.

Fire!

Another short function that shed some light on things was this one.

>C:1150  22 91 60 58  58 58 58 58  58 58 58 58  00 5c 12 02   ".`XXXXXXXXX.\..

>C:1160  00 8f 02 02  58 58 ad 11  91 09 df c9  ff f0 05 a9   ....XX..........

This shows the end of line 1, with the row of XXX padding characters, then the $00 which indicates the end of line (the only time you can use a zero, other than in line numbers and the address of the next line).

$125C is set as the address of the next line, and $0002 as the line number.

There is then the $8F which is the REM token, then some code?

It does not start with valid code, two $02 (invalid op-codes, causing a CPU JAM), then two $58 padding characters, then what looks like a function follows at $1166.

This again ends with an RTS and appears self contains as the only branch, a BEQ will jump to the RTS line.

As before, I split that up, but left space for the two $02 bytes. I used another *= to skip over the padding bytes.

$9111 is the VIA#1 PORT A, and it looks to be masking off bit PA5, which is the joystick fire button.

If that is high, then the button is not pressed, so the function exits via the BEQ and the RTS.

If it does not equal $FF, then the pin must be low, so fire is pressed.

When this happens, it sets address $1162 to $01.

Hang on, that is the address of one of the $02 values above.

OK, so those are used as variables, I added V_ and R_ prefixes to try to track variables and routines (also T_ for tables and L_ for links), and a local label for the branch forward.

V_1162 starts as $02. Elsewhere in the code, in what I think is initialisation, it is set to $02.

The rest of this routine reads from an address which is the IO chip, and based on the bit is is checking, this is looking for fire being pressed. If it is pressed, it sets this flag variable to $01.

Elsewhere, it checks if the value is $01 and starts a process I worked out to be firing the missile.

Once it sets the missile in motion, it sets the value back to $02.

It also sets to back to $02 later during the movement of the missile.

There are no other references I can see to V_1162, so I think that is it's entire job.

From that, I can say that is a "Fire has been pressed" flag, and the other variable here V_1163 is "a missile has been launched" flag.

These are only ever set to $01 or $02, and are only checked for those value.

I think I can conclude the values are being used as

  • TRUE / ACTIVE = $01
  • FALSE / INACTIVE = $02

I am sure the programmer would have liked to use the more standard $00 for false and anything else for true, but of course we can't use $00 here, so the logic here is using $01 and $02.

There is another function buttoned up. I have left the literals for the mask values, I could have changed those to PA5_MASK or FIRE_MASK, but I think it is fine for now, I have added appropriate comments.

Turning the Tables

The third line number 2 started with a block of numbers before the valid code started.

Those were referenced by the following code. Registers A, X and Y were stored in $177E, $1780 and $1781 respectively, and were restored at the end of the function.

There was then a reference to $1778, but this was +X, so $1779,$177A etc.

I worked out this was the "update the score" function, and $1778 was a lookup table for scores.

The scores were of course stored plus one, but I thought it would be better to show those as 50+1 etc.

The temporary A,X and Y register locations were also named and the final byte was a variable used to store the number of points read from the table.

It would then loop around that many times, updating the score digits directly on the screen.

(why not load Y with the number of points and then DEY to avoid the compare, and why use JMP - when BNE - would have been shorter and also protected against infinite loops as it would eventually hit zero and not branch)

Writing to the screen

When I see JSR calls in the range of $B000 - FFFF, these are KERNAL routines, normally well defined and documented, so when I see those I can replace them with the function names.

Likewise, there are defined ares in zero page and $0200-$03FF that can be labelled appropriately to help understand what is going on.

This short function, followed by lots of padding, references two known memory locations.

From those, I could also understand the relevance of the values $07 and $39 in the code.

This is setting the current colour used by the kernal print routines to $07 (yellow) and using the print routine to print a character $39 to the screen.

This is one in the range which was copied over at the start of the code, and I had worked out was the snake graphic.

In order to use that function, there must be a call to set the location on the screen somewhere ...

Found it, a call to $FFF0.

It took me quite a while to work all that out because some of the references were to a variable at $1508, e.g.

LDX $1508

but others were as if $1508 was the start of a table

LDA $1508,X

I need to remember how the author is working here, it makes more sense when that is written as

LDA $1509-1,X

I worked out that $1508 was an index to the current portion of the snake being drawn, and there were several tables this indexed showing X and Y positions and I think direction (or possibly status).

With those defined, the code makes more sense.

This sets the X and Y location to be printed using the PLOT function.

Those are read from a table using an index (stored plus one to avoid containing zero, so the table address is -1)

And of course, the values are also stored plus one as they cannot contain zero.

(there really is a whole lot of work required to avoid using zero here)

But Wait, That's Cheating!

This function started by reading and writing to certain bytes in the $1Dxx region. This is where the user defined graphics are stored in this setup. Is it changing part of a character?

I thought this might have been related to the mushrooms being blasted away by fire, but that is handled by one of four different characters with different states of destruction.

I finally worked out that these were actually being used as variables.

Variables in real RAM!

Variables that can contain zero!!

But that is cheating!!!

If you are going to do that, why not put all the variables in there so we don't have to do this +1, -1 all the time.

Why not put the code there as well, save us all a headache?

I worked out these are being used as player X and Y locations. When the joystick is checked and the player needs to be, the new location is calculated and what is there is checked, using the KERNAL PLOT and the zero page CURSOR_POS and CURSOR_LINE_PTR functions, (which is quite a neat way of doing it)

That all seemed to make sense, following the code through until I hit a line that didn't make sense.

The code is reading in the port which contains several bits which are the joystick directions (3 directions plus fire, the 4th direction is on another port, because VIC20....)

If it detects the joystick is to the right, it increments the player Y position, to the left, decrements Y, etc.

When it comes to checking up, it should skip over the 

DEC NEW_PLAYER_X 

line if the joystick is not held up.

But rather than

BCS $10E9

Which would branch over the next line and continue, it does

BCS $10E7

This branches into the middle of the next instruction.

It just happens that $86 $1D represents a valid bit of code which does not break anything.

It unnecessarily writes X to address $1D, which is some temporary storage for strings in BASIC.

0019-0021 25-33 Stack for temporary strings

All I can say is the author was very lucky, that could easily have been invalid code and broken things, but by a fluke, it works out to be an innocuous instruction and it continues at $10E9 where it was meant to go.


I have not completed the whole disassembly, I will probably return to it at some point. It is an interesting process, and keeps my mind occupied anyway on days when I don't have the energy to do anything else.

I learned a few new tricks, but I suppose the main takeaway is, yes, you can store code in REM statements on a VIC20, but you really, REALLY, shouldn't.

I suppose you could rewrite this as "code at the end of the file" style, I wonder how much better / easier it would be..... No.....

Or even entirely in assembler ....

No.... Must not rewrite it ......

Adverts

All Tynemouth products are still available direct from me, and I can ship worldwide.

Including the limited edition 10th anniversary recreation of the very first Penultimate Cartridge:


International shipping is a bit complicated at the moment, so if you want to order from outside the UK, please contact me using the contact link at the top of this page.

See here for more information:

Sorry to have to do this, and I know this is going to affect sales, but please understand it is the only option I have right now.

Stop Press!

I am going to do another batch of Mini PET 40/80s with keyboard, with a few updates. 

These are pre-order now, shipping worldwide in November. £450 kit / £500 built.

Available exclusively from me, contact me using the link at the top of the page to get a price for shipping and any duties, based on your address.

The Mini PET 40/80 internal PET replacement boards are also available now, £350 kit / £375 built.

Again contact me if interested.


Patreon

If you enjoy posts like this, you can support me via Patreon, and get access to advance previews of blog posts, and exclusive posts. Paid Patreon supports will be getting the third part shortly, and maybe a forth part three will follow if there is any interest

You also get progress updates on new projects and other behind the scenes updates, as well as access to my Patreon only Discord server for even more regular updates, and to discuss your own projects.

Sunday, 9 August 2026

Timebomb Part 2 - Bug Fixes and Code Optimisation

Following on from the previous post where I took a VIC20 BASIC game and rewrote it in 6502 assembler, I have a few issues to address.

  • Fix bugs that I introduced
  • A look at maze generation
  • Fix bugs in the original version
  • Tidy up the code
  • Optimise the code for speed and size
  • Improve readability and portability by using names constants
  • Test this by writing a PET version

Fix bugs that I introduced

First up, I need to fix some bugs which I introduced in the rewrite.

The first is an odd one, that is no immediately obvious reason how and why it happens.

Normally, the player starts in the middle of the screen, which is actually the bottom of the maze. There is a maze below, but they have to move upwards as there is a solid row of walls two lines below them.

Sometimes (a wonderfully vague and unhelpful term in troubleshooting), sometimes, that solid wall that demarcates the bottom of the maze is broken.

I have highlighted the line in black and you can see gaps.

If you move below that line, it confuses things and it all goes wrong.


I initially "fixed" this by fixing the symptom, that bottom line being broken, rather than the cause.

I added some code to check to see if the maze generation was trying to place a path on that line and blocked it and sent it scurrying back up into the safe bits of the maze.

Later on, I worked out what was happening, and why it was happening, but to understand that, I need to look at how the maze is generated. 

It is a random maze, freshly generated every time you start a new game, or the old one gets blown up because you didn't find the bomb in time.

A look at maze generation

To generate the maze, it first fills the maze with walls.

In the starts in the middle and creates paths.

(this is a modified debug build which draws the maze generation progress, see the github link at the end)

It picks a random direction, and sees what is two squares away in that direction. If it is a wall, it moves to that square and creates a path on the way.

It keeps moving in that direction until it hits something which isn't a wall, a previous path, or the edge or the maze.

At that point, it turns 90 degrees counter clockwise and tried to continue in that direction.

That repeats until it has turned a full 360 degrees, at which point, it backtracks to a previous square and tries again.

This continues until it gets back to the start.

That all works well, but I skipped over one detail - how does it know when it hits the edge of the maze?

It is 66 rows of 22 characters

It might look 2D.

It might even look 3D with the red and blue fringing.

But it is in fact 1D.

This is all dealt with linearly, a single run of 1452 squares (66 * 22). To move up or down, it jumps 22 squares in either direction, the width of the maze.

If it were generated using XY co-ordinates, it would be much easier to limit things, but I expect some of the other calculations would be more difficult. I don't know, maybe I will try to rewrite it like that, but not today. (please not today, this is already going to be a very long post)

To mark out the top of the maze, it adds a row of spaces. You can see this at the top where you also get to see what is in RAM before the start of the maze (I could fix that, but I have decided to leave it - for now).

You can see from that the right hand side also is a row of spaces.

This continues along the side of the whole maze.

I did think about trying to disguise that by shrinking the screen, or setting the spaces to be solid blue, but it didn't look right, so I left it alone.

In the generation algorithm, when it finds something which is not a wall, it stops and goes off in a different direction, creating a boundary.

That is the top and the side, what about the bottom?

Well, immediately following the maze in RAM is the top of video RAM, so on the original version, when it was generating the maze, the video RAM was full of spaces, other than the "MAKING MAZE" message on the second line.

A whole row of spaces, creating the 4th boundary of the maze.

How Did I Break It?

When I rewrote the maze generation in 6502 assembler, it was so lightening fast that I didn't actually need the "MAKING MAZE" screen, so I simply removed it.

The first time the game runs, the video RAM is probably going to be the BASIC screen.

That's fine, it is unlikely any of the characters will be walls, so that will work as the bottom boundary of the maze.

When you lose the game and it needs to generate a new maze. At that point, the screen contains the remains of the old maze, INCLUDING SOME WALLS.

Depending on where you finished, that might include places where there were runs of walls.

If it just happens that there is an old wall at the point the maze generator was poking it's nose into the video RAM, it will make a path there.

That won't happen very often, which is why this only happened "sometimes", and I now know never on the first run, which is why I didn't see it very often.

It is nice to get to the point where you understand why something happens, and more importantly, why it only happens sometimes.

To fix that, I moved the maze up in memory and added a row of spaces between the bottom of the maze and the top of video RAM.

A Random Bug

One random bug I caught was in the code which places the timebomb.

Part of that process needs a randomly generated horizontal location.

The maze is 22 characters wide. There are walls left and right, and is a space on the far right, making 19 possible locations. 

The original code used int(rnd(0)*20) which will generate a random number from 0-19. (I think that might be a an error in the original, it only needs an offset of 0-18 to make that?)

I got the random number for 0-19 wrong in the first version. My plan was to take a number from 0-3 (4 options) and another from 0-15 (16 options) to get a number from 0-19 (20 options), but it doesn't work like that. There were two ways to generate 0, and no way to get 19, the maximum was going to be 3+15 = 18.

The RAND16 function generates a 16 bit number. The MSB is returned in the accumulator (and also SEED_MSB), and the LSB is in SEED_LSB.

Here I take the MSB in the accumulator and AND with $03 to get a number from 0-3.

I next take the LSB and AND that with $0F to get a number from 0-15, and add those together.

jsr RAND16
and #$03
sta TEMP
lda SEED_LSB
and #$0F
clc
adc TEMP

The fix was fairly simple, rather than the CLC to clear the carry, I used ROR to rotate one bit of the LSB into the carry.

jsr RAND16
and #$03
sta TEMP
lda SEED_LSB
ror
and #$0F
adc TEMP

The final ADC operation is now adding 0-3 to 0-15 and 0-1, giving a number from 0-19. (AND will never generate a carry, so does not touch the flag set in the previous instruction)

Testing that in practice, I did indeed see locations far left and far right. Sorted.

Fix bugs in the original version

There were a few issues I found that were present in the original.

One was the starting square was usually a wall, so when the player moved away, the wall the close up behind them.

Sort of a "reverse Homer".

That could lead to getting stuck in inescapable sections or blocking off a better route, so I hard wired it to mark that square as a path.

Another issue is also shown in those two pictures above.

The maze is composed of 66 lines of 22 characters.

This sits in memory directly below the screen RAM, 23 lines of 22 characters.

During the game, the screen is a view of 23 lines within the 66 lines maze.

The player is always on the middle row, and there are 11 lines of maze above, and 11 lines below.

That is fine when you are in the middle, but when you start, you are on the 64th line.

11 lines above that is line 53, so the screen will show lines 53-66, but what about the remaining 9 lines?

If you look at the starting screen.

This is composed of three parts, I have highlighted those below.

The maze is stored in RAM between the end of the program and the start of the screen RAM.

The red section at the top is a copy of last 14 lines of the maze.

The last line is highlighted in black. This is always a solid line across the maze to stop the player moving below (at least it is with the maze generation fixed).

Beneath that, highlighted in blue, is a copy of the next 9 x 22 characters in RAM following the maze.

This is actually the top of the screen RAM, so it copies that instead.

You get the maze lines 54-64, and then top of the screen, which is the maze lines 54-62

I have copied the blue squares up to the top so you can see.

That helps make the maze look larger, but the solid line stops the player moving into the "shadow maze".

When the player moves up, the maze moves down, and the pattern beneath the solid line changes to a copy of what is at the top of the screen now.

Previously what you saw was maze lines 54-64, followed by lines 54-62.

But now you get lines 53-64, followed by lines 53-61, so the pattern below the line changes.

That can be a little confusing or distracting if it catches your eye, and it continues until the solid line is off the bottom of the screen and the whole view is of valid maze.

I have highlighted the end of the maze in black, and as an example what is initially a 2 square section below that line.

When the maze moves up, the top of the screen changes, and so does the copy, so it looks like the layout is changing.

I fixed that when I added the row of spaces to fix the "hole in the wall" issue.

I rewrote that section so that rather than relying on the screen data being directly below the maze, there was now a lines space, so the original didn't work.

I changed it so that when it detected it had reached the end of the maze, it reset to a specific location, always line 54, matching what would have been shown on the start screen.

That means the maze under the line, will now remain consistent. It is a repeat of part of the maze you can already see, so it is not giving anything away as it would if I had duplicated a different portion of the maze. I did consider using the top of the maze, but that might give you hints if you knew it was that.

I picked an example with a similar two square wall on the left.

You can now see it stays intact when the maze moves.

The final one in this area was another of those "sometimes" issues.

I would occasionally see one of the squares around the middle row disappear at the start, and then reappear when the maze scrolled.

I thought I had got some screenshots, but I can't find them (they have also disappeared). So these are cheated (by modifying video RAM).

It was usually one on the left, just above the middle.

Did you see it (or rather not see it?)

This was another one that didn't make any sense until I worked it out.

When the player moves, it clears the old square and then redraws the player in the new square. (the process was slower in BASIC, so you can see the player character flickering between clear and redraw - that is something else I optimised out, don't redraw the maze if the player hasn't moved)

When the game first starts, the old square is initialised to $0000, so it writes the space character to that address (good job this is not a Commodore 64).

When you fail to find the bomb in time, it explodes, destroying the maze, so a new one has to be built.

The original, used RUN to restart the program (and then spent a minute creating a new maze). As part of that, the old square would have been initialised to $0000 again.

What I (finally) realised, is when you complete a round successfully, and restart the game, it does not reset the old position, so when you first move, it overwrites the old position and draws the new position.

But the old position was from the end of the last round, and if it turns out to be a wall now the maze has scrolled back to the start, it clears the wall until the maze scrolls, when it reappears.

Again, it makes sense once you work it out, but until then I just had a random square that sometimes flickered when a new round started.

That was an easy fix, I just set the old position to $0000, why not, that is just to STY commands. (Y is always 0 in my world, see the previous post)

Tidy up the code

Whilst I have been going through fixing things like that, to make things clearer, I have been expanding the comments where appropriate, and looking around for unnecessary code etc.

I found a few more variables that were set to a constant value, and then not changed, so I just changed those to be load the constant value when required. (those are a hangover from the BASIC version)

I found quite a few bits of similar or repeated code that I could combine, and things that could be rearranged to make more sense.

This was particularly true in the joystick section, where I was able to change a large block of code which set direction and player character if a direction was detected, part of which is shown on the left.

The new version (on the right above) load an index in the X register and later in a single block of code, uses an existing array, and a new 4 byte array to set the direction and player character once.

There were several places where multiple things were being set to the same thing, so shuffling code around could save the duplication.

There were also a few times variables were used for temporary storage that I was able to optimise out by using the X register as a temporary store.

Optimise the code for speed and size

Time for some more top tips?

Top Tip - Optimise Loops # 1

There is often quite a few things that can be done to tighten code loops. This can reduce size and increase speed, both quite useful things.

This loop writes wall characters to an area of memory. It keep going until the MSB reaches an address after the end.

    lda #CHAR_WALL
-
    sta (DST),y 
    inc DST_LSB
    bne -
    inc DST_MSB
    lda DST_MSB
    cmp #>MAZE_END+1    
    bne -

This increments the MSB, then loads it, then compares it, and tests the result.

With something like that, one trick I like to use is to preset X to the compare value.

You can then skip loading the value and compare X to the store value and save some instructions.

    lda #CHAR_WALL
    ldx #>MAZE_END+1
-
    sta (DST),y 
    inc DST_LSB
    bne -
    inc DST_MSB
    cpx DST_MSB
    bne -

Top Tip - Optimise Loops # 2

Another thing when you have a more complicated compare to do it to simply avoid doing it.

There is one bit of code that writes spaces all down the right hand side.

But after the adding, it needs to check if it has reached the end each time

-   lda #CHAR_PATH
    sta (DST),y
    lda DST_LSB
    clc
    adc #22
    sta DST_LSB
    bcc +
    inc DST_MSB
+
    lda DST_MSB
    cmp #$1E
    bne -

That is a simple example, sometimes it would be a 16-bit comparison.

Here, the start point and end point are fixed, so it is always going to run the same number of cycles, the 66 lines between them. So why not just turn it into a 66 cycle loop?

    ldx #MAZE_HEIGHT
-   lda #CHAR_PATH
    sta (DST),y
    lda DST_LSB
    clc
    adc #22
    sta DST_LSB
    bcc +
    inc DST_MSB
+
    dex
    bne -

Top Tip - Optimise Loops # 3

You can do similar things with other loops, avoid the comparison by counting down to zero.

    ldy #0
-   lda (MAP),y
    sta (SCREEN),y
    iny
    cpy #22
    bne -

Can become

    #MAZE_WIDTH-1
-   lda (MAP),y
    sta (SCREEN),y
    dey
    bpl -

In this case, Y need to got from 21 to 0, so the comparison is BPL which will stop when it hits -1

(as long as it does not matter that it is copying the last character first. The end result is the same, nothing is reversed, only the order that things happen in.)

Top Tip - Optimise Loops # 4

One rule to consider with loops is to move anything you can out side of the loop to speed it up.

And example is toggling the clock pin on an IO port 8 times as fast as possible

One version could look like:

    lda #0
    sta COUNTER
-   lda DATA
    ora #CLOCK_PIN
    sta VIA_PORTA
    lda DATA
    sta VIA_PORTA
    inc COUNTER
    lda COUNTER
    cmp #8
    bne -

A more optimised version could be

    ldy #8
    lda DATA
    tax
    ora #CLOCK_PIN

-   sta VIA_PORTA
    stx VIA_PORTA
    dey
    bne -

Here the value to be written (the contents of the DATA byte with and without the clock bit set) are pre-loaded into A and X and can then be written out to the port without reloading or recalculating.

Top Tip - Optimise Loops # 5

Continuing with that example, if you really want to go as fast as possible, but are less concerned about space, you can unroll the loop.

    lda DATA
    tax
    ora #CLOCK_PIN

    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA
    sta VIA_PORTA
    stx VIA_PORTA

That will toggle the clock pin 8 times without any delays between instructions.

The only way you could speed that up further is to arrange for the IO port to be mapped into zero page (which I have done before).

Fitting It All In Under 1K

Although I mentioned in the previous post that the code was a little over 1K in size and it would be nice to get it below 1K, for no real reason, I wasn't actively trying to achieve that.

However, as I was optimising things to make it better or faster or clearer, I did end up shedding quite a few bytes, so I had another pass through the code to see if there was anywhere I could make savings without affecting performance or readability of the code.

I had made sure that Y was always going to be left as zero, so I removed a couple of places where it was reset to 0.

I changed a few JMP label instructions to BNE label, in cases where label was within 127 bytes, and the zero flag was going to be clear, often the previous instruction was lda #constant and constant was not zero.

There were a few places I could reorder things to the code dropped through to the right place and didn't need any jumps or branches.

There were also a few hangover variables stored in the $03xx region. I moved those into zero page, which saved 1 byte per access.

Almost there. There was one variable which indicated if the bomb has been found. It only ever contained 0 or 1. This is where it was set to 1.

lda #1
sta f

I changed that to

inc FOUND

That saved the final two bytes.

After all that, the current version is now down to 977 bytes.

I am happy with that, I would take the rest of the day off, but it's past midnight already.

Improve readability and portability by using named constants

I have used code examples from various version, in the more recent ones, I have tried to get rid of all the literals like 22 and $1E00 etc. and replace those with named constants.

That should make it easier to follow, and often it makes the comments redundant.

; start in the middle
lda #<MAZE_MIDDLE
sta CURRENT_SQUARE_LSB
lda #>MAZE_MIDDLE
sta CURRENT_SQUARE_MSB

I have also gone for calculating all the positions and offsets in the constants. Avoids the need for code which loads the address of the start of the maze and then adds and offset.

If both of those values are constants, why not calculate them in advance and then just load the pre-calculated value in.

MAZE_WIDTH = 22
MAZE_HEIGHT = 66
MAZE_TOP = MAZE_END -(MAZE_HEIGHT * MAZE_WIDTH) + 1
MAZE_END_OF_TOP_LINE = MAZE_TOP + MAZE_WIDTH - 1

Test this by writing a PET version

One advantage of not having any screen size or address information in the code, and having it all in one location in the defines file means it is easier to change.

To test this, I wanted to write a PET version. This is similar to the VIC20 version, much of the code remains the same, only reading the joystick, making the sounds and the size and location of the screen change.

I did look at making the screen wider, but that made the maze too complicated. Maybe I could offer the user a choice of difficulty at the start, but the one on the VIC just seems about right, and so I have a 22 character maze in the middle of the screen.

I still need to write a new sound routine to make the ticks and explosion, but other than that it is working and looks rather good in green and black.

The updated VIC20 code is on github, I will upload the PET version once I have added the missing bits.

I now need to read my own blog post on PET Sounds.


All items are still available, and I can ship worldwide.

International shipping is a bit complicated at the moment, so if you want to order from outside the UK, please see this page for more information:

Sorry to have to do this, and I know this is going to affect sales, but please understand it is the only option I have right now.

Patreon

If you enjoy posts like this, you can support me via Patreon, and get access to advance previews of blog posts, and exclusive posts.

You also get progress updates on new projects and other behind the scenes updates, as well as access to my Patreon only Discord server for even more regular updates, and to discuss your own projects.

I currently have 50% off your fist month if you want to try it out.