ZalaXa 4 — First Glimpse of Multicolour

Well here we are! If you pull the latest commits from GitHub. you should see the code for part 4 of the tutorial.

If you Assemble And Run \tutorials\part4\src\main.asm in Zeus, you’ll see the familiar menu we wrote in part 3. This time, if you press space, hopefully you’ll see some multicolour animation!

Let’s try and have a look at what I added. First of all, you will notice there are now eight source files, in which I’ve reorganised the previous code, and added some new code:

Many assemblers allow this, and it does help to organise your code. In Zeus, it’s done with the include directive:

25
26
27
28
29
30
31
32
33
; main.asm
 
include                 "menu.asm"
include                 "sprites.asm"
include                 "utilities.asm"
include                 "database.asm"
include                 "constants.asm"
include                 "macros.asm"
include                 "nirvana+.asm"

The last file (which is last deliberately, and I’ll explain why later) is Einar’s source code for NIRVANA+, taken directly from his Dropbox drive. We won’t look at this in detail for now—suffice it to say it has an NIRVANA+ API, and we can call routines to do magic multicolour things.

The /tiles/nirvana+.btile file also comes from Einar’s Dropbox. This file contains 16×16 pixel multicolour tiles, in a special 8×2 attribute format tailored for NIRVANA.

ZX-Paintbrush is a graphical editing tool we will find indispensible for working with btiles. Download it from Klaus Jahn’s website here (by clicking on the image).

If you open the file in ZX-Paintbrush, you can see it contains the 17 sprites from part 1 (by Dave “R-Tape” Hughes):

A slightly closer examination reveals the important detail—each 8×2 pixel block can have exactly one background and foreground colour (and its own brightness and flash value), enabling the multicolour magic!

All I’m doing here is cycling between the first two btiles in this set, to do some simple but effective animation. First we clear the standard 8×8 attributes (for a fast clean CLS), then we set the index and coordinates of NIRVANA+ sprite A (there are eight of them) to the first btile in the top left hand corner, then we enable NIRVANA+:

17
18
19
20
21
22
23
24
25
26
27
; menu.asm
 
SetupGame               proc
                        call ClsAttr                    ; Clear the 8x2 attributes for a fast CLS before setup
                        ld a, BTile.NirvanaDemo         ; BTile.NirvanaDemo is 0 - the index of the first tile in the set
                        ld (Sprites.AIndex), a          ; Set NIRVANA+ sprite A to this sprite index
                        ld hl, $1000                    ; LSB is $00 (the column), MSB is $10 (the line, decimal 16)
                        ld (Sprites.AColumn), hl        ; Set NIRVANA+ sprite A coords to 0, 16
                        call NIRVANA_start              ; Enable NIRVANA+
                        ret
pend

NIRVANA+ horizontal coordinates range from 0 to 31—standard Spectrum character columns. Vertical coordinates range from 0 to 215. NIRVANA+ never draws anything multicolour on the first character row. It also allows you to draw a tile completely off the top or bottom of the screen, so the visible range is actually between 16 and 199. Don’t worry too much about this for now, just take note that pixel line 16 is the top of the visible NIRVANA+ screen.

Our main loop now has a call to AnimateDemo, 50 times a second:

17
18
19
20
21
22
23
; main.asm
 
Loop:
                        halt                            ; Wait until the next 50th second frame
                        call AnimateDemo                ; Animate our monster
                        jp Loop                         ; Go into an endless loop (for now...)
pend

The AnimateDemo routine reads the lowest byte of the Spectrum ROM’s frame counter, which is increment every 50th of a second by NIRVANA’s interrupt handler—when it goes above 255 it wraps back round to zero. It turns that into a number between 0 and 7 with a fancy bitwise modulus calculation using the and opcode. There are 32 lots of 8 in the 256 possible values of a byte, so this is a clever fast way of counting in eights (well, between 0 and 7).

So, for 7 out of every 8 frames, it returns without doing anything.

3
4
5
6
7
8
9
10
11
12
13
14
15
; sprites.asm
 
