### Archive

Posts Tagged ‘tutorial’

## How To Write ZX Spectrum Games – Chapter 4

Random Numbers

Note: This article was originally written by Jonathan Cauldwell and is reproduced here with permission.

Generating random numbers in machine code can be a tricky problem for a novice programmer.

First of all, let’s get one thing straight. There is no such thing as a random number generator. The CPU merely follows instructions and has no mind of its own, it cannot simply pluck a number out of thin air based on a whim. Instead, it needs to follow a formula which will produce an unpredictable sequence of numbers which do not appear to follow any sort of pattern, and therefore give the impression of randomness. All we can do is return a false – or pseudo – random number.

One method of obtaining a pseudo-random number would be to use the Fibonacci sequence, however the easiest and quickest method of generating a pseudo-random 8-bit number on the Spectrum is by stepping a pointer through the ROM, and examining the contents of the byte at each location in turn. There is one small drawback to this method – the Sinclair ROM contains a very uniform and non-random area towards the end which is best avoided. By limiting the pointer to, say, the first 8K of ROM we still have a sequence of 8192 “random” numbers, more than enough for most games. In fact, every game I have ever written with a random number generator uses this method, or a very similar one:

```; Simple pseudo-random number generator.
; Steps a pointer through the ROM (held in seed), returning
; the contents of the byte at that location.

random ld hl,(seed)        ; Pointer
ld a,h
and 31              ; keep it within first 8k of ROM.
ld h,a
ld a,(hl)           ; Get "random" number from location.
inc hl              ; Increment pointer.
ld (seed),hl
ret
seed   defw 0```

Let’s put our new random number generator to use in our Centipede game. Every Centipede game needs mushrooms – lots of them – scattered randomly across the play area, and we can now call the random routine to supply coordinates for each mushroom as we display them. The bits underlined are those we need to add.

```; We want a black screen.

ld a,71             ; white ink (7) on black paper (0),
; bright (64).
ld (23693),a        ; set our screen colours.
xor a               ; quick way to load accumulator with zero.
call 8859           ; set permanent border colours.

; Set up the graphics.

ld hl,blocks        ; address of user-defined graphics data.
ld (23675),hl       ; make UDGs point to it.

; Okay, let's start the game.

call 3503           ; ROM routine - clears screen, opens chan 2.

; Initialise coordinates.

ld hl,21+15*256     ; load hl pair with starting coords.
ld (plx),hl         ; set player coords.

call basexy         ; set the x and y positions of the player.
call splayr         ; show player base symbol.

; Now we want to fill the play area with mushrooms.

ld a,68             ; green ink (4) on black paper (0),
; bright (64).
ld (23695),a        ; set our temporary colours.
mushlp ld a,22             ; control code for AT character.
rst 16
call random         ; get a 'random' number.
and 15              ; want vertical in range 0 to 15.
rst 16
call random         ; want another pseudo-random number.
and 31              ; want horizontal in range 0 to 31.
rst 16
ld a,145            ; UDG 'B' is the mushroom graphic.
rst 16              ; put mushroom on screen.
djnz mushlp         ; loop back until all mushrooms displayed.

; This is the main loop.

mloop  equ \$

; Delete the player.

call basexy         ; set the x and y positions of the player.
call wspace         ; display space over player.

; Now we've deleted the player we can move him before redisplaying him
; at his new coordinates.

ld bc,63486         ; keyboard row 1-5/joystick port 2.
in a,(c)            ; see what keys are pressed.
rra                 ; outermost bit = key 1.
push af             ; remember the value.
call nc,mpl         ; it's being pressed, move left.
pop af              ; restore accumulator.
rra                 ; next bit along (value 2) = key 2.
push af             ; remember the value.
call nc,mpr         ; being pressed, so move right.
pop af              ; restore accumulator.
rra                 ; next bit (value 4) = key 3.
push af             ; remember the value.
call nc,mpd         ; being pressed, so move down.
pop af              ; restore accumulator.
rra                 ; next bit (value 8) reads key 4.
call nc,mpu         ; it's being pressed, move up.

; Now he's moved we can redisplay the player.

call basexy         ; set the x and y positions of the player.
call splayr         ; show player.

halt                ; delay.

; Jump back to beginning of main loop.

jp mloop

; Move player left.

mpl    ld hl,ply           ; remember, y is the horizontal coord!
ld a,(hl)           ; what's the current value?
and a               ; is it zero?
ret z               ; yes - we can't go any further left.
dec (hl)            ; subtract 1 from y coordinate.
ret

; Move player right.

mpr    ld hl,ply           ; remember, y is the horizontal coord!
ld a,(hl)           ; what's the current value?
cp 31               ; is it at the right edge (31)?
ret z               ; yes - we can't go any further left.
inc (hl)            ; add 1 to y coordinate.
ret

; Move player up.

mpu    ld hl,plx           ; remember, x is the vertical coord!
ld a,(hl)           ; what's the current value?
cp 4                ; is it at upper limit (4)?
ret z               ; yes - we can go no further then.
dec (hl)            ; subtract 1 from x coordinate.
ret

; Move player down.

mpd    ld hl,plx           ; remember, x is the vertical coord!
ld a,(hl)           ; what's the current value?
cp 21               ; is it already at the bottom (21)?
ret z               ; yes - we can't go down any more.
inc (hl)            ; add 1 to x coordinate.
ret

; Set up the x and y coordinates for the player's gunbase position,
; this routine is called prior to display and deletion of gunbase.

basexy ld a,22             ; AT code.
rst 16
ld a,(plx)          ; player vertical coord.
rst 16              ; set vertical position of player.
ld a,(ply)          ; player's horizontal position.
rst 16              ; set the horizontal coord.
ret

; Show player at current print position.

splayr ld a,69             ; cyan ink (5) on black paper (0),
; bright (64).
ld (23695),a        ; set our temporary screen colours.
ld a,144            ; ASCII code for User Defined Graphic 'A'.
rst 16              ; draw player.
ret

wspace ld a,71             ; white ink (7) on black paper (0),
; bright (64).
ld (23695),a        ; set our temporary screen colours.
ld a,32             ; SPACE character.
rst 16              ; display space.
ret

; Simple pseudo-random number generator.
; Steps a pointer through the ROM (held in seed), returning
; the contents of the byte at that location.

random ld hl,(seed)        ; Pointer
ld a,h
and 31              ; keep it within first 8k of ROM.
ld h,a
ld a,(hl)           ; Get "random" number from location.
inc hl              ; Increment pointer.
ld (seed),hl
ret
seed   defw 0

plx    defb 0              ; player's x coordinate.
ply    defb 0              ; player's y coordinate.

; UDG graphics.

blocks defb 16,16,56,56,124,124,254,254    ; player base.
defb 24,126,255,255,60,60,60,60     ; mushroom.```

Once run this listing looks more like a Centipede game than it did before, but there’s a major problem. The mushrooms are distributed in a random fashion around the screen, but the player can move straight through them. Some form of collision detection is required to prevent this happening, and we shall cover this in the next chapter.

Categories: Z80 Assembly

# Loudspeaker Sound Effects

Note: This article was originally written by Jonathan Cauldwell and is reproduced here with permission.

The Loudspeaker

There are two ways of generating sound and music on the ZX Spectrum, the best and most complicated of which is via the AY38912 sound chip in the 128K models. This method is described in detail in a later chapter, but for now we will concern ourselves with the 48K loudspeaker. Simple it may be, but this method does have its uses especially for short sharp sound effects during games.

Beep

First of all we need to know how to produce a beep of a certain pitch and duration, and the Sinclair ROM has a fairly accessible routine to do the job for us at address 949, all that is required is to pass the parameters for pitch in the HL register pair and duration in DE, call 949 and we get an appropriate “beep”.

