Write in C (ZX Spectrum) GameDev

This ne’er-do note is devoted to the development of games for the ZX Spectrum old computer to C. Let’s take a look at the handsome:

He began producing in 1982, and was produced until 1992. Technical data: 8-bit processor Z80, 16-128kb memory and other are extensions such as audio chipAY-3-8910.

The competition Yandex Retro Games Battle 2019 for this machine I wrote a game called Interceptor 2020. Since learning assembler for the Z80 did not have time, I decided to develop it in C language. As tulcheyna I chose the Quick Set – z88dk, which includes C compilers, and many support libraries to accelerate the implementation of applications for the Spectrum. It also supports many other Z80 machines, such as MSX, Texas Instruments calculators.

Next I will describe his flight over the surface computer architecture tulcheynom z88dk, show how it was possible to implement OOP approach is to use design patterns.

Special features

z88dk installation should be performed by a manual from the repository, but for Ubuntu users, I would like to mention feature – if you have already installed compilers for Z80 from the deb package, you should remove them as z88dk will default to access them from the bin folder of the -this version incompatibility tulcheyn compiler, you probably will not be able to collect anything.

Hello World

Write Hello World is very simple:


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

Assemble the tap in the file is even easier:


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

To start using any emulator ZX Spectrum tap supporting files, such as Online:

http://jsspeccy.zxdemo.org/

Draw on the image to full screen

tl; dr Pictures drawn tiles, tiles 8×8 pixels size, the tiles themselves are embedded in the font Spectrum, then the string of index picture is printed.

O library sprites and tiles sp1 displays tiles using UDG. The picture is translated into a set of separate UDG (tiles) is then collected on the screen using the indices. It should be remembered that UDG is used to display the text, and if your image contains very large set of tiles (eg more than 128 tiles), you have to go beyond the set boundaries and to erase the default font Spectrum. To work around this limitation, I used a base of 128 – 255 using the simplified representation, leaving the original font on the spot. On simplification of the pictures below.

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

There is a way ZX real men, real retro warriors is to open the editing palette using Spectrum, especially knowing the output image, prepare it and manually unload using png2c-z88dk or png2scr.

Way easier – take a 32-bit image, switch to Gimp colors to 3-4, slightly to edit, then import into img2spec not to work by hand with color restrictions, export png and transferred to the C array with png2c-z88dk.

It should be remembered that successful export each tile can not contain more than two colors.

As a result, you get the h file that contains a number of unique tiles, if more than ~ 128, simplify the Gimp in a picture (increase repeatability) and spend on a new procedure for export.

After exporting, you literally download a “Font” from the tiles and typing “text” of the indices of tiles on the screen. Here is an example of the “class” of the rendering:


// loading font into memory
    unsigned char *pt = fullscreenImage->tiles;

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

    // set cursor into 0,0
    sp1_SetPrintPos(&ps0, 0, 0);

    // print string
    sp1_PrintString(&ps0, fullscreenImage->ptiles);

Drawing sprites on the screen

Next, I will describe a way of drawing sprites of 16×16 pixels on the screen. Before the animation and change colors I came because corny at this stage, I guess I ran out of memory. Therefore, in the game there are only transparent monochrome sprites.

Draw in Gimp monochrome png image 16×16, etc. using png2sp1sprite translate it into assembly asm file in C code declare arrays of the assembly file, add the file at build time.

After the declaration of a resource of the sprite, it is necessary to add the screen to the desired position, then the sample code “class” 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 some functions can understand the meaning – allotsiruem memory sprite, add two columns 8×8, add color for a sprite.

Each frame is affixed position of the sprite:


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

OOP simulations

In C, there is no syntax for OOP, what do you do if you still really want to? It is necessary to connect the Dumka and illumined thought that such a thing as the PLO equipment does not exist, everything eventually comes to a machine architectures in which there is simply no concept of the object and other related abstractions.

This fact bothered me for a long time to understand why do you need the PLO, why you need to use it if in the end everything comes to machine code.

However, having worked in the product development, I opened the charm of this programming paradigms, primarily of course the development of the flexibility mechanisms of the protective code, with the right approach entropy reduction, simplification of teamwork. All of these advantages derive from the three pillars – polymorphism, encapsulation, inheritance.

Also worth noting is the simplification of addressing issues related to the architecture of the application, because 80% of architectural problems were solved by computer-scientists in the last century and described in the literature devoted to the design pattern. Next, I will describe how to add like OOP syntax in C.

For instance data storage more convenient to take the basis of class C structure. Of course, you can use a byte buffer to create its own structure for the classes, methods, but why reinvent the wheel? After all, we already reinventing syntax.

These classes

An example of the data fields “class” GameObject:


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;

We maintain our class as “GameObject.h” do #include “GameObject.h” in the right place and use.

Class methods

Take into service experience Objective-C language development, the signature method of the class will be from a function in the global osprey, the first argument will always transmitted data structure, method arguments go further. Next, an example of “the method” “class” GameObject:


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

Method call is as follows:


GameObject_hide(gameObject);

Constructors and destructors are implemented in the same manner. It can be implemented as an allocator constructor and field initializers, but I prefer separate methods for that,

Working with memory

Manual memory management type using malloc and free macros wrapped in new and delete operators for compliance with C ++:


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

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


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 common object using the retain, release the possession through release. In the modern version of ARC uses an automatic affixing call retain / release.

I sound!

Spectrum has a tweeter capable of reproducing 1-bit music, the composers of the time were able to play on it for up to 4 audio channels simultaneously. Spectrum 128k comprises a separate sound chip AY-3-8910, which can reproduce music tracker. To use the Tweeters in z88dk proposed library sound.h

What is to be learned

I was interested to read the Spectrum, to realize the game z88dk means, learn a lot of interesting things. I much remains to be explored, such as the assembler Z80, as it allows you to use the full power of Spectrum, the work of memory banks, working with the sound chip AY-3-8910. I hope to participate in the competition for next year!

References

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

Source Code

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