AnimateDemo             proc
 
                        ld a, (FRAMES)                  ; Read the LSB of the ROM frame counter (0.255)
                        and %00000111                   ; Take the lowest 3 bits (effectively FRAMES modulus 8),
                        ret nz                          ;   and return 7 out of every 8 frames.
 
                        ld a, (Sprites.AIndex)          ; For every 8th frame, read Sprite A's tile index,
                        xor %00000001                   ;   alternate between (0 => 1 => 0 => 1=> etc),
                        ld (Sprites.AIndex), a          ;   then save it back.
                        ret
pend

But for one frame in every eight, it flips the btile index of sprite A between 0 and 1 using a bitwise xor operation. In other words we do a two-frame animation, alternating every 0.16 of a second!

We won’t keep any of this code in the final game, but it neatly demonstrates two things:

  • we don’t need to do anything too fancy to set up NIRVANA+, and
  • a little animation really helps bring graphics to life.

More next time!

ZalaXa 3 — A Simple Start Menu

I bet everyone is eager to dive right in and start with some multicolour goodness. I definitely am. We’re not quite there yet, though. Lets’s set up a simple start menu first. There’s a good reason for this, which will be apparent later 🙂

Let’s have a look at the code for part 3 in GitHub. The first section, which deals with configuring Zeus and setting org, is the same as part 2.

The next section expands on the starting code that gets run as soon as we jump into our program:

12
13
14
15
16
Start                   proc                            ; A named PROCedure (also our start point)
                        ld sp, Start                    ; Put our stack right below the program
                        Border(Black)                   ; Set the border to black using a helper macro
                        call ClsAttr                    ; Call another named procedure to do a fast CLS (like GOSUB)
                        Print(MenuText, MenuText.Length); Print text on the screen using ROM routines

Immediately, on line 13 we set our stack to just below the program. This is somewhat of a personal preference, but stacks are generally either kept above or below our programs, and there’s a possibility this might end up being a 128K-only game. If that’s the case, the top 16K of RAM becomes quite valuable as it can be switched in and out with other 16K banks. Having the stack in this area tends to put a crimp on this.

Line 14 calls a macro to set the border to black. Hopefully this is self-explanatory. I like to treat macros as opportunities to improve code readability—although the opposite can be true too! The macro, further down at line 45, is the standard way of doing this in Z80.

45
46
47
48
Border                  macro(Colour)                   ; Macro (makes the code more readable) to set border
                        ld a, Colour                    ; Set a to the colour desired
                        out (ULAPort), a                ;   and output it to the ULA Port (defined in constants)
mend                                                    ; No RET is needed - this code is inserted inline

ULAPort is a constant I use instead of $FE (decimal 254), purely to make the code self-descriptive. The other readability win here is that the macro is parameterized—whatever you pass in as the value of Colour gets substituted. As I noted in the comments, there is no difference between writing Border(0), and writing:

                        ld a, 0                         ; Set a to black
                        out ($FE), a                    ;   and output it to the ULA Port

Incidentally, Zeus’s macro expansion is pretty clever. I could use my macro, unchanged, with Border(b) (without any quotes around the b). As b is a valid Z80 register, and ld a, b is a valid opcode, Zeus will assemble exactly that! It’s even smart enough to know that Border(hl) would result in ld a, hl—and grumble mightily that this is an invalid opcode.

But where were we? Oh yes. call ClsAttr on line 15 is a function. The code in this function is big enough that we don’t want to repeat it unnecessarily by inlining it every time we clear the screen. Nor does it take any parameters, so let’s assemble it once, invoke it with call, and let it return to the next line with ret, exactly like GOSUB/RETURN in BASIC. The function looks like this:

33
34
35
36
37
38
39
40
41
ClsAttr                 proc                            ; Do an attribute CLS using LDIR block copy
                        xor a                           ; Set a to 0 (blank ink, black paper)
                        ld hl, AttributeAddress         ; Address to start copying from (start of attributes)
                        ld de, AttributeAddress+1       ; Address to start copying to (next byte)
                        ld bc, AttributeLength-1        ; Number of bytes to copy (767, all the attirbutes)
                        ld (hl), a                      ; Set first byte to attribute value
                        ldir                            ; Block copy bytes
                        ret                             ; Return from the procedure (like RETURN)
