Game development for ZX Spectrum in C

This nonsensical article is dedicated to the development of a game for the old ZX Spectrum computer in C.

It began production in 1982, and was produced until 1992. Technical characteristics of the machine: 8-bit Z80 processor, 16-128kb of memory and other extensions, such as the AY-3-8910 sound chip.

As part of the competition Yandex Retro Games Battle 2019 for this machine I wrote a game called Interceptor 2020. Since there was no time to learn assembler for the Z80, I decided to develop it in C. As a toolchain, I chose a ready-made set - z88dk, which contains C compilers and many auxiliary libraries to speed up the implementation of applications for the Spectrum. It also supports many other Z80 machines, such as MSX, Texas Instruments calculators.

Next I will describe my superficial flight over the computer architecture, the z88dk toolchain, and show how I managed to implement the OOP approach and use design patterns.

Installation features

The installation of z88dk should be carried out according to the manual from the repository, however, for Ubuntu users, I would like to note a feature - if you already have compilers for Z80 installed from deb packages, you should remove them, since z88dk by default will access them from the bin folder, due to incompatibility of toolchain compiler versions, you most likely will not be able to compile anything.

Hello World

Writing Hello World is very easy:

#include 

void main()
{
    printf("Hello World");
}

It’s even easier to compile a tap file:

zcc +zx -lndos -create-app -o helloworld helloworld.c

To run, use any ZX Spectrum emulator with tap file support, for example online:
http://jsspeccy.zxdemo.org/

Draw on the picture in full screen

tl;dr Pictures are drawn in tiles, tiles of size 8x8 pixels, the tiles themselves are built into the Spectrum font, then the picture is printed as a line from the indices.

The sprite and tile output library sp1 outputs tiles using UDG. The picture is translated into a set of individual UDGs (tiles), then assembled on the screen using indices. It should be remembered that UDG is used to display text, and if your picture contains a very large set of tiles (for example, more than 128 tiles), then you will have to go beyond the boundaries of the set and erase the default Spectrum font. To get around this limitation, I used a base of 128 – 255 by simplifying the images, leaving the original font in place. About simplifying the pictures below.

To draw full-screen images you need to arm yourself with three utilities:
Gimp
img2spec
png2c-z88dk

There is a way for real ZX men, real retro warriors, to open a graphic editor using the Spectrum palette, knowing the features of the image output, prepare it manually and upload it using png2c-z88dk or png2scr.

The simpler way is to take a 32-bit image, switch the number of colors to 3-4 in Gimp, edit it slightly, then import it into img2spec so as not to work with color restrictions manually, export png and convert it to a C array using png2c-z88dk.

You should remember that for successful export, each tile cannot contain more than two colors.

As a result, you will receive an h file that contains the number of unique tiles; if there are more than ~128, then simplify the image in Gimp (increase the repeatability) and perform a new export procedure.

After export, you literally load the “font” from the tiles and print the “text” from the tile indexes onto the screen. Below is an example from the render “class”:

    // грузим шрифт в память
    unsigned char *pt = fullscreenImage->tiles;

    for (i = 0; i < fullscreenImage->tilesLength; i++, pt += 8) {
            sp1_TileEntry(fullscreenImage->tilesBase + i, pt);
    }

    // ставим курсор в 0,0
    sp1_SetPrintPos(&ps0, 0, 0);

    // печатаем строку
    sp1_PrintString(&ps0, fullscreenImage->ptiles);

Drawing sprites on the screen

Next I will describe a method for drawing 16x16 pixel sprites on the screen. I didn’t get to animation and changing colors, because... It’s trivial that already at this stage, as I assume, I ran out of memory. Therefore, the game contains only transparent monochrome sprites.

Draw a 16×16 monochrome png image in Gimp, then use png2sp1sprite to translate it into an asm assembly file, declare arrays from the assembly file in C code, and add the file at the assembly stage.

After the stage of declaring the sprite resource, it must be added to the screen in the desired position, below is an example of the code for the “class” of the game object:

    struct sp1_ss *bubble_sprite = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 3, 0, 0);
    sp1_AddColSpr(bubble_sprite, SP1_DRAW_MASK2,    SP1_TYPE_2BYTE, col2-col1, 0);
    sp1_AddColSpr(bubble_sprite, SP1_DRAW_MASK2RB,  SP1_TYPE_2BYTE, 0, 0);
    sp1_IterateSprChar(bubble_sprite, initialiseColour);

