How did I fix it? Did I spend hours debugging, poring over every line? No. I woke up in the middle of the night and thought about it and remembered that
I’d had a similar bug in this chapter when working on the original Ebook.
Stupidly I’d put the fix in the sources for the next chapter (44) but hadn’t applied it to the sources in the chapter where it had occurred (42). So I fired up my favourite code comparison tool (Devart Code Compare) and looked for differences between the source files for each chapter.
This was in the function AddObjectToCells and is part of the collision detection. It’s when an asteroid or player ship is partly on screen and calculating the cell coordinates that the object lies over. The fix was just adding these two lines so it doesn’t try and access the cells array with negative indices.
if (cellx < 0) cellx = 0;
if (celly < 0) celly = 0;