pend

This is a pretty easy method to copy the same value into a range of bytes. Again, AttributeAddress and AttributeLength are defined as constants for readability.

On line 16, Print(MenuText, MenuText.Length) is another macro. This one is highly parameterized, and as such really improves readability.

52
53
54
55
56
57
58
59
Print                   macro(TextAddress, TextLength)  ; Macro to print text on the screen using ROM routines
                        ld a, ChannelUpper              ; Channel 2 (defined in constants) is the upper screen
                        call CHAN_OPEN                  ; Open this channel (ROM routine)
PrintLoop:              ld de, TextAddress              ; Address of string to print
                        ld bc, TextLength               ; Length of string to print
                        call PR_STRING                  ; Print string (ROM routine)
 
mend

This makes use of two ZX Spectrum ROM routines, to print a string of text on the upper screen. I won’t say too much about them, as they’re often used in other programs.

You’ll notice I’m using dot notation to refer to MenuText.Length in the macro invocation. MenuText is another procedure which I’ve used to encapsulate some data that will be assembled into bytes in RAM, and also some constants. All the constant definitions inside a proc are local to that proc, so there’s an opportunity to namespace your labels for greater semantic clarity. I’m also making use of colour and attribute constants, so that the code resembles a BASIC PRINT statement as much as possible.

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
MenuText                proc                            ; Named procedure to keep our print data tidy
                        db At, 7, 13                    ; These codes are the same as you would use
                        db Paper, Black, Bright, 1      ;   with Sinclair BASIC's PRINT command
                        db Ink, Red, "Z"
                        db Ink, Yellow, "A"
                        db Ink, Cyan, "L"
                        db Ink, Magenta, "A"
                        db Ink, White, "X"
                        db Ink, Green, "A"
                        db At, 21, 6
                        db Ink, Yellow, "PRESS "
                        db Ink, White, "SPACE"
                        db Ink, Yellow, " TO START"
Length                  equ $-MenuText                 ; Let Zeus do the work of calculating the length
pend                                                   ; ($ means the current address Zeus is assembling to)

After printing the menu, the next section goes into an endless loop until the space key is pressed.

17
18
19
20
21
22
23
WaitForSpace:                                           ; All labels inside procedures are local to that procedure
                        halt                            ; Wait for the next 1/50th second interrupt (like PAUSE 1)
                        ld bc, zeuskeyaddr(" ")         ; Get the IO address to input
                        in a, (c)                       ; Read those 5 keys
                        and zeuskeymask(" ")            ; AND with the bit for SPACE
                        jr z SetupGame                  ; If it's zero the key is pressed
                        jp WaitForSpace                 ; Otherwise check keys again

Again, this is standard Spectrum Z80 stuff for reading keys. Zeus has nice zeuskeyaddr and zeuskeymask functions to make it slightly easier to code and read.

The final section does a clear screen and goes into another endless loop after the space key is pressed. This will probably get replaced in the next tutorial, but I wanted it to be clear that pressing space actually does something.

24
25
26
27
28
29
SetupGame:
                        call ClsAttr                    ; Clear the screen to prove we pressed space
EndlessLoop:
                        halt
                        jp EndlessLoop                  ; Go into an endless loop (for now...)
pend

The code at the end is worth mentioning briefly—Zeus can create TAP, TZX, SNA and Z80 files directly from code. What I’m doing here is similar to what Pasmo does with it’s --tapbas mode. Where Zeus comes into its own, though, is generating tape files for 128K Spectrums. We will see later, perhaps 🙂

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
BinPath                 equ "..\bin"                    ; Relative to main.asm
TapFile                 equ BinPath+"\ZalaXa.tap"       ; Filename of tap file
 
 
 
; Make tape file
End                     equ $                           ; Calculate the last byte of our program
Size                    equ End-Start                   ; Count the bytes to save to tape
output_tap              TapFile, "ZalaXa", "seven-fff.com/zalaxa", Start, Size, 2, Start
                                                        ; Make a .TAP file. Parameters:
                                                        ;   1) the file name
                                                        ;   2) the name of the BASIC loader program
                                                        ;   3) a comment that goes in the TAP header
                                                        ;   4) Start of machine code program
                                                        ;   5) Length of machine code program
                                                        ;   6) Zeus mode 2 files use the standard ROM loader
                                                        ;   7) Tell the BASIC loader what to run with RANDOMIZE
                                                        ;       USR (like Zeus_PC tells the Zeus emulator)

