So. On to my ZX81 program – an implementation of the Lights Out puzzle. This is one of my go-to simple programs for putting an interactive system through its paces.
As such, this is not the first time I’ve implemented the puzzle—I included C64 implementations on the first Bumbershoot collection back in 2015…
…and quietly included source for a DOS port that was otherwise not distributed…
…and after I’d worked out the basics of linking directly against the Windows layer in Hello World 4 Different Ways I also quietly did a Windows console port based on the DOS edition.
Despite all that, I’ve never really talked about implementing it. So let’s talk a little about the puzzle and how implementation strategies differ when developing for an old home computer compared to a more powerful system.
The general design
The puzzle itself is easily modeled as a 5×5 rectangular array of boolean values, with a move that selects an index and toggles its neighbors in the four cardinal directions, if they exist. A modern implementation would separate the model (this 5×5 array and operations upon it) from the view (the actual display of the puzzle).
As it happens, none of my implementations do this. Because in each case the display is text on the screen, the screen’s display of the puzzle itself is used in place of the 5×5 array. Moves directly manipulate the screen memory and the puzzle state is read by consulting it.
So despite being implemented four ways for four computers using four different instruction sets, all four implementations are broadly similar:
- The static parts of the display are drawn. This includes the title, the puzzle board in solved state, and some kind of message area at the bottom of the screen. If we need to do something special to have a screen to draw on, that also happens here.
- Generate a random but solvable puzzle.
- Read the keyboard and execute the requested move. (Alternately, if the user has requested a reset, go back to step 2, and if the user has requested to quit, proceed to the final step.)
- Check to see if the puzzle is solved. If it’s not, go back to step 3.
- Congratulate the user on a solved puzzle. Ask if they want another game, and if so go back to step 2.
- Clean up the screen and return to the context from which the program was invoked.
Let’s take each of these in turn.
Displaying the board
This is, at the end of the day, a bunch of fancy print statements. Different platforms handle things like colors and the edges of the screen differently, but the simplest approach usually involves blitting things directly into screen memory.
I accomplish this by executing a thousand or so random moves. This is not the most efficient way to produce a guaranteed-solvable Lights-Out puzzle but it does produce a nice visual effect of the puzzle being scrambled. (Since making the same move twice perfectly undoes the move, the optimum way to generate a puzzle is to flip a coin for each of the 25 spots and execute a move on that spot if the coin comes up heads.
All my implementations use roughly the same algorithm for this. Each letter appears on the screen as the center of a notional button to press; I have a routine that computes the location of each letter within the screen memory. I can then examine screen memory at that location to flip the light there. I can also then compute the addresses of its neighbors to the north, south, east, and west. In each implementation the board and screen are designed such that moving off the board hits a point of valid screen memory that does not have a letter in it—this means I don’t need to bounds-check my moves but instead can simply see if there’s a letter at the point of interest.
Determining if the user has won
This is the same algorithm across all implementations. Go through each letter from A through Y, compute the part of screen memory that cell resides in, and examine it to see if it’s on. If it is, then we know the puzzle is yet unsolved. If we make it all the way through the loop, then we know that victory has been achieved.
Making the program fit the platform requires more decisions than just the ones above, of course. I’ll run through these in the order I implemented them.
This was the first implementation. As a result, it matches my description above almost exactly, with no additions or compromises. The board is drawn with character graphics, and the character cell with the letter in it is the only one that changes. If a letter is on or off, it is shifted in and out of inverse video, and then the color memory is independently changed to match. “On” was light red inverse video, and “off” was dark grey on a black background. Most of the rest of the text was in a lighter grey, but not quite reaching full white.
Random numbers are generated by calling out to the BASIC ROM, which is a bit opaque but is also very compact.
This is a reasonably compact program, weighing in at 977 bytes. It could be ported to the VIC-20 simply by altering a few constants.
The character graphics on the IBM PC lend themselves more readily to designing displays like this, and with 80 columns to work in the result here feels the cleanest of all my implementations.
DOS (more properly, the PC BIOS) does not really have a notion of “inverse video,” though. Instead, background and foreground colors are encoded separately alongside each letter. This means that the solution for displaying lights as on or off ends up being rather more elegant, because we need only adjust or inspect these color attributes to make our moves.
The random number generator here is a simple linear congruential generator that lets the x86 chip handle the multiplication.
The DOS version is a .COM file that is the smallest of the implementations overall, at 812 bytes.
Microsoft Windows (Windows 2000 or later)
The core logic here is mostly an adaptation of the DOS implementation. However, working with the console is complicated because there’s no guarantee that the window will have a display large enough to hold the board in it. The Windows Console API addresses this by allowing the developer to allocate and provide their own text buffer. This buffer cannot be reliably accessed directly—there are API functions to do so instead—but it behaves in a manner roughly analogous to the old PC BIOS color text mode. Like the DOS implementation, we only ever read or write color data (“attributes”, as the API calls them) after drawing the initial board.
The Windows Console is also a Unicode environment, so to get access to our box-drawing characters and such all of our strings are represented as UTF-16. Fortunately for us, NASM has a convenient macro for that.
The end result is a reasonably faithful translation the DOS implementation into 32-bit x86 code (notable mainly for shortening the RNG routine from 24 instructions to 10) and replaces all reads of screen memory and syscalls to BIOS or MS-DOS with Windows ABI calls. (I give simpler examples of how to do this in my old article about Hello World four different ways. The end result depends only on kernel32.dll, but the alignment requirements for a Windows executable make this the largest of the programs, weighing in at 5,120 bytes.
The game logic here is largely the same as the other three implementations, but the display logic is almost entirely different. The general C64 trick of relying on inverse video for a letter to represent a light’s status has been kept, but the ZX81 doesn’t have the kind of box-drawing graphics characters that any of my previous platforms used. Instead, it offers sixteen characters which fill in the four quadrants of the character cell in all possible ways, and then a somewhat more restricted dithered-grey.
My solution to the display of the board, then, was simply to not draw any walls at all—an “off” light is a 3×3 grid of inverted spaces with the letter in inverse video in the center, and an “on” light retains a half-character-cell-wide black border but leaves the letter in normal video. I am actually very, very happy with how this looks, and if I had done this before the DOS and Windows versions I’d have seriously considered using this rendering technique instead of what I actually went with.
This does make the actual “flip” operation more expensive, since instead of writing three color bytes (DOS, Windows) or one character byte and one color byte (C64) we need to instead write nine bytes scattered across screen memory. This cost is more than offset by the fact that the initial screen draw is now just a matter of filling the whole screen with inverted spaces.
Filling the whole screen with inverted spaces—in effect, having the program provide white text on a black background—also has the happy side effect of ensuring that every line is its full fixed length long. That makes computing the addresses of letters in screen memory much easier, because it is simply the address (start of display file)+33*row+column+1.
The final size of LIGHTSOUT.P is 903 bytes, but much of that isn’t the program. The raw binary is actually the smallest of all our platforms, at 704 bytes. Some of this might be me getting better at implementing the program with practice, but the far more likely reason is the simplification of the initial board display.
ZX81 compatibility concerns
It took several tries to get the ZX81 build to really work the way I wanted it to. Once the basic implementation had been debugged, my code ran fine in the sz81 emulator, but tests on the more accurate and more configurable EightyOne emulator showed that despite having a core binary size of (at the time) 710 bytes, attempting to load it into a 1K ZX81 would lock the system and attempting to load it into a 2K system would successfully load, but would not run. As long as there was at least 4KB of expansion memory, though, it would run fine.
This is a bit mysterious, as thanks to the screen-memory-as-game-state trick this program should require no more memory than it actually takes to load. But, it turns out, that is the trick: the system does need 2KB to hold both the program and the full display. We use every byte of the screen in making the display thanks to the inverse-video background, but even if we didn’t do that, the puzzle display is more than enough to blow past our limits. So that’s why we were getting the lockup, at least; my original linking program was including a full 793-byte display file at the end of the program, and this was enough to make the load operation blow past all of RAM in the 1K case. We can fix that by replacing it with a 25-byte “compressed” display file instead. At that point it loads in 1KB, but still seems to need 4KB to run. What’s going on? Why 4 instead of 2?
The issue turns out to be in my assumption of getting to have a fully expanded chunk of screen memory even if there’s room for it. If you have less than 3.5KB of RAM, then the Sinclair ROM will re-compress the display file back down to 25 bytes as your program starts. If you have more, then it will re-expand it to the full 793. I was relying on the latter behavior in my board display code.
This happens inside the ROM’s implementation of the CLS command, which starts at location $0A2A. Early on it does indeed check the value of RAMTOP to decide whether or not to do a collapsed or expanded display. Unfortunately, it does the check about halfway through. I solve this by replicating the first half of the routine and then jumping to the expanded display-file case.
I think the accepted practice was actually to use a ROM routine at $0918, which was the machine code implementation of PRINT AT. Subtract your target row from 24 and put that in register B. then subtract your target column from 33 and put that in register C. (Yes, this puts 0, 0 just off the lower-right hand side of the screen. I don’t know either. I think the idea here is to count down how many characters are left in each direction within the screen as a whole.) This routine will move the cursor there, expand the display file as necessary (thus doing a gigantic overlapping memory memory-blit) pretty much up to the top of the machine stack) and then loads location $400e with the memory location of you wanted.
One of the nice things about having an inverse-video screen is that I don’t have to mess with that, so I don’t.
The final issue was more trivial, but annoying nevertheless. I had to drastically shorten my “out of memory” message because there wasn’t enough room left to have a display file that could actually display it. Thus my reasonably grammatical original sentence got crammed down to “2KB+ RAM REQUIRED, SORRY”. So it goes.
But now it’s done!
I’ve collected all four implementations in binary form into one zip file. The source code for each version is in the Github repository as usual.
- Logan, I. and O’Hara, F. The Complete Timex TS1000/Sinclair ZX81 ROM Disassembly. Melbourne House, 1982.
- Baker, Toni. Mastering Machine Code on Your ZX81. Reston, 1982.