Alas, the way in which we work out the parameters required is a little tricky as it needs a little calculation. We need to know the Hertz value for the frequency of note to emit, essentially just the number of times the loudspeaker needs to be toggled each second to produce the desired pitch. A suitable table is located below (# stands for ‘sharp’):

Middle C 261.63

C# 277.18

D 293.66

D# 311.13

E 329.63

F 349.23

F# 369.99

G 392.00

G# 415.30

A 440.00

A# 466.16

B 493.88

For each octave higher, simply double the frequency, to go an octave lower halve it. For example, to produce a note C one octave higher than middle C we take the value for Middle C – 261.63, and double it to 523.26.

Once the frequency is established we multiply it by the number of seconds required and pass this to the ROM routine in the DE register pair as the duration – so to play the note at middle C for one tenth of a second the duration required would be 261.63 * 0.1 = 26. The pitch is worked out by first dividing the 437500 by the frequency, subtracting 30.125 and passing the result in the HL registers. For middle C this would mean a value of 437500 / 261.63 – 30.125 = 1642.

In other words:

DE = Duration = Frequency * Seconds

HL = Pitch = 437500 / Frequency – 30.125

So to play note G# one octave above that of middle C for one quarter of one second:

```; Frequency of G sharp in octave of middle C = 415.30
; Frequency of G sharp one octave higher = 830.60
; Duration = 830.6 / 4 = 207.65
; Pitch = 437500 / 830.6 - 30.125 = 496.6

ld hl,497           ; pitch.
ld de,208           ; duration.
call 949            ; ROM beeper routine.
ret```

Of course, this routine isn’t just useful for musical notes – we can use it for a variety of effects as well, one of my favourites being a simple pitch bend routine:

```       ld hl,500           ; starting pitch.
ld b,250            ; length of pitch bend.
loop   push bc
push hl             ; store pitch.
ld de,1             ; very short duration.
call 949            ; ROM beeper routine.
pop hl              ; restore pitch.
inc hl              ; pitch going up.
pop bc
djnz loop           ; repeat.
ret```

Have a play with the above routine – by fiddling with it it’s pretty easy to adjust the pitch up and down, and to change the starting frequency and pitch bend and length producing a number of interesting effects. One word of warning though – Don’t go too crazy with your pitch or duration values or the beeper routine will get stuck and you won’t be able to regain control of your Spectrum without resetting it.

White Noise

When using the loudspeaker we don’t even have to stick with the routines in the ROM, it is easy enough to write our own sound effects routines, especially if we want to generate white noise for crashes and bangs. White noise is usually a lot more fun to play with.

To generate white noise all we need is a quick and simple random number generator (a Fibonacci sequence might work, but I’d recommend stepping a pointer through the first 8K of ROM and fetching the byte at each location to get a reasonably random 8-bit number). Then write this value to port 254. Remember this port also controls the border colour so if you don’t want a striped multicolour border effect we need to mask off the border bits with AND 248 and add the number for the border colour we want (1 for blue, 2 for red etc.) before performing an OUT (254) instruction. When we’ve done this we need to put in a small delay loop (short for high pitch, long for lower pitch) and repeat the process a few hundred times. This will give us a nice “crash” effect.

This routine is based on a sound effect from Egghead 3:

```noise  ld e,250            ; repeat 250 times.
ld hl,0             ; start pointer in ROM.
noise2 push de
ld b,32             ; length of step.
noise0 push bc
ld a,(hl)           ; next "random" number.
inc hl              ; pointer.
and 248             ; we want a black border.
out (254),a         ; write to speaker.
ld a,e              ; as e gets smaller...
cpl                 ; ...we increase the delay.
noise1 dec a               ; decrement loop counter.
jr nz,noise1        ; delay loop.
pop bc
djnz noise0         ; next step.
pop de
ld a,e
sub 24              ; size of step.
cp 30               ; end of range.
ret z
ret c
ld e,a
cpl
noise3 ld b,40             ; silent period.
noise4 djnz noise4
dec a
jr nz,noise3
jr noise2```
Categories: Z80 Assembly

# Keyboard and Joystick Control

Note: This article was originally written by Jonathan Cauldwell and is reproduced here with permission.

## One Key at a Time

Providing that you haven’t disabled or otherwise meddled with the Spectrum’s default interrupt mode the ROM will automatically read the keyboard and update several system variables located at memory location 23552 fifty times per second. The simplest way to check for a keypress is to first load address 23560 with a null value, then interrogate this location until it changes, the result being the ASCII value of the key pressed. This is most useful for those “press any key to continue” situations, for choosing items from a menu and for keyboard input such as high score name entry routines. Such a routine might look like this:

```       ld hl,23560         ; LAST K system variable.
ld (hl),0           ; put null value there.
loop   ld a,(hl)           ; new value of LAST K.
cp 0                ; is it still zero?
jr z,loop           ; yes, so no key pressed.
ret                 ; key was pressed.```

## Multiple Key-presses

Single key-presses are seldom any use for fast action arcade games however, for this we need to detect more than one simultaneous key-press and this is where things get a little trickier. Instead of reading memory addresses we have to read one of eight ports, each of which corresponds to a row of five keys. Of course, most Spectrum models appear to have far more keys than this so where did they all go? Well actually, they don’t. The original Spectrum keyboard layout consisted of just forty keys, arranged in eight groupings or rows of five. In order to access some of the functions it was necessary to press certain combinations of keys together – for example to delete the combination required was CAPS SHIFT and 0 together. Sinclair added these extra keys when the Spectrum Plus came onto the scene in 1985, and they work by simulating the combinations of key-presses required for the original rubber keyed models.

The original keyboard layout was separated into these groupings:

```Port  Keys

32766 B, N, M, Symbol Shift, Space
49150 H, J, K, L, Enter
57342 Y, U, I, O, P
61438 6, 7, 8, 9, 0
63486 5, 4, 3, 2, 1
64510 T, R, E, W, Q
65022 G, F, D, S, A
65278 V, C, X, Z, Caps Shift```

To discover which keys are being pressed we read the appropriate port number, each key in the row being allocated one of the lower five bits d0-d4 (values 1,2,4,8 and 16) where d0 represents the outside key, d4 the innermost. Curiously, each bit is high where it is not pressed, low where it is – the opposite of what you might expect.

To read a row of five keys we simply load the port number into the bc register pair, then perform the instruction in a,(c). As we only need the lowest value bits we can ignore the bits we dont want either with an and 31 or by rotating the bits out of the accumulator into the carry flag using five rra:call c,(address) instructions.

If this is difficult to understand consider the following example:

```       ld bc,63486         ; keyboard row 1-5/joystick port 2.
in a,(c)            ; see what keys are pressed.
rra                 ; outermost bit = key 1.
push af             ; remember the value.
call nc,mpl         ; it's being pressed, move left.
pop af              ; restore accumulator.
rra                 ; next bit along (value 2) = key 2.
push af             ; remember the value.
call nc,mpr         ; being pressed, so move right.
pop af              ; restore accumulator.
rra                 ; next bit (value 4) = key 3.
push af             ; remember the value.
call nc,mpd         ; being pressed, so move down.
pop af              ; restore accumulator.
rra                 ; next bit (value 8) reads key 4.
call nc,mpu         ; it's being pressed, move up.```

## Joysticks

Sinclair joystick ports 1 and 2 were simply mapped to each of the rows of number keys and you can easily prove this by going into the BASIC editor and using the joystick to type numbers. Port 1 (Interface 2) was mapped to the keys 6,7,8,9 and 0, Port 2 (Interface 1) to keys 1,2,3,4 and 5. To detect joystick input we simply read the port in the same way as reading the keyboard. Sinclair joysticks use ports 63486 (Interface 1/port 2), and 61438 (Interface 2/port 1), bits d0-d4 will give a 0 for pressed, 1 for not pressed.

The popular Kempston joystick format is not mapped to the keyboard and can be read by using port 31 instead. This means we can use a simple in a,(31). Again, bit values d0-d4 are used although this time the bit settings are as you might expect, with a bit set high if the joystick is being applied in a particular direction. The resulting bit values will be 1 for pressed, 0 for not pressed.

```
; Example joystick control routine.

joycon ld bc,31            ; Kempston joystick port.
and 2               ; check "left" bit.
call nz,joyl        ; move left.
and 1               ; test "right" bit.
call nz,joyr        ; move right.
and 8               ; check "up" bit.
call nz,joyu        ; move up.
and 4               ; check "down" bit.
call nz,joyd        ; move down.
and 16              ; try the fire bit.
call nz,fire        ; fire pressed.```

## A Simple Game

We can now go one step further and, putting into practice what we have already covered, write the main control section for a basic game. This will form the basis of a simple Centipede variant we will be developing over the next few chapters. We haven’t covered everything needed for such a game yet but we can make a start with a small control loop which allows the player to manipulate a small gun base around the screen. Be warned, this program has no exit to BASIC so make sure you’ve saved a copy of your source code before running it.

```; We want a black screen.

ld a,71             ; white ink (7) on black paper (0),
; bright (64).
ld (23693),a        ; set our screen colours.
xor a               ; quick way to load accumulator with zero.
call 8859           ; set permanent border colours.

; Set up the graphics.

ld hl,blocks        ; address of user-defined graphics data.
ld (23675),hl       ; make UDGs point to it.

; Okay, let's start the game.

call 3503           ; ROM routine - clears screen, opens chan 2.

; Initialise coordinates.

ld hl,21+15*256     ; load hl pair with starting coords.
ld (plx),hl         ; set player coords.

call basexy         ; set the x and y positions of the player.
call splayr         ; show player base symbol.

; This is the main loop.

mloop  equ \$

; Delete the player.

call basexy         ; set the x and y positions of the player.
call wspace         ; display space over player.

; Now we've deleted the player we can move him before redisplaying him
; at his new coordinates.

ld bc,63486         ; keyboard row 1-5/joystick port 2.
in a,(c)            ; see what keys are pressed.
rra                 ; outermost bit = key 1.
push af             ; remember the value.
call nc,mpl         ; it's being pressed, move left.
pop af              ; restore accumulator.
rra                 ; next bit along (value 2) = key 2.
push af             ; remember the value.
call nc,mpr         ; being pressed, so move right.
pop af              ; restore accumulator.
rra                 ; next bit (value 4) = key 3.
push af             ; remember the value.
call nc,mpd         ; being pressed, so move down.
pop af              ; restore accumulator.
rra                 ; next bit (value 8) reads key 4.
call nc,mpu         ; it's being pressed, move up.

; Now he's moved we can redisplay the player.

call basexy         ; set the x and y positions of the player.
call splayr         ; show player.

halt                ; delay.

; Jump back to beginning of main loop.

jp mloop

; Move player left.

mpl    ld hl,ply           ; remember, y is the horizontal coord!
ld a,(hl)           ; what's the current value?
and a               ; is it zero?
ret z               ; yes - we can't go any further left.
dec (hl)            ; subtract 1 from y coordinate.
ret

; Move player right.

mpr    ld hl,ply           ; remember, y is the horizontal coord!
ld a,(hl)           ; what's the current value?
cp 31               ; is it at the right edge (31)?
ret z               ; yes - we can't go any further left.
inc (hl)            ; add 1 to y coordinate.
ret

; Move player up.

mpu    ld hl,plx           ; remember, x is the vertical coord!
ld a,(hl)           ; what's the current value?
cp 4                ; is it at upper limit (4)?
ret z               ; yes - we can go no further then.
dec (hl)            ; subtract 1 from x coordinate.
ret

; Move player down.

mpd    ld hl,plx           ; remember, x is the vertical coord!
ld a,(hl)           ; what's the current value?
cp 21               ; is it already at the bottom (21)?
ret z               ; yes - we can't go down any more.
inc (hl)            ; add 1 to x coordinate.
ret

; Set up the x and y coordinates for the player's gunbase position,
; this routine is called prior to display and deletion of gunbase.

basexy ld a,22             ; AT code.
rst 16
ld a,(plx)          ; player vertical coord.
rst 16              ; set vertical position of player.
ld a,(ply)          ; player's horizontal position.
rst 16              ; set the horizontal coord.
ret

; Show player at current print position.

splayr ld a,69             ; cyan ink (5) on black paper (0),
; bright (64).
ld (23695),a        ; set our temporary screen colours.
ld a,144            ; ASCII code for User Defined Graphic 'A'.
rst 16              ; draw player.
ret

wspace ld a,71             ; white ink (7) on black paper (0),
; bright (64).
ld (23695),a        ; set our temporary screen colours.
ld a,32             ; SPACE character.
rst 16              ; display space.
ret

plx    defb 0              ; player's x coordinate.
ply    defb 0              ; player's y coordinate.

; UDG graphics.

blocks defb 16,16,56,56,124,124,254,254    ; player base.```

Fast, isn’t it? In fact, we’ve slowed the loop down with a halt instruction but it still runs at a speedy 50 frames per second, which is probably a little too fast. Don’t worry, as we add more features to the code it will begin to slow down. If you are feeling confident you might like to try adapting the above program to work with a Kempston joystick. It isn’t difficult, and merely requires changing port 63486 to port 31, and replacing the four subsequent call nc,(address) to call c,(address) (The bits are reversed, remember?)

Redefineable keys are a little more tricky. As you are probably aware, the original Spectrum keyboard was divided into 8 rows of 5 keys each, and by reading the port associated with a particular row of keys, then testing bits d0-d4 we can tell if a particular key is being pressed. If you were to replace ld bc,31 in the code snippet above with ld bc,49150 you could test for the row of keys H to Enter – though that doesn’t make for a convenient redefine keys routine. Thankfully, there is another way of going about it.

We can establish the port required for each row of keys using the formula in the Spectrum manual. Where n is the row number 0-7 the port address will be 254+256*(255-2^n). There’s a ROM routine at address 654 which does a lot of the hard work for us by returning the number of the key pressed in the e register, in the range 0-39. 0-7 correspond to the innermost key of each row in turn (that’s B, H, Y, 6, 5, T, G and V), 8-15 to the next key along in each row up to 39 for the outermost key on the last row – CAPS SHIFT. The shift key status, just for the record, is also returned in d. If no key is pressed then e returns 255.

The ROM routine can only return a single key number which is no good for detecting more than one keypress at a time. To determine whether or not a specific key is being pressed at any time we need to convert the number back into a port and bit, then read that port and check the individual bit for ourselves. There’s a very handy routine I use for the job, and it’s the only routine in my games which I didn’t write myself. Credit for that must go to Stephen Jones, a programmer who used to write excellent articles for the Spectrum Discovery Club many years ago. To use his routine, load the accumulator with the number of the key you wish to test, call ktest, then check the carry flag. If it’s set the key is not being pressed, if there’s no carry then the key is being pressed. If that’s too confusing and seems like the wrong way round, put a ccf instruction just before the ret.

```; Mr. Jones' keyboard test routine.

ktest  ld c,a              ; key to test in c.
and 7               ; mask bits d0-d2 for row.
inc a               ; in range 1-8.
ld b,a              ; place in b.
srl c               ; divide c by 8,
srl c               ; to find position within row.
srl c
ld a,5              ; only 5 keys per row.
sub c               ; subtract position.
ld c,a              ; put in c.
ld a,254            ; high byte of port to read.
ktest0 rrca                ; rotate into position.
djnz ktest0         ; repeat until we've found relevant row.
in a,(254)          ; read port (a=high, 254=low).
ktest1 rra                 ; rotate bit out of result.
dec c               ; loop counter.
jp nz,ktest1        ; repeat until bit for position in carry.
ret```
Categories: Z80 Assembly

# Simple Text and Graphics

Note: This article was originally written by Jonathan Cauldwell and is reproduced here with permission.

## Introduction

So you’ve read the Z80 documentation, you know how the instructions affect the registers and now you want to put this knowledge to use. Judging by the number of emails I have received asking how to read the keyboard, calculate screen addresses or emit white noise from the beeper it has become clear that there really isn’t much in the way of resources for the new Spectrum programmer. This document, I hope, will grow to fill this void in due course. In its present state it is clearly years from completion, but in publishing the few basic chapters that exist to date I hope it will be of help to other programmers.

The ZX Spectrum was launched in April 1982, and by today’s standards is a primitive machine. In the United Kingdom and a few other countries it was the most popular games machine of the 1980s, and through the joys of emulation many people are enjoying a nostalgic trip back in time with the games of their childhoods. Others are only now discovering the machine for the first time, and some are even taking up the challenge of writing games for this simple little computer. After all, if you can write a decent machine code game for a 1980s computer there probably isn’t much you couldn’t write.

Purists will hate this document, but writing a game isn’t about writing “perfect” Z80 code – as if there were such a thing. A Spectrum game is a substantial undertaking, and you won’t get around to finishing it if you are too obsessed with writing the very best scoring or keyboard reading algorithms. Once you’ve written a routine that works and doesn’t cause problems elsewhere, move on to the next routine. It doesn’t matter if it’s a little messy or inefficient, because the important part is to get the gameplay right. Nobody in his right mind is going to disassemble your code and pick faults with it.

The chapters in this document have been ordered in a way designed to enable the reader to start writing a simple game as soon as possible. Nothing beats the thrill of writing your first full machine-code game, and I have set out this manual in such a way as to cover the very basic minimum requirements for this in the first few chapters. From there we move on to cover more advanced methods which should enable the reader to improve the quality of games he is capable of writing.

Throughout this document a number of assumptions have been made. For a start, it is assumed that the reader is familiar with most Z80 opcodes and what they do. If not there are plenty of guides around which will explain these far better than I could ever do. Learning machine code instructions isn’t difficult, but knowing how to put them together in meaningful ways can be. Familiarity with the load (ld), compare (cp), and conditional jump (jp z / jp c / jp nc) instructions is a good place to start. The rest will fall into place once these are learned.

## Tools

These days we have the benefit of more sophisticated hardware, and there is no need to develop software on the machine for which it is intended. There are plenty of adequate cross-assemblers around which will allow Spectrum software to be developed on a PC and the binary file produced can then be imported into an emulator – SPIN is a popular emulator which has support for this feature.

For graphics there’s a tool called SevenUp which I use, and can thoroughly recommend. This can convert bitmaps into Spectrum images, and allows the programmer to specify the order in which sprites or other graphics are sorted. Output can be in the form of a binary image, or source code. Another popular program is TommyGun.

Music wise I’d recommend the SoundTracker utility which can be downloaded from the World of Spectrum archives. There’s a separate compiler program you’ll also need. Bear in mind that these are Spectrum programs, not PC tools and need to be run on an emulator.

As editors and cross-compilers go I am not in a position to recommend the best available, because I use an archaic editor and Z80 Macro cross-assembler written in 1985, running in DOS windows. Neither are tools I would recommend to others. If you require advice on which tools might be suitable for you, I suggest you try the World of Spectrum development forums. This friendly community has a wide range of experience and is always willing to help.

## Personal Quirks

Over the many years that I have been writing Spectrum software a number of habits have formed which may seem odd. The way I order my coordinates, for example, does not follow the conventions of mathematics. My machine code programs follow the Sinclair BASIC convention of PRINT AT x,y; where x refers to the number of character cells or pixels from the top of the screen and y is the number of characters or pixels from the left edge. If this seems confusing at first I apologise, but it always seemed a more logical way of ordering things and it just stuck with me. Some of my methodology may seem unusual in places, so where you can devise a better way of doing something by all means go with that instead.

One other thing: commenting your code as you go along is important, if not essential. It can be hellishly difficult trying to find a bug in an uncommented routine you wrote only a few weeks ago. It may seem tedious to have to document every subroutine you write, but it will save development time in the long run. In addition, should you wish to re-use a routine in another game at some point in the future, it will be very easy to rip out the required section and adapt it for your next project.

Other than that, just have fun. If you have any suggestions to make or errors to report, please get in touch.

Jonathan Cauldwell, January 2007.

# Hello World

The first BASIC program that most novice programmers write is usually along these lines:

```10 PRINT "Hello World"
20 GOTO 10```

Alright, so the text may differ. Your first effort may have said “Dave is ace” or “Rob woz ere”, but let’s face it, displaying text and graphics on screen is probably the most important aspect of writing any computer game and – with the exception of pinball or fruit machines – it is practically impossible to conceive a game without a display. With this in mind let us begin this tutorial with some important display routines in the Spectrum ROM.

So how would we go about converting the above BASIC program to machine code? Well, we can PRINT by using the RST 16 instruction – effectively the same as PRINT CHR\$ a – but that merely prints the character held in the accumulator to the current channel. To print a string on screen, we need to call two routines – one to open the upper screen for printing (channel 2), then the second to print the string. The routine at ROM address 5633 will open the channel number we pass in the accumulator, and 8252 will print a string beginning at de with length bc to this channel. Once channel 2 is opened, all printing is sent to the upper screen until we call 5633 with another value to send output elsewhere. Other interesting channels are 1 for the lower screen (like PRINT #1 in BASIC, and we can use this to display on the bottom two lines) and 3 for the ZX Printer.

```
ld a,2              ; upper screen
call 5633           ; open channel
loop   ld de,string        ; address of string
ld bc,eostr-string  ; length of string to print
call 8252           ; print our string
jp loop             ; repeat until screen is full

string defb '(your name) is cool'
eostr  equ \$```

Running this listing fills the screen with the text until the scroll? prompt is displayed at the bottom. You will note however, that instead of each line of text appearing on a line of its own as in the BASIC listing, the beginning of each string follows directly on from the end of the previous one which is not exactly what we wanted. To achieve this we need to throw a line ourselves using an ASCII control code. One way of doing this would be to load the accumulator with the code for a new line (13), then use RST 16 to print this code. Another more efficient way is to add this ASCII code to the end of our string thus:

```string defb '(your name) is cool'
defb 13
eostr  equ \$```

There are a number of ASCII control codes like this which alter the current printing position, colours etc. and experimentation will help you to decide which ones you yourself will find most useful. Here are the main ones I use:

13 NEWLINE sets print position to the beginning of the next line.

16,c INK Sets ink colour to the value of the following byte.

17,c PAPER Sets ink colour to the value of the following byte.

22,x,y AT Sets print x and y coordinates to the values specified in the following two bytes.

Code 22 is particularly handy for setting the coordinates at which a string or graphic character is to be displayed. This example will display an exclamation mark in the bottom right of the screen:

```       ld a,2              ; upper screen
call 5633           ; open channel
ld de,string        ; address of string
ld bc,eostr-string  ; length of string to print
call 8252           ; print our string
ret
string defb 22,21,31,'!'
eostr  equ \$```

This program goes one step further and animates an asterisk from the bottom to the top of the screen:

```       ld a,2          ; 2 = upper screen.
call 5633       ; open channel.
ld a,21         ; row 21 = bottom of screen.
ld (xcoord),a   ; set initial x coordinate.
loop   call setxy      ; set up our x/y coords.
ld a,'*'        ; want an asterisk here.
rst 16          ; display it.
call delay      ; want a delay.
call setxy      ; set up our x/y coords.
ld a,32         ; ASCII code for space.
rst 16          ; delete old asterisk.
call setxy      ; set up our x/y coords.
ld hl,xcoord    ; vertical position.
dec (hl)        ; move it up one line.
ld a,(xcoord)   ; where is it now?
cp 255          ; past top of screen yet?
jr nz,loop      ; no, carry on.
ret
delay  ld b,10         ; length of delay.
delay0 halt            ; wait for an interrupt.
djnz delay0     ; loop.
ret             ; return.
setxy  ld a,22         ; ASCII control code for AT.
rst 16          ; print it.
ld a,(xcoord)   ; vertical position.
rst 16          ; print it.
ld a,(ycoord)   ; y coordinate.
rst 16          ; print it.
ret

xcoord defb 0
ycoord defb 15```

## Printing Simple Graphics

Moving asterisks around the screen is all very fine but for even the simplest game we really need to display graphics. Advanced graphics are discussed in later chapters, for now we will only be using simple Space Invader type graphics, and as any BASIC programmer will tell you, the Spectrum has a very simple mechanism for this – the User Defined Graphic, usually abbreviated to UDG.

The Spectrum’s ASCII table contains 21 (19 in 128k mode) user-defined graphics characters, beginning at code 144 and going on up to 164 (162 in 128k mode). In BASIC UDGs are defined by poking data into the UDG area at the top of RAM, but in machine code it makes more sense to change the system variable which points to the memory location at which the UDGs are stored, which is done by changing the two-byte value at address 23675.

We can now modify our moving asterisk program to display a graphic instead with a few changes which are underlined.

```       ld hl,udgs      ; UDGs.
ld (23675),hl   ; set up UDG system variable.
ld a,2          ; 2 = upper screen.
call 5633       ; open channel.
ld a,21         ; row 21 = bottom of screen.
ld (xcoord),a   ; set initial x coordinate.
loop   call setxy      ; set up our x/y coords.
ld a,144        ; show UDG instead of asterisk.
rst 16          ; display it.
call delay      ; want a delay.
call setxy      ; set up our x/y coords.
ld a,32         ; ASCII code for space.
rst 16          ; delete old asterisk.
call setxy      ; set up our x/y coords.
ld hl,xcoord    ; vertical position.
dec (hl)        ; move it up one line.
ld a,(xcoord)   ; where is it now?
cp 255          ; past top of screen yet?
jr nz,loop      ; no, carry on.
ret
delay  ld b,10         ; length of delay.
delay0 halt            ; wait for an interrupt.
djnz delay0     ; loop.
ret             ; return.
setxy  ld a,22         ; ASCII control code for AT.
rst 16          ; print it.
ld a,(xcoord)   ; vertical position.
rst 16          ; print it.
ld a,(ycoord)   ; y coordinate.
rst 16          ; print it.
ret
xcoord defb 0
ycoord defb 15
udgs   defb 60,126,219,153
defb 255,255,219,219```

As Rolf Harris used to say: “Can you tell what it is yet?”

Of course, there’s no reason why you couldn’t use more than the 21 UDGs if you wished. Simply set up a number of banks of them in memory and point to each one as you need it.

Alternatively, you could redefine the character set instead. This gives a larger range of ASCII characters from 32 (SPACE) to 127 (the copyright symbol). You could even mix text and graphics, redefining the letters and numbers of your font to the style of your choice, then using up the symbols and lowercase letters for aliens, zombies or whatever your game requires. To point to another set we subtract 256 from the address at which the font is placed and place this in the two byte system variable at address 23606. The default Sinclair font for example is located at ROM address 15616, so the system variable at address 23606 points to 15360 when the Spectrum is first switched on.

This code copies the Sinclair ROM font to RAM making it “bolder” as it goes, then sets the system variable to point to it:

```       ld hl,15616         ; ROM font.
ld de,60000         ; address of our font.
ld bc,768           ; 96 chars * 8 rows to alter.
font1  ld a,(hl)           ; get bitmap.
rlca                ; rotate it left.
or (hl)             ; combine 2 images.
ld (de),a           ; write to new font.
inc hl              ; next byte of old.
inc de              ; next byte of new.
dec bc              ; decrement counter.
ld a,b              ; high byte.
or c                ; combine with low byte.
jr nz,font1         ; repeat until bc=zero.
ld hl,60000-256     ; font minus 32*8.
ld (23606),hl       ; point to new font.
ret```

## Displaying Numbers

For most games it is better to define the player’s score as a string of ASCII digits, although that does mean more work in the scoring routines and makes high score tables a real pain in the backside for an inexperienced assembly language programmer. We will cover this in a later chapter, but for now we’ll use some handy ROM routines to print numbers for us.

There are two ways of printing a number on the screen, the first of which is to make use of the same routine that the ROM uses to print Sinclair BASIC line numbers. For this we simply load the bc register pair with the number we wish to print, then call 6683:

```      ld bc,(score)
call 6683```

However, since BASIC line numbers can go only as high as 9999, this has the disadvantage of only being capable of displaying a four digit number. Once the player’s score reaches 10000 other ASCII characters are displayed in place of numbers. Fortunately, there is another method which goes much higher. Instead of calling the line number display routine we can call the routine to place the contents of the bc registers on the calculator stack, then another routine which displays the number at the top of this stack. Don’t worry about what the calculator stack is and what its function is because it’s of little use to an arcade games programmer, but where we can make use of it we will. Just remember that the following three lines will display a number from 0 to 65535 inclusive:

```       ld bc,(score)
call 11563          ; stack number in bc.
call 11747          ; display top of calc. stack.```

## Changing Colours

To set the permanent ink, paper, brightness and flash levels we can write directly to the system variable at 23693, then clear the screen with a call to the ROM:

```; We want a yellow screen.
ld a,49             ; blue ink (1) on yellow paper (6*8).
ld (23693),a        ; set our screen colours.
call 3503           ; clear the screen.```

The quickest and simplest way to set the border colour is to write to port 254. The 3 least significant bits of the byte we send determine the colour, so to set the border to red:

```       ld a,2              ; 2 is the code for red.
out (254),a         ; write to port 254.```

Port 254 also drives the speaker and Mic socket in bits 3 and 4. However, the border effect will only last until your next call to the beeper sound routine in the ROM (more on that later), so a more permanent solution is required. To do this, we simply need to load the accumulator with the colour required and call the ROM routine at 8859. This will change the colour and set the BORDCR system variable (located at address 23624) accordingly. To set a permanent red border we can do this:

```       ld a,2              ; 2 is the code for red.
call 8859           ; set border colour.```
Categories: Z80 Assembly

## Sprite Graphics Tutorial

This tutorial is by Derek M. Smith © 2005.

Sprite graphics are the backbone of arcade games. Put simply, a sprite is a moveable screen object, such as a spaceship, alien, or anything else you can imagine. Some computers come with built in sprites, such as the Commodore and Atari ranges. These machines could generate sprites without the need for complex programming, and on top of this, they used an additional processor, which left the main CPU free to get on with the rest of the program. The Spectrum sadly was never adorned with such luxuries and so programmers had to write their own sprite routines from scratch (a daunting task for the amateur).

Sloppy programming in this area could really spoil a game, either making it too slow, or through flickering graphics.

A simple sprite routine is often one of the first things a new programmer, after having mastered the basics of machine code, will have a go at.

At first it seems straight forward, but soon all sorts of hurdles appear. The first usually being the Spectrum’s unusual screen arrangement. More experienced programmers who have mastered the basic sprite handling routine will then seek ways to optimise it.

This tutorial is aimed at both beginners and the more experienced programmers. Beginners will learn the principles behind sprite programming and the experienced machine coders will learn to find ways of improving their routines. For simplicity, this tutorial assumes that the reader has a decent grasp of assembly language.

ZX Spectrum screen arrangement
“The display file stores the television picture. It is rather curiously laid out…” -Spectrum Manual ch24 p164

On the face of it the Spectrum’s screen arrangement is pretty strange. Just watch the screen of a game loading, and you’ll understand what I mean. Why does it skip lines like that? Sure it may be interesting to watch the picture being gradually built up, but it can be a real pain when it comes to writing a sprite routine (at least until you understand the principles behind its layout).

First off, the Spectrum screen has a resolution of 256 pixels across by 192 down, not including the border around it. It can display 8 colours (including black and white) with two levels of intensity (brightness).

The Memory Map for the screen starts at address 16384 and is 6912 bytes long.
It is split in to two halves with the first 6144 bytes containing the bit-map (or pixel map, if you wish) and the remaining 768 bytes containing the attribute-map.

Consider the bit-map first:-

Each line of 256 pixels is stored as 32 bytes: 32 x 8 = 256. So far so good.

Now you would think that each line would follow on from the one before in the pixel map, and most people (myself included) write their first sprite routine thinking this to be the case – only to find that when they execute the routine, with a shudder of anticipation, their sprite is spread all over the screen. At this point some give up (or decide to write adventure games instead) baffled by the Spectrum’s idiosyncrasies.

Let me say now that when you do grasp the screen layout and the techniques used for addressing it, I think you will be glad that the designers done it that way.

Type in the following and run it:

```	10 FOR S = 16384 TO 22527
20 POKE S, 255
30 NEXT S```

This short BASIC program fills the screen. Although it is moving through memory sequentially, POKING 255 into each memory location, the screen fills up in a rather more esoteric manner. Run the program a few times and watch the pattern it traces. You’ll notice two things: One is the way it skips lines, another is that the screen is divided into three parts.

I said earlier that each line is stored as 32 bytes, with the first line beginning at 16384. Where does the second line start? Most of us assume it would start at 16384+32. In fact it starts at 16384+256 and 16384+32 takes us down to line 8. Remember that the screen is used to display text (characters) as well as graphics. So adding 32 actually takes us down one character row (8 screen lines).

In machine code 16bit addresses, such as 16384, are stored in high byte / low byte format. The high byte is equal to ADDRESS / 256 and the low byte is the remainder from the division, so 16384 in high/low byte format would be 64, 0 (16384 / 256 = 64 with no remainder). This means that when we increase the high byte of a 16 bit address by one, it is equivalent to adding 256. So when it comes to screen addressing all we need to do to move down a line is increase the high byte of the address. This can be done quite easily and quickly in machine code:

```	ld hl,16384	;load the hl register pair with the address of the start of the display file
inc h		;increment the high byte (4 tstates)```

This is in fact much quicker than adding 32 where we would have to do the following:

```	ld hl,16384
ld a,l		;load the accumulator with the l register as we cannot add
;directly to the l register
ld l,a		;load the result back into the l register (total time 15 tstates)```

The above works within a group of 8 lines, ie. 1 char line.

Now, as mentioned before, the other peculiar thing about the screen layout is that it is divided in to three parts – top, middle and bottom. Each third of the screen has 64 lines (or 8 character rows) and takes up 2048 bytes of memory. All that has been said so far applies only so long as we don’t cross from one third into another.

The whole matter becomes at good deal clearer if we look at the screen address in binary.

```           High Byte                |               Low Byte

0   1   0   T   T   L   L   L          Cr Cr Cr Cc Cc Cc Cc Cc```

I have used some abbreviations to make things a bit clearer:

T – these two bits refer to which third of the screen is being addressed: 00 – Top, 01 – Middle, 10 – Bottom

L – these three bits indicate which line is being addressed: from 0 – 7, or 000 – 111 in binary

Cr – these three bits indicate which character row is being addressed: from 0 – 7

Cc – these five bits refer to which character column is being addressed: from 0 – 31

The top three bits ( 010 ) of the high byte don’t change.

The first task in putting a sprite on the screen is to translate the X,Y coords into a screen address.
There are two ways of doing this. One is to set up a look-up table which contains 192 addresses corresponding to each screen line. The other way is a bit more interesting and involves distilling the appropriate line, column and row bits that make up the address from the X and Y coords. Lets examine this way first.

Taking the Y coord first: This will be in the range 0 – 191, with 0 corresponding to the top of the screen. The lowest three bits indicate which line (within a character row) 0 – 7 we are dealing with. This is the same as the high byte of the screen address. The top two bits refer to which third of the screen we are dealing with:

```			   Y Coord

T   T   -   -   -   L   L   L```

Let us assume that the B & C registers contain our X & Y coords. First we need to isolate the lowest three bits of the Y coord (C reg.), as follows:

```	ld a,c
and %00000111		;% indicates that the number following it is in binary format```

We will use the HL register pair for the screen address. So next we transfer these three bits to the high byte (H reg.)

`	ld h,a`

In order to get the top two bits into the correct position we must shift them right three times, as follows:

```	ld a,c
rra			;rotate right accumulator
rra
rra```

This shifts all the bits to the right three times, with the highest bit being reset after each shift. All that’s left to do at this stage is to clear the bits we don’t need, as follows:

`	and %00011000`

This must now be ORd with the H register.

`	or h`

Then the top three bits, which remain constant, are set as appropriate:

```	or %01000000
ld h,a			;load the result back into the H reg.```

So now we have the high byte of the screen address.

The low byte of the address is composed of the following bits of both the X and Y coords:

```   	  	 X Coord              |               Y Coord

Cc Cc Cc Cc Cc   -   -   -         -   -   Cr Cr Cr   -   -   -

Low Byte

Cr Cr Cr Cc Cc Cc Cc Cc```

The character column bits need to be shifted to the right three times.

```	ld a,b			;B reg. holds the X coord
rra
rra
rra
and %00011111		; ensure the top 3 bits are clear
ld l,a```

Then the character row bits must be shifted left twice so that they correspond to the highest three bits of the low byte of the address (see earlier).

```	ld a,c			;C reg. holds the Y coord
rla			;rotate left accumulator
rla
and %11100000		;isolate the character row bits
or l			;OR the result with the low byte
ld l,a			;and place in L register```

Right, that’s the difficult part done. We now have the screen address in HL. All that is left is to get the pixel position (0 – 7 from left to right) from the X coord (lowest three bits).

```	ld a,b
and %00000111```

So the complete routine is as follows:

```On Entry: B reg = X coord,  C reg = Y coord
On Exit: HL = screen address, A = pixel position

; Calculate the high byte of the screen addressand store in H reg.

ld a,c
and %00000111
ld h,a
ld a,c
rra
rra
rra
and %00011000
or h
or %01000000
ld h,a

; Calculate the low byte of the screen address and store in L reg.

ld a,b
rra
rra
rra
and %00011111
ld l,a
ld a,c
rla
rla
and %11100000
or l
ld l,a

; Calculate pixel postion and store in A reg.

ld a,b
and %00000111```

Using a Look-up Table

The other method of calculating the screen address is to use a table of pre-calculated addresses, and then use the Y coord to pick out the right one. This is a good deal quicker than the above method, albeit at the cost of 384 bytes of memory for the table. The look-up table contains the address of each line in the display file, 192 lines.

Routine to generate a Screen Address Table:

```scradtab	equ 64000

gentab		ld de,16384
ld b,192

lineloop	ld (hl),e
inc l
ld (hl),d
inc hl

inc d
ld a,d
and 7
jr nz,nextline
ld a,e
ld e,a
jr c,nextline
ld a,d
sub 8
ld d,a

nextline	djnz lineloop

ret```

Assuming again that on entry the B and C registers contain our X & Y coords.

```	ld de,scradtab		;address of look-up table
ld l,c			;Y coord in L register
ld h,0
;appropriate point in the table
ld a,(hl)		;get low byte of screen address; store in A temporarily
;so as not to corrupt HL
inc l
ld h,(hl)		;get high byte
ld l,a			;HL now contains the address of the start of the line

ld a,b			;calculate character column 0 - 31 from X coord
and %11111000		;isolate appropriate bits
rrca			;rotate right circular accumulator (faster than srl a)
rrca
rrca			;shifting three times is the same as dividing by eight
ld l,a			;put result back in L reg.```

On exit HL will contain the screen address.

An even quicker way is to arrange the lookup table so that it is aligned with a 256 byte page boundary. This method separates the low byte and the high byte of the screen addresses, so in effect there are two tables one containing the low bytes of the address of each screen line and one containing the high bytes. Each must be aligned with a page boundary, ie. the start address of the table must be cleanly divisible by 256.

The above routine for generating the screen address table needs the following changes made to it:

```lineloop	ld (hl),e
inc h
ld (hl),d
dec h
inc l```

The table would be filled as follows:

```	64000 - 64191		0....... 32....... 64....... 96....... 128.......		Low bytes of screen addresses

64256 - 64447		64,65,66....71, 64,65,66....71, 64,65,66....71....	High bytes of screen addresses```

Finding the start address of a particular line is then done as follows:

```	ld h,scradtab/256	; high byte of start of table
ld l,c			; C reg. contains the Y coord
ld a,(hl)		; already we have found the low byte, so store in A temporarily
inc h			; increasing high byte moves forward 256 bytes, and to the
ld h,(hl)		; corresponding high byte of the screen address
ld l,a			; HL now contains the screen address for the start of the line```

All that is then needed is to add on the column position, which is calculated in the same way as the previous routine.

Basic considerations

The main factors which need consideration when writing a sprite routine are:

1. Whether or not to use masked sprites
2. Whether or not to use pre-shifted sprites
3. What sizes of sprite to use and whether to use a different routine tailored for each size or a generic
routine which will produce various sizes of sprite

Writing a generic sprite routine which can handle many sizes and types of sprite, is generally shunned by most programmers, because the complexity of the routine has a negative impact on performance. It is perferable to write several routines tailored to specific sizes of sprite.

As per usual there is a trade-off between memory and speed, with the fastest routines using the most memory.

Masked sprites on average will take about 30% more time to process.

Pre-shifted sprites, which are sprites stored in 2, 4 or 8 different pixel positions, are by far the fastest type, but consume lots of memory.

An alternative to using pre-shifted sprites favored by some programmers, is to have a look-up table containing each bit pattern from 0 – 255 shifted into eight positions. In practice this takes up 4K of memory but this is usually less than is required when pre-shifting a large number of sprites. More about this later.

A Worked Example

It’s now time to take a look at how to code a basic sprite routine. The example below is for an 8 x 8 non-masked sprite. The sprite data (a small arrow pointer) is located at USR “A” – 65368. The routine shifts the data in real time. The sprite is XORed with the contents of the screen. You could also OR the sprite with the screen contents (see below for explanation of OR, XOR etc.) Real time rotation of sprite data is easiest acheived with small sprites (16 pixels or less wide), as the data can be stored in registers while being rotated.

The steps in the algorithm to draw the sprite could be stated as follows:

1. Retrieve X and Y coords.
2. Calculate Screen Address based on X,Y coords, using a look-up table
3. Calculate Bit Position from X coord (X coord AND 7 = bit position)
4. Retrieve a line of the sprite graphics data
5. Check if Bit Position is zero
6. If so there is no need to shift the sprite data, so skip the code which shifts the data (jump to step 8 )
7. Shift the sprite data according to its bit position
8. Put the line of sprite data on the screen
10. Perform steps 4-9 until all lines have been drawn

```		ORG 50000

SPRITE	DI			;Disable Interupts. Not strictly necessary in this
;example as we are not redirecting the Stack.

LD BC,(XPOS)		; First off, get the X & Y coords
; and place them in B & C registers

LD H,SCRADTAB/256	; this next section calculates the
LD L,B			; screen address using a lookup table
LD A,(HL)		; as explained earlier in the tutorial
INC H
LD H,(HL)
LD L,A
LD A,C
AND 248
RRCA
RRCA
RRCA
LD L,A
; as HL is needed again

LD A,C			; find which pixel position the sprite
AND 7			; will be at and store it. We need this to
LD (BITPOS),A		; know how many times to shift the sprite data

LD HL,SPRGFX	; start address for the sprite graphic

LD C,8			; The sprite is 8 lines tall

LINELOOP	LD E,(HL)		; load the E reg with the first line of
INC L			; sprite data, and move forward

PUSH HL		; preserve this address for later

LD A,(BITPOS)		; Retrieve the pixel position
OR A			; Quick way of testing if A is zero - Note: A is unaffected
JR Z,SKIPROTATE	; If zero then no shifting is needed

LD B,A			; loop counter for number of times to
; rotate (shift) sprite data
XOR A			; Quick way setting A to zero and
; clearing the Carry Flag. The Carry Flag must be reset
; as the rotate instructions will shift its contents
; into the sprite data.

ROTATELOOP	RR E			; An extra register is needed for the
RRA			; shifted sprite data. After the RR E is executed
; rightmost bit of sprite data is shifted out to the Carry Flag.
; It is then shifted into the A reg by RRA. So no data is lost.
DJNZ ROTATELOOP	; Loop back until shifting is complete

SKIPROTATE	LD D,A			; Store in D register, as A will be
; needed for another purpose. E & D regs now contain the
; shifted sprite data.

LD A,(HL)		; Actually put a line of the sprite on the screen
XOR E
LD (HL),A
INC L
LD A,(HL)
XOR D
LD (HL),A

DEC L			; move back and down one line
INC H

LD A,H			; It is not necessary to recalculate
AND 7			; the screen address for each line of
JR NZ,A1		; the sprite. All that is needed is to
LD A,L			; check if a char. or segment boundary
LD L,A			; accordingly.
JR C,A1
LD A,H
SUB 8
LD H,A

A1		LD (SCRADD),HL	; store it again

POP HL		; retrieve the address of the next line
; of sprite data
DEC C
JP NZ,LINELOOP	; loop back until all lines are drawn.

EI			; Enable Interupts again
RET

XPOS		DEFB 0
YPOS		DEFB 0
BITPOS	DEFB 0

On Exit : A, BC, DE, HL corrupt

As can be seen from the above routine it is not necessary to re-calculate the screen address for every line of a sprite. A couple of checks can be made to test if the next line to be drawn is in a new character row or screen third and adjust the address accordingly:

```	LD A,H				;HL contains screen address
AND 7
JR NZ, REST_OF_PROGRAM
LD A,L
LD L,A
JR C, REST_OF PROGRAM
LD A,H
SUB 8
LD H,A

Rest Of Program continues here...```

Routine to generate a table of screen addresses

```GENTAB	LD DE,16384
LD B,192

LINELOOP	LD (HL),E
INC H
LD (HL),D
DEC H
INC L

INC D
LD A,D
AND 7
JR NZ,NEXTLINE
LD A,E
LD E,A
JR C,NEXTLINE
LD A,D
SUB 8
LD D,A

NEXTLINE	DJNZ LINELOOP

RET```

Sprite Graphics Data

```		ORG 65368

SPRGFX	DEFB %00000000
DEFB %01111000
DEFB %01110000
DEFB %01111000
DEFB %01011100
DEFB %00001110
DEFB %00000100
DEFB %00000000```

OR, XOR, AND

```00111100  OR 	00011000  = 00111100

00111100  XOR	00011000  = 00100100

00111100  AND	00011000  = 00011000```

Masking is a technique used to blank out the area behind a sprite before drawing the sprite to the display. It’s slower than planar (non-masked) sprites, and uses twice as much memory but the final result is more pleasing to the eye. If your sprites are going to be moving over a patterned background its the best technique to use.

The way to draw a masked sprite is to AND the mask with background and then OR the actual sprite with the result. When you AND two bitmaps, bits in the BACKGROUND are reset by zeros in the MASK, and left as they are by ones. That’s probably not very easy to grasp so look at the following examples:

```background	            mask

00111100     and      11111111 	=  00111100	; each bit in the data byte remains  the same after the mask is applied

00111100     and      00000000 	=  00000000	; all the bits in the data byte are reset by the mask

11111111     and      00111100 	=  00111100	; the middle four bits remain unchanged and the rest are reset```

The previous example showed how to code a very simple sprite routine. Lets now look at a more complex example. This routine will draw a 16 x 16 Masked Sprite, storing the background underneath in a buffer.

This is probably the largest size that can be conveniently shifted in real-time. Any larger and you will want to use a different technique.

The following routine uses a couple of non-standard programming techniques. These tricks help to speed up execution but make the code a bit more difficult to follow. One technique involves using the Stack to retrieve the sprite data, the other is self-modifying code, where the program pokes values into instructions that will be executed later on in the routine.

```		ORG 50000,50000

SPRITE	DI				; Disable Interupts.
LD (SPTEMP),SP		; Store Stack Pointer as it will be redirected
; by the routine
LD BC,(XPOS)
LD A,C
AND 7
LD (BITPOS),A

LD L,B
LD A,(HL)
INC H
LD H,(HL)
LD L,A
LD A,C
AND 248
RRCA
RRCA
RRCA
LD L,A

LD IX,BKGRNDBUF		; IX is used to point to a temporary buffer where the contents
; of the screen under the sprite are stored.

LD SP,SPRGFX		; start address for the sprite graphic

LD A,16			; The sprite is 16 lines tall
LD (LINECOUNT),A

LINELOOP	POP DE			; Using the stack to retrieve a line of sprite graphics
POP HL			; E and D will contain the MASK as it is stored first
; L and H hold the actual sprite image
LD A,255			; When shifting, the A reg will be the extra register that the MASK
; is shifted into. It is loaded with 255 as that means all the bits are
; initially transparent.
SCF				; The carry flag is set by this instruction so that bits shifted into the
; left side of the mask are set (transparent)
EX AF,AF'			; We also need an extra register for the sprite image, so we will use
; the alternate or shadow A register.

LD A,(BITPOS)			; Retrieve the pixel position
OR A				; Quick way of testing if A is zero
JR Z,SKIPROTATE		; If zero then no shifting is needed

LD B,A				; loop counter for number of times to shift

XOR A				; clear carry flag and set A reg. to zero,
; as the rotate instructions will shift its contents (carry flag's)
; into the sprite image data. This is the opposite to the MASK.

ROTATELOOP	EX AF,AF'			; Shift the Sprite Mask data
RR E
RR D
RRA

EX AF,AF'			; Shift the Sprite Image data
RR L
RR H
RRA

DJNZ ROTATELOOP		; Loop back until shifting is complete

SKIPROTATE	LD (DATA+1),A			; This is the piece of self-modifying code mentioned earlier.
EX AF,AF'			; As the A reg will be needed and there are no other registers
LD (MASK+1),A			; free, we will poke their data (the rightmost bytes of the sprite mask
; and image) into instructions further on in the routine.

LD A,(BC)			; Actually put a line of sprite data on the screen
LD (IX),A			; Store what is under the sprite so that it can be erased
; without corrupting the background
AND E				; This instruction applies the MASK
OR L				; The sprite image is then ORed with the background
LD (BC),A			; and the result copied back to the screen
INC C
INC IXL

LD A,(BC)			; Put the second byte on the screen
LD (IX),A			; As we are dealing with a 16 x 16 sprite
AND D				; each line will be three bytes wide when shifted
OR H
LD (BC),A
INC C
INC IXL

LD A,(BC)			; Put the third byte on the screen
LD (IX),A
MASK		AND 255			; These are the two instructions that were modified
DATA		OR 0				; earlier. The data stored in the A reg. and its shadow
; were poked into the AND & OR instructions.
LD (BC),A
INC IXL

DEC C
DEC C				; move back and down one line
INC B

LD A,B				; It is not necessary to recalculate
AND 7				; the screen address for each line of
JR NZ,A1			; the sprite. All that is needed is to
LD A,C				; check if a char. or segment (screen third) boundary
LD C,A				; accordingly.
JR C,A1
LD A,B
SUB 8
LD B,A

A1		LD (SCRADD),BC		; store it again

LD HL,LINECOUNT
DEC (HL)
JP NZ,LINELOOP		; loop back until all lines are drawn.

LD SP,(SPTEMP)		; Restore the Stack Pointer
EI				; Enable Interupts again
RET```

In order to clear the sprite we need to copy back to the screen the Buffer holding the contents
of the screen under the sprite. The following routine will do this.

```CLEARSPRITE	DI

LD BC,(OLDXPOS)

LD L,B
LD A,(HL)
INC H
LD H,(HL)
LD L,A
LD A,C
AND 248
RRCA
RRCA
RRCA
LD L,A

LD DE, BKGRNDBUF

LD C,16

CLOOP		LD A,(DE)
LD (HL),A
INC L
INC E

LD A,(DE)
LD (HL),A
INC L
INC E

LD A,(DE)
LD (HL),A
INC E

DEC L
DEC L
INC H

LD A,H
AND 7
JR NZ,A2
LD A,L
LD L,A
JR C,A2
LD A,H
SUB 8
LD H,A

A2		DEC C
JP NZ,CLOOP

EI
RET

XPOS		DEFB 0
YPOS		DEFB 0
OLDXPOS	DEFB 0
OLDYPOS	DEFB 0
LINECOUNT	DEFB 0
BITPOS	DEFB 0
SPTEMP	DEFW 0

BKGRNDBUF	EQU 64512```
```; ASM source file created by SevenuP v1.12
; SevenuP (C) Copyright 2002-2004 by Jaime Tejedor G¢mez, aka Metalbrain

;GRAPHIC DATA:
;Pixel Size:      ( 16,  16)
;Char Size:       (  2,   2)
;Sort Priorities: X char, Char line, Y char, Mask
;Attributes:      No attributes

SPRGFX	DEFB	248, 31,  0,  0
DEFB	224,  7,  3,192
DEFB	192,  3, 15,240
DEFB	128,  1, 25,248
DEFB	128,  1, 51,252
DEFB	  0,  0, 39,252
DEFB	  0,  0,111,250
DEFB	  0,  0,127,252

DEFB	  0,  0,127,250
DEFB	  0,  0,127,252
DEFB	  0,  0, 63,248
DEFB	128,  1, 63,244
DEFB	128,  1, 31,232
DEFB	192,  3, 13, 80
DEFB	224,  7,  2,128
DEFB	248, 31,  0,  0```

Addendum: There appears to be a minor bug in the original code by Derek Smith. Commentator uglifruit posted a fix in the comments section, which has now been integrated into the above code.

Categories: Z80 Assembly Tags: , ,

## Introduction to Z88DK – Part 1: Installation & Compilation

This article was originally published on http://www.speccy.org/wiki, in Spanish, and is reproduced with permission from Santiago Romero. Translation to English courtesy Google and some re-write from my end. Please do let me know of any errors in the text.

In this series of articles we’ll take a look at Z88DK and learn to make programs with it for our Spectrum.

Basically it is a C cross compiler, which allows us to make our programs in this language on our desktop computer (PC running Windows or Linux, SPARC) and create a file that can be run in an emulator. Using the right tools it can be moved to tape to run on our Spectrum. While these articles will focus on the target machine of this publication (the Sinclair ZX Spectrum), the z88dk allows develop applications for a wide range of platforms including Sam Coupe, MSX1, Jupiter ACE, ZX81, and a large number of computers based on the Z80 processor.

The package includes a set of libraries that allow us to easily add functionality to the programs, including a versatile graphics library, which will enable us to even write a game. The C compiler included with z88dk is only a small compiler accepts many features of ANSI C and perform basic optimizations. Finally, we clarify that the purpose of these articles is not to explain the syntax or the operation of the C language and, the reader is assumed to have a basic knowledge about it.

In this issue we focus on how to install the package for different platforms, as well as learn how to compile and run the examples.

## Installation

To download the latest stable version we will go to the download page of z88dk, where we can get the Linux version. Binaries for Windows can be obtained from Dennis Grönign’s page (the link can also be found on the same page z88dk).

Installing on Linux

The first step after downloading the file z88dk-src-xytar.gz (where xy is the version of the package at the time of writing – the latest stable version was 1.5), is unpacking in the directory where you want to have it installed:

`tar-xvzf z88dk-src-xytar.gz`

Once this is done we must compile the various binaries and libraries that make z88dk:

```cd z88dk
. / build.sh```

To use z88dk we should declare a number of environment variables. We can do this by creating a file setpath.sh (which we will execute permissions with chmod a + x setpath.sh) with the following contents:

```Export Z88DK = "(z88dk) / z88dk"
Export PATH = "\$ PATH: \$ Z88DK/bin"
Export Z80_OZFILES = "\$ Z88DK/lib /"
Export ZCCCFG = "\$ Z88DK/lib/config /"```

where (z88dk) is the directory where you have unpacked the tar.gz. Every time we use z88dk, must execute this file by using the following command:

`setpath.sh source`

With this we define the environment variables for the current shell.

One tool that we use in creating our programs is bin2tap. This program transforms the binary produced by the compiler to TAP files that can be run in an emulator. Fortunately, this program comes bundled with z88dk. Unfortunately, this is included without compiling, and also not compiled to run the. / Build.sh previously indicated.

To build it, we move to the \$ Z88DK/support/zx /, and execute:

`cc-o bin2tap bin2tap.c`

That way we will create the executable program. To use it comfortably, we copy the bin directory:

`mv \$ Z88DK/support/zx/bin2tap \$ Z88DK/bin /`

Compiling and Running on Linux

Once the package is installed, and prepared our system, we explain how we can compile our programs and run them on any emulator. We shall do this in the examples located in the \$ Z88DK/examples/spectrum.

In the above directory are a number of files containing C programs that use z88dk librarie. In the README file have a description for each one of them. Let’s compile and test the gfx.c, which incorporates a series of graphic effects that look spectacular. To do so, according to the README file, we can run:

`CCZ + zx-or gfx.bin gfx.c-lndos`

Below is a brief description of the syntax:
• Just after the ZCC command specify the target machine, ie the machine which will produce the binary. In our case we want to create a binary for the ZX Spectrum, so we use the modifier + zx (the switches for each of the machines supported can be found at \$ Z88DK/doc/compile.txt).

• With the-o parameter specified the resulting binary file name (in our case, gfx.bin).

• Then name the source file.

• Finally, we con-lndos to bind to the bookstore NDOS (in next installments we go into detail about the most useful libraries and functionalities offered). The libraries are in \$ Z88DK/libsrc /.

As you can see, the syntax is very similar to Linux gcc compiler, so if we are used to programming in C on this platform, we should not have any problem. The resulting file, gfx.bin, is a binary file (which a text editor can’t understand). Keep in mind that CCZ is not the compiler itself, but it is a frontend that is responsible for implementing the compiler and assembler / linker (all these applications can be found in the \$ Z88DK/bin /).

This binary may not yet be executed in any emulator, we must first convert it to a suitable format. To do this we can use the application bin2tap, we compiled in the previous paragraph:

`bin2tap gfx.bin gfx.tap`

And now we can test the program in our favorite emulator!

Installation on Windows (thanks to the collaboration of Miguel)

This installation has been completed and tested on a PC with Windows 98 Second Edition. Attempt on a Windows XP system files and executables in the bin directory gave the error “xxxxxxx.exe is not a valid win32 file” (This may be due more to the PC on which the author has installed the operating system incompatibility problems between himself and z88dk Windows XP).
The first step we must carry out is to download the file z88dk-win32-xyzip (where xy indicates the version of z88dk) we can find on the project website. Once downloaded, unzip the zip file in the directory c: \ z88dk, which will be the default directory that we use in this article. We can switch to one that suits us more by changing the path in all explanations given below.

The following adds the path of the executables and libraries to the autoexec.bat file. For this we have two options:

• 1. Add the path manually by editing the autoexec.bat file. To do this simply edit the autoexec.bat file located in c: / with the Windows Notepad, or from a MS-DOS “edit autoexec.bat” and add the following lines:

```SET Z80_OZFILES = C: \ z88dk \ Lib \
SET ZCCCFG = C: \ z88dk \ Lib \ Config \
SET PATH =% PATH% C: \ z88dk \ Bin
```

• 2. When you uncompress the zip files containing z88dk, there is a file called SETZ88-W95.inf, we place the mouse pointer over it, right-click and select install, which automatically adds the file path autoexec.bat.
After one of the above, reboot the PC to update the paths.
Compile and run on Windows

When writing code with the z88dk, the code is written in C language in plain text files with your preferred editor (can be even Windows Notepad). These files are usually saved with a .c extension.
To show briefly how we create a file to run on a ZX Spectrum emulator, or upload to a real computer, we’ll use one of the examples that come with z88dk.

• The first thing we do is open a MS-DOS command window and move to the folder where the examples are present:
To put ourselves in the root directory of C:

```CD c:\
CD z88dk \ examples \ spectrum
```

With that we are in the examples folder.
Now we have to compile the program. To do this we will use the executable ZCC.EXE, which is located in the BIN folder, but we do not have to enter it at all, because we added its path earlier. Compile by typing:

```CCZ + zx-or gfx.bin gfx.c-lndos
```

When you run it, it creates a file.bin in which we will have our program. We need to convert it to a format that the emulator can understand, or move to tape and load on a real ZX Spectrum.

• To convert the file from .bin to .tap, we have a program called BIN2TAP.EXE that is included in z88dk and located in the \ support \ zx folder.

Usage is very simple: we have to be in the same folder as the. BIN2TAP.exe and provide it the .bin source and specify the target .tap. Execute:

```BIN2TAP gfx.bin gfx.tap
```

And now we have our program ready to load into our favorite emulator.

Categories: Z88DK Tags: , , , , ,

## Tutorial: ZX Spectrum Machine Code Game in 30 Minutes!

This tutorial by Jon Kingsman (bigjon) originally appeared in a thread on WoSF. Reproduced with permission.

Roadrace game by bigjon, incorporating suggestions from Dr Beep, skoolkid and Matt B

Hi folks, I’m a machine code novice who coded a very small roadrace game to help me learn.

I reckon you can learn the basics of machine code in half an hour by coding this game step by step.

This tutorial assumes you have a working knowledge of ZX Spectrum basic, and the ZX Spin emulator.

Make yourself a large cup of tea – by the time you’ve drunk it, you be able to program in machine code!

CHAPTER 1 – Create a machine code function that returns the score to BASIC
Machine code programs are a series of bytes in the Spectrum’s memory.
In this chapter we will

• – Use the Spin assembler to write a few bytes into the memory generating a score for our game.
• – Write a BASIC program to run the machine code and print the score we have obtained from it.

Open ZX Spin.  Select Tools -> Z80 Assembler.
To run our roadrace game, we need to execute the following steps:

```MAIN 	;label for main section of program as opposed to graphics data etc

;arrange to put our machine code at free, fast-running (over 32768) and memorable address in RAM
org 33000

;initialise score

PRINCIPALLOOP ;label for the loop in the game that will execute over and over
;set new carposition
;crash? if so, go to GAMEOVER.
;print car
;jump back to PRINCIPALLOOP

GAMEOVER ;label for the cleaning up that needs to be done before returning to BASIC
;return score to BASIC```

Copy and paste the paragraph above into the Spin Assembler.It will appear as 15 lines of mainly grey text.

The text is grey because text after a ; is a comment. The assembler ignores it but it’s there for our benefit.

You can TAB comments over towards the right-hand side of the assembler page to make your code more readable.

The labels are in pink.The assembler won’t put anything in RAM for them but will use them as entry points to jump to.

In the assembler, do File -> Save as and type something like mc30mintut.asm into the save box.
We’ll do the first and last of these steps in this chapter, starting with the last one.

The assembly language instruction for ‘return to calling program’ (in our case a BASIC routine) is ‘ret’.

Click on the end of line 15, press enter to create line 16 and type ret
The word ret‘ appears in blue. This is Spin’s colour code for an instruction.

When the Spin assembler gets to the instruction ret it writes the byte 201 into the memory at an address we choose.

The computer knows that the first byte it meets will be an instruction byte.

It does something different for each byte from 0 to 255. There’s a list in Appendix A of the Spectrum Manual.

Some instruction bytes, like 201 for ret, are complete as is – no further info is needed to complete the action.

Some instruction bytes need one or two bytes of data afterwards for the computer to know what to do.

Some other instruction bytes need a further instruction byte to clarify the action required.

Now we’ll initialise the score, ready for the mc program to report it back to BASIC at the end of the game.

The computer does most of its work using 7 temporary byte-sized addresses called registers.

The first register deals with single bytes only (numbers 0 to 255), the other six are in pairs to deal with 0 to 65535.

The first (single-byte) register is called the A register, sometimes also referred to as the accumulator.

The other three register pairs are called BC, DE, and HL (H is for High byte, L is for Low byte)

Any machine code function called from basic will return the value from 0 to 65535 in the BC register.

We will write the value 0 into the BC register, ready to increase it by 1 each time the game goes round its principal loop.

At the beginning of line 4, type ld bc,0. ld is the instruction for load a value into a register or register pair.

The instruction byte for ld is different for each register or register pair that is loaded.

The instruction byte for ld bc is 1. The computer then expects 2 data bytes to give it a number from 0 to 65535.

In our case the two data bytes will be 0,0.  So the assembler will write 1,0,0,201 at address 33000 in RAM.

We’ll assemble this code now. Do File -> Save, then File -> Assemble. Type 33000 into the Start Address box and click OK.

At the bottom window of the assembler you should see a report that says “No errors in 16 lines. 4 bytes generated”.

You can see the four bytes are now at memory address 33000 by clicking in the main Spin display window on Tools -> Debugger.

To run these four bytes of machine code, enter this one-line program in the main Spin display window:
10 PRINT AT 0,0; “Your score was “; USR 33000

Now RUN the program. Did you get “Your score was 0”? Congratulations – you have coded your first machine code program!

Do File -> Save in the main Spin display window and save as something like mc30mintut.sna. Here ends Chapter 1!

CHAPTER 2 – Display material on the screen.
There are two areas of the Spectrum’s memory which have a direct effect on the screen display.
The complicated way is the display file, from addresses 16384 to 22527, which stores a dash of 8 pixels per byte.

Try POKE-ing 255 into bytes within this range to see the funny order in which this memory area is mapped onto the screen.

The simple way is the attribute file, from 22528 to 23296, which affects an 8×8 pixel block per byte, in logical order.

In this chapter we will

• Draw our ‘car’ by changing the paper colour of one character square to blue.
• Draw our ‘road’ by using a loop to create two vertical stripes of black paper colour down the screen.

In the spin assembler line 5, delete the word ‘road’ in the comments.

At the beginning of line 5, type ld hl,23278. This points HL to the middle of the bottom row in the display file.

Insert line 6, ld a,8. This puts a blue PAPER colour into the A register. Why 8? See the BASIC manual chapter 16.

Insert line 7, ld (hl),a. The brackets round hl mean the load will be to the address in RAM that hl is pointing to.

Insert line 8, ld (32900),hl ;save car posn. We’ll store the attribute file address of the ‘car’ in some free bytes in RAM.

Now for the road. Insert line 4, ld hl,22537 ;initialise road. This points to a third of the way along the top line.

To save the road position, which we’ll need frequently, we’ll let the computer choose where to store it, on its ‘stack’.

Chapter 24 of the manual has a diagram showing where the machine stack is in the RAM.
To write to the stack we use push. To write from the stack we use pop. What goes on the stack first will come off last.

Insert line 5, push hl ;save road posn. Insert line 21, pop hl ;empty stack

To print a black road we need 0 in the accumulator (ch16 of the BASIC manual).

We could do ld a, 0 but this takes 2 bytes whereas xor a takes only one. Insert line 6, xor a.
xor compares the chosen register to the A register and puts a 1 in the A register for each bit that is different.

We’ll print the top line of the road. Two double squares of black with a 9-square gap between them.

Insert line 7, then copy and paste the following code:

```	ld (hl),a
inc hl ;inc increases the register by one, dec decreases it by one.
ld (hl),a
ld de,9 ;for a 9-space gap in the road.
ld (hl),a
inc hl
ld (hl),a```

To get hl to point to the left hand verge on the next line, we need to move 21 bytes further in the attribute file.

Insert line 15, ld de, 21 ;point to left verge on next line

To fill the screen with the road we will use machine code’s equivalent of a FOR-NEXT loop, djnz.
djnz stands for Decrement then Jump if Not Zero. We load the b register with the number of times we want to loop.

Insert line 7, ld b,24 ;print road verge on 24 lines.
Insert line 8, fillscreen – this is the label for our loop to jump back to.
Insert line 19, djnz fillscreen.

Because our routine will continue from the loop when b=0, we no longer need to initialise b as well as c to 0 in the next line.

Change line 20 ld bc, 0 to ld c,b.  This is one byte shorter.

Assemble and save. If you want to see the blue ‘car’, you’ll need to add something like 20 PAUSE 0 to your basic program.

CHAPTER 3 – move the car, test for collision.
Time to start playing the game! First we need to erase the car ready to move it if the player wants to.

Insert line 26, then copy and paste the following code:

```	ld hl,(32900) ;retrieve car posn
ld a,56 ;erase car
ld (hl),a```

Before we read the keyboard we will lock the keyboard for most of the game, and unlock it only when we want to read the keys.

The instruction to lock the keyboard is di = ‘disable interrupts. Its opposite is ei = ‘enable interrupts’.

Replace line 3 with di. Insert line 29, ei. Insert line 31, di. Insert line 41, ei

To read the keys we use the IN ports – see ch23 of the BASIC manual – to read the left and right half of the bottom row.

We load bc with the port number and use the instruction cp (compare) to see if the number has dropped to show a keypress.

Delete line30 and replace with the following code:

```	ld bc,65278 ;read keyboard caps to v
in a,(c)
cp 191
jr nz, moveright
inc l
moveright
ld bc,32766 ;read keyboard space to b
in a,(c)
cp 191
jr nz, dontmove
dec l
dontmove```

jr nz stands for jump relative if not zero. It skips over the instruction to increment / decrement the car position.

Replace line 43 with the following to see if we bump into the oncoming road 32 bytes (1 screen) down the attribute file:

```	ld (32900),hl ;store car posn
ld de, 32 ;new carposn
xor a  ;set carry flag to 0
sbc hl,de
ld a,(hl) ;crash?
or a
jr z,gameover
ld a,8  ;print car
ld (hl),a```

We’d like to sub hl,de but there’s no such instruction so we use sbc, subtract with carry, and set the carry flag to zero.

or compares the register to the a register bit by bit and leaves a 1 in the a register for each bit that is 1 in either.

If all the digits are zero, then the zero flag will be set, so we can use or a to test for a black paper colour.

Delete line 53. Delete line 53 again!

To clean up the score at GAMEOVER insert line21, push bc; save score. Replace line 57 with pop bc;retrieve score

To cycle round the game before GAMEOVER change line 55 to jp PRINCIPALLOOP.

Assemble, save, and run. You’ll need to deliberately crash to get out!

CHAPTER 4 – scroll and move the road, keep score, adjust speed.
To scroll the road down the screen we copy the screen attribute bytes to the line beneath 736 times.

We use the instruction lddr, which stand for LoaD ((hl) to (de)),Decrement (hl and de) and Repeat (until bc is zero).

Replace line 53 with the following:

```	ld hl,23263 ;scroll road
ld de,23295
ld bc,736
lddr
pop bc  ;retrieve score```

To add 1 to the score and save it ready for GAMEOVER, insert the following into line 59:

inc bc ;add 1 to score
push bc ;save score

To move the road randomly left or right on the top line we use the following algorithm –
Choose a location in ROM where the are 256 random looking bytes and add the low byte of the score in bc to it.

If it is odd, lower the road position in hl by one. If it is even, increase by one.

(To test the last bit for odd and even we use ‘and 1’ which “masks” the last bit and sets the zero flag if it is 0).

Check to see if the road has reached the edge of the screen and bump it away if it has.
Print the new road top line like we did in chapter 2.

Replace line 58 with the following hefty chunk of code:

```	pop hl  ;retrieve road posn
ld (hl),a
inc hl
ld (hl),a
ld de,9
ld (hl),a
inc hl
ld (hl),a
ld hl,14000 ;source of random bytes in ROM
ld d,0
ld e,c
ld a,(hl)
dec hl  ;move road posn 1 left
and 1
inc hl
inc hl
ld a,l  ;check left
cp 255
jr nz, checkright
inc hl
inc hl
checkright
ld a,l
cp 21
dec hl
dec hl
ld (hl),a
inc hl
ld (hl),a
ld de,9
ld (hl),a
inc hl
ld (hl),a```

The last thing we need to do to have a playable game is slow down our blindingly fast machine code.

Insert the following into line 106 (as extension material, you could adjust the figure in bc with a keypress to ‘brake’):

```;wait routine
ld bc,\$1fff ;max waiting time
wait
dec bc
ld a,b
or c
jr nz, wait```

Save, assemble, and run – and that’s it! Has your tea gone cold yet?

```main
org 33000
di
xor a
ld b,24
fillscreen
ld (hl),a
inc hl
ld (hl),a
ld de,9
ld (hl),a
inc hl
ld (hl),a
ld de,21
djnz fillscreen
ld c,b  ;initialise score
push bc  ;save score
ld hl,23278 ;initialise car
ld a,8
ld (hl),a
ld (32900),hl ;save car posn
principalloop
ld hl,(32900) ;retrieve car posn
ld a,56  ;erase car
ld (hl),a
ei
ld bc,65278 ;read keyboard caps to v
in a,(c)
cp 191
jr nz, moveright
inc l
moveright
ld bc,32766 ;read keyboard space to b
in a,(c)
cp 191
jr nz, dontmove
dec l
dontmove
di
ld (32900),hl ;store car posn
ld de, 32 ;new carposn
xor a  ;set carry flag to 0
sbc hl,de
ld a,(hl) ;crash?
or a
jr z,gameover
ld a,8  ;print car
ld (hl),a
ld de,23295
ld bc,736
lddr
pop bc  ;retrieve score
ld (hl),a
inc hl
ld (hl),a
ld de,9
ld (hl),a
inc hl
ld (hl),a
ld hl,14000 ;source of random bytes in ROM
ld d,0
ld e,c
ld a,(hl)
dec hl  ;move road posn 1 left
and 1
inc hl
inc hl
ld a,l  ;check left
cp 255
jr nz, checkright
inc hl
inc hl
checkright
ld a,l
cp 21
dec hl
dec hl
ld (hl),a
inc hl
ld (hl),a
ld de,9
ld (hl),a
inc hl
ld (hl),a
inc bc  ;add 1 to score
push bc  ;save score
;wait routine
ld bc,\$1fff ;max waiting time
wait
dec bc
ld a,b
or c
jr nz, wait
jp principalloop
gameover
pop bc  ;retrieve score
pop hl  ;empty stack
ei
ret; game and tutorial written by Jon Kingsman ('bigjon', 'bj'). electronic mail gmail.com - atsign - jon.kingsman (reversed)```
Categories: Z80 Assembly Tags: , ,