Well, that was a very long, very explain-y post. Next time I will talk a little more about NIRVANA+ and introduce some multicolour code!

ZalaXa 2 — Setting up the dev environment

I’m going to dive right in and talk about setting up my dev environment. All the code and techniques we use with Z80 and ZX Spectrum development can be made to work with any toolchains, and every established developer has their favourites.

I’m no exception, and I’m an enthustiastic user of Simon Brattel‘s Zeus. Zeus has a lineage going back to 1977 on Simon’s homebrew computers, and on the Spectrum from the beginning. Many now-legendary games developers used Zeus back in the day.

Simon was also an early pioneer of cross-development. Many of his classic games, like Halls of the Things and Dark Star, were written on his Z80 homebrew computer, Basil, with a Parasys debugger link between Basil and the Spectrum.

The Windows cross-development IDE has had a continuous pedigree since, as the main IDE for Simon’s electronics and processor design business. And, for the last decade, as a continuously-developed Spectrum-oriented assembler, IDE and emulator with, incidentally, inbuilt support for NIRVANA+.

My personal affiliation to Zeus is based on how easy it makes my development process. I suspect most of this is an affinity between the way Simon and I think—some of this being that our thinking is similar, and some being the way I’m challenged to think differently.

Whatever the philosophical underpinnings, the end result is that I’ll be doing this tutorial series on Zeus. Feel free to follow along with Zeus if you’re a relative beginner, or adapt my examples for your own favourite IDE, assembler and emulator.

Installing Zeus is easy. Download the latest version of zeus.exe here, stick it in a directory and make a shortcut to it. If you’re on Windows 7/8/10, you’ll have to do the usual unblocking the first time you run the program. Zeus works well on Linux and MacOS under Wine, although I only use Windows myself.

I’ve made a GitHub repository for this series of tutorials. Familiarize yourself with the git version control system, and the process of cloning a repository, if you don’t already know this. I use TortoiseGit on Windows, and find it very simple and intuitive.

I will establish a convention that the source for the latest version of ZalaXa will be inside the /src directory, and the source for a particular tutorial post will be inside the /tutorials directory—this posts code is found at /tutorials/part2, for example.

Once you have cloned the repository and updated it to the latest version, choose File >> Open in the Zeus menu, and open \tutorials\part2\main.asm. You will see this code—the bare minimum template to assemble a Z80 program and run it in Zeus’s emulator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
; main.asm
 
zeusemulate             "48K"                           ; Tell the Zeus emulator to be a 48K Spectrum
zoLogicOperatorsHighPri = false                         ; Zeus assembler options
zoSupportStringEscapes  = false                         ;   (see Config tab
zoAllowFloatingLabels   = false                         ;   for details)
Zeus_PC                 = Start                         ; Tell the Zeus emulator where to start running code at
org                     $8000                           ; Tell the Zeus assembler where to place the code
 
 
 
Start                   proc                            ; A named PROCedure (also our start point)
                        jp Start                        ; Go into an endless loop!
pend

Click the Assemble Then Emulate button:

You should be rewarded with an assembler status message saying this:

nErrors = 0 nRedef = 0 nUndef = 0

and a completely blank white spectrum screen in the Zeus emulator:

And on that bombshell, we will continue in the next post!

ZalaXa 1 — The Idea

Talking to my Spec-Chum Andy Dansby the other day, I came up with the idea of doing a blog tutorial series on writing a multicolour ZX Spectrum game.

Maybe not for the complete beginner, as there are any number of excellent tutorials for n00bs out there already. But something where you follow along and let it carry you through into a specialised subject area.

