On the Atari 2600

For those less familiar with the details of 2600 hacking:

From the above diagram, you can see that one frame consists of 262 scanlines, of which only 192 are visible. Thirty-seven (plus three) occur, in some sense, before the screen is drawn and 30 occur after. The programmer is responsible for making sure they know what scanline they are on so that they can do things like adjust the background color, playfield graphics and sprites appropriately.

A scanline takes 76 CPU cycles to draw. In order to simultaneously track the current scanline and do potentially involved computations, the 2600 expects you to do your work in < 76 CPU cycle chunks and then sta WSYNC (write the A register to the memory location WSYNC).

sta WSYNC causes the processor to halt until the start of the next scanline. You have to be a little conservative, because some instructions take varying number of cycles, depending on the values they operate on. I suppose a very clever programmer could strobe WSYNC less than once per line, carefully tracking their cycles so as to absolutely maximize their use of the processor but that would be tricky.

The problem I had was that I was calculating too much on one of the scanlines in the OVERSCAN area and so my tracking of the number of scanlines was off, sometimes. The solution was to remove a few WSYNCs from my overscan loop and put them into that big calculation so that I never went over 76 cycles for a given chunk of calculation.