There’s two things which I don’t like about that colours program – firstly that the screen wasn’t clear before we coloured it, and secondly that it immediately returns to BASIC afterwards, and so you lose the bottom two rows of the screen before you even had a chance to see them.
We’ll get onto the screen shortly (I promise!), but first, that other issue…
Assuming it would be nice to return to BASIC (which actually isn’t something you usually do in a game, but anyway…) one solution would be to wait for the user to press a key before we exit the code. Luckily, this can be done using the ‘in’ command. As mentioned in the last post, this is a way to read information back from the machine, such as the state of the keyboard 🙂
Add the following just before the ‘ret’ statement:
WAITFORKEY: ld a, 0 in a, (254) cpl and %00011111 jp z, WAITFORKEY
What is happening here is as follows:
WAITFORKEY: ld a, 0 in a, (254)
This reads the entire keyboard, and puts the result in A. Okay, so that’s a slight lie, as there is no way we can store all the possible combinations of keys which can be pressed at the same time in one single byte…
The keyboard is handled by splitting it up into 8 sets of keys, each of the four 4 rows split into 2. For example, the bottom row is split into SHIFT, Z, X, C, & V and SPACE, SYM SHIFT, M, N, & B. What the code is doing is reading all 8 sets, with the state of the left-most key in each set being stored in the right-most (least-significant) bit of the result, so the result actually contains a record of which ‘column’ of the keyboard a key might have been pressed. You can’t tell which key, but it’s good enough to know if any key was pressed (and we could work out which column if we needed to)
cpl and %00011111 jp z, WAITFORKEY
‘cpl’ stands for ‘compliment’ and it reverses all the bits in A, so zero becomes one, and visa-versa. We then use ‘and’ to ensure only the first 5 bits are kept, as the top three contain information we’re not interested in, and isn’t related to the keyboard (remember that each set only handled five keys). We need to do this because if a key is pressed in that column, then the bit will be returned as reset, and complimenting it changes this so that the bit will instead be set if a key is held. ‘and’, like the ‘or’ we used when checking to see if we had filled all the colours, also detects if the result is zero or not, and finally we use that knowledge to keep checking the keyboard until something is pressed.
Now, if you run the program, it should wait at the end for you to press a key before returning to BASIC. For a further task, you can use similar logic to wait until no keys are pressed before filling the screen with colour, and could also wait for the pressed key to be released before returning. Have a play, you can’t break anything!