I will talk about the history of multicolour on the Spectrum in more detail later, but for now, let’s say that one of the strengths, and quirks, of the Spectrum is its display format. Unlike other home micros of the era, the Spectrum restricted you to one foreground and one background for every block of 8 by 8 pixels—the primary motivation of the designers being economy: a relatively small amount of precious RAM was taken up by graphics data, leaving more for other program features. Being as popular as it became, this was taken as a creative challenge by 1980s programmers, and many excellent games and other programs were written, making maximum use of both the available memory and these particular visual constraints.

It’s not the only way of doing things, though. Instead of the dedicated Spectrum ULA handling the graphics output, earlier homebrew computers often used the microprocessor to draw the display. This took up much of the available processor time, and involved precise timing—the program would “chase” the TV’s raster beam as it scanned across and down the screen, outputting pixels at the precisely-synchronised time.

At some point during the Spectrum’s heyday, some talented people figured out raster chasing could be used on the Spectrum too—you could let the ULA chip draw the pixels, but you could change the colours on the fly, as you chased the raster beam. In this way you could have one foreground colour in every 8×4, 8×2 or even 8×1 pixel block. Fast forward to 2015, and the smart folks had systemised this to the extent of enabling Einar Saukas to publish the NIRVANA bicolor graphics engine, using 8×2 attributes.

It’s this engine, or rather its fullscreen variant NIRVANA+, that I’d like to base this tutorial series around.

As a taster, here’s Einar’s NIRVANA+ demo program. Download the .TAP here.

ZalaXa — Table of Contents

  1. The Idea
  2. Setting Up the Dev Environment (code)
  3. A Simple Start Menu (code)
  4. First Glimpse of Multicolour (code)
  5. Wide Tiles (code)
  6. Preshifted Sprites (code)
  7. Moving the Ship (code)
  8. Clearing the NIRVANA+ Screen (code)
  9. Proportional Fonts With FZX (code)
  10. A Naïve Scoring Routine (code)
  11. Flashy 1UPmanship (code)
  12. Towards a Scrolling Starfield (code)
  13. You Gotta Roll With It (code)

Zeus Data Breakpoints — Part 1

One of the nice things about the Zeus Z80 cross-assembler is the debugger built into its integrated emulator.

OMOIDE, one of the ZX Spectrum games I’m working on has a huge conceit—the entire game is presented as if it’s an obscure Japanese game that never got translated into English. The text is written in English, in katakana script, as the Japanese do for foreign loanwords, and often also for videogames.

I softened slightly on the menu items, as it’s all too easy for players to accidentally select a joystick option that renders them a) unable to play the game, if not just b) confused. I added a little marquee at the top that discreetly cycles through the menu options in English.

The text for option 0 is supposed to say 0: PLAY in a tiny 3×5 pixel font (actually one of the Robotron 2084 fonts), but sadly it doesn’t. It’s something more akin to N. Qi Nw, which is no good to anybody, apart from possibly a klingon.

I checked all the obvious things, and couldn’t for the life of me figure out why this item (and only this item) gets corrupted. It happens consistently, even if you assign that text to a different option—the problem moves with the text, not with the menu slot. It’s semi-legible, like the lines got shuffled around, which makes it worse than random garbage, as there’s obviously some logic to it, albeit wrong logic.

Let’s look at the data that’s copied onto the screen. This is a multicolour NIRVANA+ menu, which means there’s only about 15,000 T-states available per frame to do everything, instead of the usual 70,000-odd. For speed of reading, writing and address calculation, I’m storing the data in the same format the screen does. Which, if you’ve ever watched a loading screen appear line by line, you’ll know is not laid out in a linear coordinate-based fashion.

I write the text in a standard .SCR file, and load it into memory at a convenient place. It turns out I don’t need the while file, only about 3/5ths of the first third of the pixels, up until the green dots. And none of the attributes – they’re just they’re to make it easier to work with in my graphics app. By checking in a hex editor, I can see I only need the first 1139 bytes—still a bit wasteful, but I have the space and I need every T-state.

This data is referenced in a table, where zxpixeladdr() is a Zeus helper function that converts pixels into addresses—zxpixeladdr(0, 0) would emit $4000, etc. Only the low byte of each address needs to be stored, because the high byte is the same for all the entries—halving the size of the table.