From the names of the functions you can roughly understand the meaning - allocate memory for the sprite, add two 8x8 columns, add a color for the sprite.

The position of the sprite is indicated in each frame:

sp1_MoveSprPix(gameObject->gameObjectSprite, Renderer_fullScreenRect, gameObject->sprite_col, gameObject->x, gameObject->y);

Emulating OOP

There is no syntax for OOP in C, what should you do if you still really want to? You need to connect your mind and be enlightened by the idea that there is no such thing as OOP equipment; everything ultimately comes to one of the machine architectures, in which there is simply no concept of an object and other abstractions associated with it.

This fact prevented me for a very long time from understanding why OOP is needed at all, why it is necessary to use it if in the end everything comes to machine code.

However, after working in product development, I discovered the delights of this programming paradigm, mainly, of course, development flexibility, code protection mechanisms, with the right approach, reducing entropy, simplifying team work. All of these advantages stem from three pillars - polymorphism, encapsulation, inheritance.

It is also worth noting the simplification of solving issues related to application architecture, because 80% of architectural problems were solved by computer scientists back in the last century and described in the literature on design patterns. Next, I'll describe ways to add OOP-like syntax to C.

It is more convenient to take C structures as the basis for storing data of a class instance. Of course, you can use a byte buffer, create your own structure for classes, methods, but why reinvent the wheel? After all, we are already reinventing syntax.

Class data

Example of GameObject “class” data fields:

struct GameObjectStruct {
    struct sp1_ss *gameObjectSprite;
    unsigned char *sprite_col;
    unsigned char x;
    unsigned char y;
    unsigned char referenceCount;
    unsigned char beforeHideX;
    unsigned char beforeHideY;
};
typedef struct GameObjectStruct GameObject;

Save our class as “GameObject.h”, do #include “GameObject.h” in the right place and use it.

Class methods

Taking into account the experience of the developers of the Objective-C language, the signature of a class method will be functions in a global scope, the first argument will always be the data structure, followed by the method arguments. Below is an example of a “method” of the “class” GameObject:

void GameObject_hide(GameObject *gameObject) {
    gameObject->beforeHideX = gameObject->x;
    gameObject->beforeHideY = gameObject->y;
    gameObject->y = 200;
}

The method call looks like this:

GameObject_hide(gameObject);

Constructors and destructors are implemented in the same way. It is possible to implement a constructor as an allocator and field initializer, but I prefer to control object allocation and initialization separately.

Working with memory

Manual memory management of the form using malloc and free wrapped in new and delete macros to match C++:

#define new(X) (X*)malloc(sizeof(X))
#define delete(X) free(X)

For objects that are used by several classes at once, semi-manual memory management is implemented based on reference counting, in the image and likeness of the old Objective-C Runtime ARC mechanism:

void GameObject_retain(GameObject *gameObject) {
    gameObject->referenceCount++;
}

void GameObject_release(GameObject *gameObject) {
    gameObject->referenceCount--;

    if (gameObject->referenceCount < 1) { 
        sp1_MoveSprAbs(gameObject->gameObjectSprite, &Renderer_fullScreenRect, NULL, 0, 34, 0, 0);
        sp1_DeleteSpr(gameObject->gameObjectSprite);
        delete(gameObject);
    }
}

Thus, each class must declare the use of a shared object using retain, releasing ownership through release. The modern version of ARC uses automatic retention/release calls.

Sound!

The Spectrum has a tweeter capable of reproducing 1-bit music; composers of that time were able to reproduce up to 4 sound channels on it simultaneously.

Spectrum 128k contains a separate sound chip AY-3-8910, which can play tracker music.

A library is offered for using the tweeter in the z88dk

What remains to be learned

I was interested in getting acquainted with the Spectrum, implementing the game using the z88dk, and learning a lot of interesting things. I still have a lot to learn, for example, the Z80 assembler, since it allows you to use the full power of the Spectrum, work with memory banks, and work with the AY-3-8910 sound chip. I hope to participate in the competition next year!

Links

https://rgb.yandex
https://vk.com/sinc_lair
https://www.z88dk.org/forum/

Source code

https://gitlab.com/demensdeum/zx-projects/tree/master/interceptor2020