align 256
MenuExplanation proc Table:
 
  ;                                   Low   Index   Function
  db MenuText.Offset+zxpixeladdr(  0,  0)   ;   0   0: Play
  db MenuText.Offset+zxpixeladdr( 72,  0)   ;   1   1: Keyboard
  db MenuText.Offset+zxpixeladdr(144,  0)   ;   2   2: Kempston
  db MenuText.Offset+zxpixeladdr(  0,  8)   ;   3   2: Sinclair
  db MenuText.Offset+zxpixeladdr( 72,  8)   ;   4   2: Cursor
  db MenuText.Offset+zxpixeladdr(144,  8)   ;   5   2: Fuller
  db MenuText.Offset+zxpixeladdr(  0, 16)   ;   6   2: Kempston Mouse
  db MenuText.Offset+zxpixeladdr( 72, 16)   ;   7   2: AMX Mouse
  db MenuText.Offset+zxpixeladdr(144, 16)   ;   8   3: Help
  db MenuText.Offset+zxpixeladdr(  0, 24)   ;   9   4: High Scores
  db MenuText.Offset+zxpixeladdr( 72, 24)   ;  10   5: Credits
 
  struct
    Low         ds 1
  Size send
 
  Len           equ $-Table
  Count         equ Len/Size
  High          equ high( MenuText.Offset+zxpixeladdr(0, 0))
  Joystick      equ 2
  Items         equ 6
 
pend

The code that reads and prints the date looks like this. PageBank() is a macro I use to switch the 128K upper RAM bank. As you can see, it uses ldir to do a zigzag block copy of the data—the first, third and fifth rows from left to right, and the second and fourth rows from right to left.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
PrintMenuExplanation    proc                            ; MenuExplanation.Index is passed in L
                        PageBank(0, true)
                        ld h, high(MenuExplanation)
                        ld l, (hl)
                        ld h, MenuExplanation.High
                        ld de, zxpixeladdr(80, 8)
                        ld bc, 9
                        ldir
                        inc h
                        inc d
                        dec l
                        dec e
                        ld bc, 9
                        lddr
                        inc h
                        inc d
                        inc l
                        inc e
                        ld bc, 9
                        ldir
                        inc h
                        inc d
                        dec l
                        dec e
                        ld bc, 9
                        lddr
                        inc h
                        inc d
                        inc l
                        inc e
                        ld bc, 9
                        ldir
                        ret
pend

As I always do when I hit a brick wall, I reached for the Zeus debugger and its zeusdatabreakpoint feature, inserting them into the code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
PrintMenuExplanation    proc                            ; MenuExplanation.Index is passed in L
                        PageBank(0, true)
 
                        ld a, l                         ; Save L to print in the breakpoints
                                                        ; (not needed in the final code)
                        ld h, high(MenuExplanation)
                        ld l, (hl)
                        ld h, MenuExplanation.High
                        ld de, zxpixeladdr(80, 8)
                        ld bc, 9
                        zeusdatabreakpoint 2, "zeusprinthex(1, a, hl, de, bc)", $
                        ldir
                        inc h
                        inc d
                        dec l
                        dec e
                        ld bc, 9
                        zeusdatabreakpoint 2, $
                        lddr
                        inc h
                        inc d
                        inc l
                        inc e
                        ld bc, 9
                        zeusdatabreakpoint 2, $
                        ldir
                        inc h
                        inc d
                        dec l
                        dec e
                        ld bc, 9
                        zeusdatabreakpoint 2, $
                        lddr
                        inc h
                        inc d
                        inc l
                        inc e
                        ld bc, 9
                        zeusdatabreakpoint 2, $
                        ldir
                        ret
pend

There are nine general purpose slots that you can write data-driven breakpoint expressions in—plus slots to break on expressions involving data reads, writes, IO port reads and writes, and RAM page changes. Expressions can be set in the UI or in code—the latter allowing them to persist across multiple debugging sessions.

The expressions can be extremely complicated, and can read and change memory if you need to. Here I’m keeping it simple. zeusprinthex(1, a, hl, de, bc) means always (1) print these expressions (the values of a, hl, de and be) to the debug output window, whenever the emulator’s PC is pointing at these addresses (the five values of $, which equates to the five lines following each expression). I’m using the same slot (2) for all of them, as the expression is the same.

Running through the first three menu items, it looks like this:

I put a general non-data breakpoint in at the start of the routine too, purely because it separates out the debug output nicely.

Immediately you can see the pattern is wrong. For the second and third menu items, hl (the source address) increases by $100 for each of the five lines. But for the first item it doesn’t! It’s an edge-case—the lines that go wrong start on a 256-byte boundary (i.e. has an $NN00 address).

0000 D100 402A 0009
0000 D208 4132 0009
0000 D200 422A 0009
0000 D308 4332 0009
0000 D300 442A 0009
 
0001 D109 402A 0009
0001 D211 4132 0009
0001 D309 422A 0009
0001 D411 4332 0009
0001 D509 442A 0009
 
0002 D112 402A 0009
0002 D21A 4132 0009
0002 D312 422A 0009
0002 D41A 4332 0009
0002 D512 442A 0009

I could fix this in the code with special handling, but it’s much easier to shift everything along one byte—which equates to 8 pixels to the right—in the .SCR file! After all, I have the space 🙂

  ;                                   Low   Index   Function
  db MenuText.Offset+zxpixeladdr(  8,  0)   ;   0   0: Play
  db MenuText.Offset+zxpixeladdr( 80,  0)   ;   1   1: Keyboard
  db MenuText.Offset+zxpixeladdr(152,  0)   ;   2   2: Kempston
  db MenuText.Offset+zxpixeladdr(  8,  8)   ;   3   2: Sinclair
  db MenuText.Offset+zxpixeladdr( 80,  8)   ;   4   2: Cursor
  db MenuText.Offset+zxpixeladdr(152,  8)   ;   5   2: Fuller
  db MenuText.Offset+zxpixeladdr(  8, 16)   ;   6   2: Kempston Mouse
  db MenuText.Offset+zxpixeladdr( 80, 16)   ;   7   2: AMX Mouse
  db MenuText.Offset+zxpixeladdr(152, 16)   ;   8   3: Help
  db MenuText.Offset+zxpixeladdr(  8, 24)   ;   9   4: High Scores
  db MenuText.Offset+zxpixeladdr( 80, 24)   ;  10   5: Credits

Bingo, bug fixed! This took about a minute and half from starting to write the databreakpoint expressions to testing the fix—waaay shorter than it took to write up for the blog! Sure, I could have stepped through the code in any emulator, and figured out the same thing, but this approach scales up very well when the problem is more complicated, particularly when it is spread out over multiple routines across a longer timeframe.

Jet Power Jack Mini-Attract Mode

Recently I’ve been fiddling around getting Jet Power Jack running on the Russian Pentagon 128 ZX Spectrum clone. Einar and Denis Grachev made a version of the  NIRVANA+ engine adapted to the Pentagon’s uncontented ULA timings.

A while ago I made a full attract mode for Jet Power Jack, but reluctantly had to shelve it as I was running low on memory (despite having an entire 128K to squander). The Pentagon version needs a boot menu where you can pick which version of the game to load, so I thought it might be good to play around with attract mode ideas again.

 

The original attract mode recorded keystrokes and frame numbers, and fed them directly to the game—well, a special patched version of the game that was really fiddly to set up in these RAM-impoverished times. This is simpler, as it just processes a script with a list of directions to go in, and the number of times to repeat each one:

BootScript proc Table:
 
  ;   URDL  Repeat
  db %0001,     48
  db %0000,      6
  db %0100,     10
  db %1000,     16
  db %0001,     12
  db %1000,      4
  db %0001,     12
  db %0100,     12
  db %1000,     12
  db %1100,     14
  db %0100,     32
  db %0110,     11
  db %0100,     28
  db %1000,      6
  db %0011,     11
  db %1001,     11
  db %0001,     14
  db %0010,      6
  db %1100,      6
  db %0110,      6
  db %1100,      6
  db %0110,      6
  db %0100,      4
  db %1000,      6
  db %0100,     20
  db %0010,      6
  db %0110,     12
  db %0010,      6
  db %0011,     17
  db %0100,     16
  db %1000,      6
  db %0010,      3
  db %0011,      6
  db %0001,     28
  db %1000,      3
  db %0001,     12
  db %0100,     12
  db %0001,     54
  db %0100,     30
 
  struct
    Direction   ds 1
    Repeat      ds 1
  Size send
 
  Len           equ $-Table
  Count         equ Len/Size
 
pend

This is the code that reads and processes the script, one “repetition” every 1/50th second PAL frame:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
AnimateJack             proc
GetNext equ $+1:        ld a, 0
                        or a
                        jp nz, Process
 
Seq equ $+1:            ld a, SMC
                        add a, a
                        ld hl, BootScript.Table
                        Add(hl, a)
                        ld de, 0
                        ld a, (hl)                      ; 0000URDL  PlayerRecord.Direction
                        bit BitLeft, a                  ;     8421
                        jp nz, GoLeft
                        bit BitRight, a
                        jp nz, GoRight
Vertical:
                        bit BitUp, a
                        jp nz, GoUp
                        bit BitDown, a
                        jp nz, GoDown
                        jp Calculate
GoLeft:
                        ld e, -2
                        jp Vertical
GoRight:
                        ld e, 2
                        jp Vertical
GoUp:
                        ld d, -2
                        jp Calculate
GoDown:
                        ld d, 2
Calculate:
                        ld a, e
                        ld (Deltas), a
                        ld a, d
                        ld (Deltas+1), a
 
X equ $+1:              ld a, 126
                        add a, e
                        ld e, a
                        ld (X), a
 
Y equ $+1:              ld a, 164
                        add a, d
                        ld d, a
                        ld (Y), a
 
                        inc hl
                        ld a, (hl)                      ; PlayerRecord.Repeat
                        dec a
                        ld (Rept), a
                        ld (GetNext), a
Draw:
                        ld a, (Deltas)
                        ld c, 0
                        cp 2
                        jp z, Thrust
                        ld c, 4
Thrust:
                        ld ixl, 0
                        ld a, (FRAMES)
                        and %1000
                        jp z, ThrustOffset
                        ld ixl, 8
ThrustOffset:
                        ld a, e
                        ld b, e
                        and %11111000
                        rra                             ; / 2
                        rra                             ; / 4
                        rra                             ; / 8
                        ld e, a                         ; Char column: INT(pixel column / 8))
                        ld a, b
                        and %00000110
                        rra                             ; Horizontal offset: (pixel column % 8) / 2
                        ld b, Tiles.Jack                ; Jack Base tile
                        add b                           ; + horizontal offset
                        add c                           ; + directional offset
                        add ixl                         ; + thrust index
                        ld (SPRITE_H_IX), a
                        ld (SPRITE_H_COL), de
OldPos equ $+1:         ld hl, SMC
                        ld (SPRITE_G_COL), hl
                        ld a, Tiles.Blank
                        ld (SPRITE_G_IX), a
                        ld (OldPos), de
 
                        ret
Process:
Deltas equ $+1:         ld hl, SMC
                        ld a, (X)
                        add l
                        ld l, a
                        ld (X), a
                        ld a, (Y)
                        add h
                        ld h, a
                        ld (Y), a
 
Rept equ $+1:           ld a, SMC
                        dec a
                        ld (Rept), a
                        ex de, hl
                        jp nz, Draw
                        ld (GetNext), a
                        ld a, (Seq)
                        inc a
                        cp BootScript.Count
                        jp c, SaveSeq
                        xor a
SaveSeq:
                        ld (Seq), a
                        jp Draw
 
Left                    equ  1
Down                    equ  2
Right                   equ  4
Up                      equ  8
 
BitLeft                 equ  0
BitDown                 equ  1
BitRight                equ  2
BitUp                   equ  3
 
pend

It’s not at all optimised. I tend to write Z80 code vaguely optimised for speed rather than size, but only to the extent it flows freely and is still readable (to me!).

This is the multicolour tileset. You should be able to see the offsets mentioned in the code—horizontal (0..3), directional (0 or 4) and vertical (0 or 8):