Skip to content

Choose Your Destiny manual

logo

The program is a compiler and interpreter to run "Choose Your Own Adventure" type stories or choice-based adventures and gamebooks, for the Spectrum 48, 128, +2 and +3.

It consists of a virtual machine that interprets commands found in the text to perform the different interactive actions and a compiler that is responsible for translating the adventure from a BASIC-like language, with which the adventure script is written, to a file interpretable by the engine.

In addition, it can also display compressed images stored on the same disk, as well as sound effects based on Shiru's BeepFx, PT3-type melodies created with Vortex Tracker or melodies created with WyzTracker 2.0.


Requirements and installation

These are the external requirements for the tool:

If you upgrade from an older version, it is recommended NOT to overwrite it: rename the directory of the old version and unzip the new one. Your games don't have to be copied, because each one is a project in its own folder. If your game was made with version 1.6.6 or earlier, in CYD's own folder, see Migrating a game from an older version.

Here are the more detailed instructions for each operating system:

Windows installation

Installation is easy, just unzip the corresponding ZIP file downloaded from the Releases section of the repository. In this case, everything is included in the package. Windows 10 or higher, 64-bit version is required (32-bit not supported).

Linux, BSDs and UNIX-like installation

For these systems, the requirements are:

  • GNU/Linux / Unix / macOS / BSD with a BASH-compatible shell.
  • Python 3.11 or higher
  • All common system programs (grep, cat, etc.).
  • All programs required to compile C programs on the system (libc, libstdc++, g++, GNU make, etc.).
  • Autotools (autoconf, automake, aclocals...).
  • wget
  • git

These requirements are needed to compile SjASMPlus. There is no binary distribution of this tool for UNIX-compatible systems, so you need to compile it directly.

Due to the diversity of distributions, it is impossible for me to give detailed instructions for installing the requirements in each particular case, so some knowledge is required on the part of the user to do so.

The first thing to do is to clone the engine repository to any location you think is convenient and to download the dependencies recursively:

git clone --recursive https://github.com/cronomantic/ChooseYourDestiny.git
cd ChooseYourDestiny

Now you can proceed to compile SjASMPlus with the following commands:

cd external/sjasmplus
make clean
make
cd ..

And with this we have the dependencies ready. As a last step, we must make the compilation script executable:

cd ../..
chmod a+x make_adv.sh

You can now use the tool on Linux.

CYDC (compiler)

This program is the compiler that translates the adventure text into a TAP or DSK file. In addition to compiling the adventure into a file that can be interpreted by the engine, it performs a search for the best abbreviations to reduce the size of the text.

cydc_cli.py [-h] [-l MIN_LENGTH] [-L MAX_LENGTH] [-s SUPERSET_LIMIT]
              [-T EXPORT-TOKENS_FILE] [-t IMPORT-TOKENS-FILE] [-C EXPORT-CHARSET]
              [-c IMPORT-CHARSET] [-S] [-n NAME] [-img IMAGES_PATH] [-trk TRACKS_PATH]
              [-sfx SFX_ASM_FILE] [-scr LOAD_SCR_FILE] [-v] [-V] [-trim] [-dce] [-code]
              [--project-root FOLDER] [-I FOLDER] [--lib-path FOLDER] [--import-path FOLDER]
              [--no-strict-colons] [--max-errors MAX_ERRORS] [--check] [--no-warn-unused]
              [--no-warn-gosub] [--no-warn-shared-vars] [--debug-stack] [--debug-errors] [--keep-temp]
              [--token-format {auto,flat,nested}]
              [-pause PAUSE_AFTER_LOAD] [-wyz] [-il NUM_IMAGE_LINES] [-720] [-autoboot]
              {48k,128k,plus3,mld,mld128,esxdos} input.cyd [SJASMPLUS_PATH] [OUTPUT_PATH]
  • -h: Shows the help
  • -l MIN_LENGTH: The minimum length of the abbreviations to search for (default 3).
  • -L MAX_LENGTH: The maximum length of the abbreviations to search for (default 30).
  • -s SUPERSET_LIMIT: Limit for the superset of the search heuristics (default 100).
  • -T EXPORT-TOKENS_FILE: Export the found abbreviations to the JSON file indicated by the parameter.
  • -t IMPORT-TOKENS-FILE: Import abbreviations from the indicated file and skip the search for them.
  • --token-format {auto,flat,nested}: Abbreviation format. With nested, an abbreviation can contain others, which usually compresses texts 5 to 10% further in text-heavy adventures; the interpreter is then built with a different decoder, the same size as the usual one. With auto (the default) the compiler tries both formats and keeps whichever takes less memory, so with little text it keeps using the simple (flat) format and the output is identical to before. A file exported with -T keeps the format it was generated with, and importing it with -t uses that same format.
  • -C EXPORT-CHARSET: Export the 6x8 character set used by default in JSON format.
  • -c IMPORT-CHARSET: Import the character set to be used in JSON format.
  • -S: If a compressed text fragment does not fit in a bank, it is split into two between the current bank and the next one with this option activated. Otherwise, the fragment is moved to the next bank.
  • -n NAME: Name to use for the output file (name for the TAP or DSK file); if not defined, it will be the same as the input file.
  • -scr LOAD_SCR_FILE: Path to an SCR file with the loading screen to use.
  • -img IMAGES_PATH: Path to the directory with the adventure images.
  • -trk TRACKS_PATH: Path to the directory with the PT3 AY music files or WyzTracker files.
  • -sfx SFX_ASM_FILE: Path to an assembly file generated by BeepFx.
  • --project-root FOLDER: The project's root folder (by default, the folder of the script). An INCLUDE that is not found next to its file is looked for here (see INCLUDE directive).
  • -I FOLDER, --include-path FOLDER: Another folder where INCLUDE looks, after the project root. It can be repeated.
  • --lib-path FOLDER: A folder where INCLUDE LIB looks, before the bundled lib/. It can be repeated.
  • --import-path FOLDER: Another folder where IMPORT looks, after the script's folder. It can be repeated.
  • -v: Verbose mode, gives more information about the process.
  • -V: Indicates the version of the program.
  • -trim: Removes code from commands that are not used in the adventure to make the interpreter smaller.
  • -dce: Removes bytecode that can never be reached (for example, library routines you include but never call). Reachability follows both jumps and sequential fall-through, so nothing that could run is removed. Especially useful with the bundled libraries.
  • -code: Shows the generated bytecode.
  • --no-strict-colons: Allows old syntax without : separators between statements on the same line.
  • --max-errors MAX_ERRORS: Maximum number of parser/preprocessor errors to report before stopping (default 20).
  • --check: Only checks the script for errors (syntax, symbols and the code generator's own, such as a RESTORE with no DATA after it), without assembling it or writing any file, so SJASMPLUS_PATH and OUTPUT_PATH are not needed. It is much faster than compiling because it skips the abbreviation search. Exits with code 0 when there are no errors and 1 otherwise. It does not check whether the adventure fits in memory or whether the images and music exist.
  • --no-warn-unused: Don't warn about declared labels, variables and data arrays that are never used. These warnings (WARNING [PARSER]) don't stop the build. They are only given for files inside the project's folder, and never for the library folders (the bundled lib/ and those of --lib-path), so a library doesn't warn about the routines you don't call. Constants are not reported, since it is normal not to use all of them (for example, those of an ENUM).
  • --no-warn-gosub: Don't warn about the GOSUB/RETURN problems the compiler finds by following the program's flow (see GOSUB ID): a RETURN that can be reached with no GOSUB pending, and a subroutine that can end without RETURN, going on into the main code. These warnings (WARNING [CODEGEN]) don't stop the build.
  • --no-warn-shared-vars: Don't warn about variables that one file declares and another file uses under another name, by their number (SET 205 TO ...) or from another variable (SET v TO {...} running past v). That is how a library's variables, such as sprites.cyd's 200..211, get overwritten without noticing. Reusing a variable under several names within one file doesn't warn, and neither does using it by its name from any file. These warnings (WARNING [CODEGEN]) don't stop the build.
  • --debug-stack: For debugging. The interpreter checks the GOSUB stack at runtime: a RETURN with no GOSUB pending gives system error 9, and a GOSUB that would fill the stack gives error 10, instead of hanging or resetting the Spectrum. It adds about 30 bytes to the interpreter and a little work to each GOSUB and RETURN, so leave it out of the final build.
  • --keep-temp: Keep the intermediate files of the build (cyd.asm, cyd.sym, the listing with -v, and the +3 DISK and .BIN) in the cyd_tmp folder of the output folder. Without it, the output folder only gets what the build delivers (the .tap, .DSK, .MLD, or the esxdos SD files), and cyd_tmp is removed when the build ends well; if it fails, cyd_tmp stays and the compiler says where it is.
  • --debug-errors: For debugging. When a system error happens, the message also says at which instruction, and the compiler writes a .map file next to the game that turns it into a file and a line (see Error codes). Without this option the interpreter doesn't change; with it, the instructions that can't fail run just as fast, so it is only worth leaving out for the bytes.
  • -pause: Number of seconds of pause after finishing the loading process; it can be aborted with any keypress.
  • -wyz: Use WyzTracker music type instead of Vortex Tracker.
  • -il NUM_IMAGE_LINES: Number of lines to use in image files (default 192).
  • -720: If using the +3 format, a 720 KB disk image will be used instead of the standard 180 KB size.
  • -autoboot, --autoboot: [esxdos] Also emit AUTOBOOT.BAS + ESXDOS.CFG so the game cold-boots from the SD card (see the esxDOS note below).

-{48k,128k,plus3,mld,mld128,esxdos}: Spectrum model to be used: -- 48k: Version for tape in TAP format, does not include the PT3 or WyzTracker player and everything is loaded at once. It depends on the size of the available memory. -- 128k: Version for tape in TAP format, everything is loaded at once in the memory banks and depends on the size of the available memory. -- plus3: This version will generate a DSK file to run on Spectrum +3. Resources are loaded dynamically as needed and capacity depends on the disk size. -- mld (EXPERIMENTAL): Generates an .MLD file for the Dandanator Mini cartridge in 48K mode. Text, images and bytecode are read directly from the cartridge slots (no RAM banking and no music playback), spanning several Dandanator slots (up to ~256 KB of content). It uses the cartridge save system. -- mld128 (EXPERIMENTAL): Generates an .MLD file for Dandanator Mini targeting Spectrum 128K. Because everything else (text/images/bytecode) is read from the cartridge slots, the RAM banks are reserved for what must live in RAM: music (PT3/WyzTracker, which plays from RAM) and the DIM arrays (which must be writable; they are placed in dedicated RAM banks that never collide with the music). Spans many Dandanator slots (up to ~480 KB of content). Known limitation: if music, arrays and content together force all RAM banks to be used, compilation aborts with a clear error. -- esxdos: Version for divMMC/divIDE interfaces with an SD card (esxDOS), targeting Spectrum 128K. It works like plus3 (resources loaded dynamically on demand from files), but accessing the SD through the esxDOS API (RST $08) instead of the +3 disk. Unlike the other targets it does not produce a single file, but a set of files to copy onto the SD (see the note below). It includes the -autoboot option.

  • input.cyd: Input file with the adventure script.
  • SJASMPLUS_PATH: Path to the SjASMPlus executable.
  • OUTPUT_PATH: Path where the output files will be stored.

Note on Dandanator (mld/mld128). The compiler produces an .MLD file, which is the game, but it is not directly loadable: it must be packed into a 512 KB Dandanator Mini cartridge ROM. Use the bundled mld2rom.py utility (pure Python; the firmware and menu are built in, no external base ROM is needed):

python mld2rom.py -o my_game.rom -a my_game.MLD

The -a flag enables autoboot (launches the game without going through the menu). The resulting ROM can be flashed onto a real Dandanator Mini or loaded in an emulator that supports it (e.g. EsPectrum, or ZEsarUX with --enable-dandanator --dandanator-rom my_game.rom). The generated ROM is byte-for-byte identical to the one produced by the official dandanator-mini tool.

As an alternative to the command line, the distribution ships a standalone graphical utility, mld2rom_gui.py (launchers mld2rom_gui.cmd / mld2rom_gui.sh), to build the ROM with more options: game name, menu font, background graphic, menu texts, autoboot and border effect.

Note on esxDOS (output files and their location on the SD card). Unlike the other targets, the esxdos target does not produce a single file but a set of files in OUTPUT_PATH that must be copied onto the SD card:

  • NAME.tap — the bootstrap loader (a BASIC program). This is what you launch.
  • NAME.DAT — the game's resident data (interpreter + text/bytecode + WyzTracker music if any). The loader opens it by name.
  • NNN.CSC — one per image (streamed); NNN.BIN — one per Vortex (PT3) music track (streamed). Only generated if the adventure uses images/music.

Because the loader and the engine open these files by name relative to the current directory, they all (NAME.tap, NAME.DAT, NNN.CSC, NNN.BIN) must live in the same folder on the SD. To play: press NMI and select NAME.tap in the esxDOS browser (which sets the current directory to that folder). Savegame files (NNN.SAV) are also created in that folder.

With -autoboot (requires esxDOS 0.8.7+). Two extra files are produced: AUTOBOOT.BAS and ESXDOS.CFG. To make the game boot on power-on: copy AUTOBOOT.BAS to /SYS/ on the SD, set AutoBoot=1 in /SYS/CONFIG/ESXDOS.CFG (use the generated ESXDOS.CFG, or edit your own), and place NAME.DAT and the media in the SD root. Verified on real hardware (divMMC, esxDOS 0.8.9); the esxDOS cold boot cannot be emulated, so it cannot be tested in the emulator.

The compiler is a program written in Python, so it requires the Python environment installed. For convenience, the distribution includes an embedded Python package and a batch script called cydc.cmd to launch it from the command line.

The compiler depends on an external program to run, the SjASMPlus assembler, so you must specify the path to this program in the input parameters. This program is included in the distribution in the tools directory.

You must also specify a destination directory to store the files resulting from the compilation.

Optionally, you can specify the paths to directories containing the compressed images in scr format, which will be included on the resulting tape or disk. The same applies to PT3 files. Both file types must be named with 3-digit numbers, from 0 to 255, such as 000.scr, 001.scr, 002.PT3, and so on. The directories containing both files will be indicated with the -img and -trk parameters, respectively.

The images will be compressed into a CSC file. The screens can be full, or the number of horizontal lines can be limited to save memory. It also detects mirrored (symmetrical) images along the vertical axis, so it only stores half of the image. You can even force this behavior and discard the right side of the image to save space. More details on how this works are found in the Images section.

For the music, we can use Vortex Tracker modules (PT3) or music created with WyzTracker v2.0 and higher. The behavior is also described in their corresponding sections: Vortex Tracker Tunes and WyzTracker Tunes.

You can add sound effects generated with Shiru's BeepFx application. To use them, export them using the File->Compile option in the top menu. In the pop-up window that appears, make sure Assembly and Include Player Code are selected; the rest of the options are irrelevant. Then save the file somewhere accessible, specifying the path from the command line with the -sfx option.


CYD character set converter

This utility allows you to convert character sets in .chr, .ch8, .ch6 and .ch4 format into a compiler-usable file in JSON format. These formats are editable with ZxPaintbrush.

cyd_chr_conv.py [-h] [-w WIDTH_LOW] [-W WIDTH_HIGH] [-v] [-V] charset.chr charset.json

Supported parameters:

  • -w, --width_low: Character width (1-8) of the lower character set.
  • -W, --width_high: Character width (1-8) of the upper character set.
  • -h, --help: Show help.
  • -v, --verbose: Verbose mode.
  • -V, --version: Program version.
  • charset.chr: Input character set.
  • charset.json: File with the character set for the compiler.

The default character width is 6 for the lower character set (characters 0 to 126) and 4 for the upper character set (characters 144 to 255), but these values can be changed with the -w and -W parameters respectively. Note that characters 127 to 143 are special, as they are used for cursors and will always have a width of 8, so the font size will be ignored for those characters. If you want to define a specific width for each character you will have to edit it in the output JSON file. You can find more information in the Character set section.


Basic syntax

Commands for the interpreter are enclosed within two pairs of brackets, open and closed respectively. Any text outside of this is considered "printable text", including spaces and line breaks, and will be presented as such by the interpreter. Commands are separated from each other by line breaks or colons if they are on the same line.

Comments within code are delimited by /* and */; everything in between is considered a comment.

This is a self-explanatory, abbreviated example of the syntax:

This is text [[ INK 6 ]] This is text again but yellow
It's still text [[
/* This is a comment and the following are commands */
WAITKEY
INK 7: PAPER 0
]]
This is text again but white, and watch out for the line break that precedes it!

The interpreter runs through the text from the beginning, printing it on the screen if it is "printable text." When a complete word does not fit on the rest of the line, it prints it on the next line. And if it does not fit on the rest of the screen, a wait is generated and the user is asked to press the confirmation key to clear the section of text and continue printing (this last behavior is optional).

When the interpreter detects commands, it executes them sequentially, unless it encounters jumps. Commands allow you to introduce programmable logic into the text to make it dynamic and varied according to certain conditions. The most common and powerful is to ask the player to choose from a series of options (up to a limit of 32 at a time), which can be chosen with the Q and A keys or the up and down cursor keys (horizontally, with O and P or the left and right cursor keys, if set up with MENUCONFIG), and selected with SPACE or ENTER. It supports a Kempston joystick too. The game can change these keys and accept a Sinclair or cursor joystick with MENUKEY and MENUJOY. Again, this is a self-explanatory example:

[[ /* Commands that set screen colors and clear the screen */
PAPER 0 /* Background color to zero (black)*/
INK 7 /* Ink color (white) */
BORDER 0 /* Border color (black) */
CLEAR /* Clear text area (full screen) */
LABEL Location1]]You are in location 1. Where do you want to go?
[[OPTION GOTO Location2]]Go to location 2
[[OPTION GOTO Location3]]Go to location 3
[[CHOOSE]]
[[ LABEL Location2]]You did it!!!
[[ GOTO Final]]
[[ LABEL Location3]]You are dead!!!
[[ GOTO Final]]
[[ LABEL Final : WAITKEY: END ]]

The OPTION GOTO label command will generate an option point at the position where the command has been reached. When the CHOOSE command is reached, the interpreter will allow the user to choose from one of the option points that have been accumulated on the screen up to that point. A maximum of 32 are allowed.

When choosing an option, the interpreter will jump to the section of text where the corresponding label indicated in the option is found. Labels are declared with the LABEL identifier pseudo-command within the code, and when a jump to it is indicated, the interpreter will begin processing from the point where we have declared the label. In the example, if we choose option 1, the interpreter will jump to the point indicated in LABEL Location2, which will print the text "You did it!!!", and then go to GOTO Final which will make an unconditional jump to where LABEL Final is defined and ignore everything in between.

Label identifiers only support alphanumeric characters (numbers and letters) and the underscore (_), must start with a letter or an underscore (not a digit) and are case-sensitive (upper and lower case are distinguished), i.e. LABEL Label is not the same as LABEL label. Commands, on the other hand, are not case-sensitive, but for clarity, it is recommended to capitalize them.

A shortened version of labels is also allowed by preceding the label identifier with the character #, so that #MyLabel is the same as LABEL MyLabel. With this, we could rewrite the previous code like this:

[[ /* Commands that set screen colors and clear the screen */
PAPER 0 /* Background color to zero (black) */
INK 7 /* Ink color (white) */
BORDER 0 /* Border color (black) */
CLEAR /* Clear text area (full screen) */
LABEL Location1]]You are in location 1. Where do you want to go?
[[OPTION GOTO Location2]]Go to location 2
[[OPTION GOTO Location3]]Go to location 3
[[CHOOSE]]
[[ #Location2 ]]You did it!!!
[[ GOTO Final ]]
[[ #Location3 ]]You are dead!!!
[[ GOTO Final]]
[[ #Final : WAITKEY: END ]]

The available commands are described in their corresponding section.

Strict colon mode (syntax enforcement)

As of version 1.2.x, the compiler enforces Strict Colon Mode by default. This means that when multiple code statements are placed on the same line within [[ ]] blocks, they must be separated by colons (:).

Correct syntax (Strict Colon Mode enabled - DEFAULT):

[[ PRINT 42 : INK 5 : GOTO Label1 ]]
[[ LABEL Label1 : DECLARE 0 AS myvar : SET myvar TO 10 : WAITKEY : END ]]

Incorrect syntax (missing colons):

[[ PRINT 42 INK 5 GOTO Label1 ]]  <-- ERROR: Statements must be separated by colons

If you need to support old code without colon separators, pass the --no-strict-colons flag to the compiler:

cydc_cli.py --no-strict-colons 48k input.cyd sjasmplus output

Key points: - Line breaks automatically separate statements, so colons are only needed when multiple commands are on the same line - Colons are optional with the --no-strict-colons flag for backwards compatibility - This change improves code readability and prevents parsing ambiguities

INCLUDE directive (multi-file projects)

The compiler supports splitting large adventures into multiple source files using INCLUDE.

Syntax:

[[ INCLUDE "chapters/chapter1.cyd" ]]

Rules and behavior: - INCLUDE is processed at compile-time by the preprocessor. - The directive must be inside [[ ]] code blocks. - INCLUDE "path" looks for the file, in this order: next to the file containing the directive; in the project's root folder (the folder of the main script, or the one given with --project-root); and in the folders given with -I. So a file in any subfolder can write INCLUDE "common/vars.cyd" from the root. - INCLUDE LIB "path" includes a library: it only looks in the library folders, first those given with --lib-path and then the bundled lib/. A file of yours with the same name as a library never takes its place. - An absolute path is used as it is. - Nested includes are supported up to 20 levels. - The same library included twice with INCLUDE LIB (for instance by your program and by another library) is only included the first time. Any other file included twice is an error, which says where it was included first. - Circular includes are detected and reported as errors. - Included files can include other files.


Bundled libraries

The lib/ directory ships a set of libraries written in the CYD language itself, with their core in native Z80 assembly (ASM blocks, see Native routines); they do not modify the virtual machine or add dependencies. They are collections of subroutines that you add to your program with INCLUDE LIB and call with GOSUB. Each library skips over itself (an internal GOTO at the top), so you can include it at the start of your script without execution falling into the subroutines: they only run when you call them with GOSUB.

[[
    INCLUDE LIB "math16_32.cyd"
    INCLUDE LIB "strings.cyd"
    ... your program ...
]]

Each library reserves a block of variables as its workspace. The blocks do not overlap, so you can use several at once. If your program uses one of those numbers under another name or directly by its number, the compiler warns (see --no-warn-shared-vars):

Library Reserved variables
math16_32.cyd 224..254
strings.cyd 216..223
sprites.cyd 200..211
sprites_px.cyd 200..212 (instead of sprites.cyd)

math16_32.cyd — 16- and 32-bit arithmetic

Provides wide unsigned integers (16-bit: 0..65,535; 32-bit: 0..4,294,967,295) with multiplication and division, which CYD's 8-bit variables could not do without overflowing. Operands are loaded into "registers" (groups of 2 or 4 consecutive variables, low byte first): A = mlA0..mlA3, B = mlB0..mlB3, C = mlC0..mlC3. The 16-bit operations use the low 2 bytes of each.

Since CYD literals are 8-bit, wide values are loaded byte by byte with the multiple assignment: SET mlA0 TO {226, 4} loads 1250 (= 0x04E2, low byte first).

Routine Effect
add16 / add32 A = A + B (wraps on overflow)
sub16 / sub32 A = A - B (wraps; use cmp to check first)
cmp16 / cmp32 mlCmp = 0/1/2 → A<B / A=B / A>B
shl16 / shl32 A = A << 1
shr16 / shr32 A = A >> 1
mul32 C = A * B (truncated to 32 bits)
mul1632 C(32) = A(16) * B(16) — never overflows (recommended for scores)
div32 A = A / B (quotient), C = A mod B (remainder)
print16 / print32 prints A in decimal (destroys A, B and C)

To divide by a 16-bit value, load it into B with mlB2 = mlB3 = 0 and use div32 (the quotient may be 32-bit). The 16-bit tier is ~2–4× faster; avoid mul/div inside very tight loops. There is a full example in examples/math_library.

Example: score = enemies × points + bonus = 1250 × 800 + 234567.

[[
    INCLUDE LIB "math16_32.cyd"
    SET mlA0 TO {226, 4}       /* A = 1250 */
    SET mlB0 TO {32, 3}        /* B = 800  */
    GOSUB mul1632              /* C = 1000000 (no overflow) */
    SET mlA0 TO {@mlC0, @mlC1, @mlC2, @mlC3}   /* A = C */
    SET mlB0 TO {71, 148, 3, 0}   /* B = 234567 */
    GOSUB add32                /* A = 1234567 */
]]Score: [[ GOSUB print32 ]]

strings.cyd — text strings

Keyboard input, printing and handling of character strings stored in consecutive variables (using [@ptr] indirection), terminated by 0. Before calling, set the registers: stBase (index of the first variable of the buffer), stLen (capacity in characters) and, for copy or compare, stB2 (index of the second buffer).

Routine Effect
strClear zero-fills the buffer
strLen counts characters up to the 0 or the end → stRes
strPrint prints the buffer (CHAR) up to the 0 or the end
strInput reads a string from the keyboard (cursor, ENTER ends, DELETE erases)
strCopy copies the stBase buffer → stB2 (stLen bytes)
strCmp compares stBase with stB2 → stRes = 0/1/2 (less/equal/greater)

Example: ask for a name and greet.

[[
    INCLUDE LIB "strings.cyd"
    SET stBase TO 0 : SET stLen TO 16
    GOSUB strInput
]]Hello, [[ GOSUB strPrint ]]!

There is a full example in examples/strings_library.

sprites.cyd — masked sprites

Draws parts of the picture loaded in the buffer (PICTURE) over the screen without erasing the background. Each sprite has its mask: the silhouette of what it covers, drawn in ink in the same picture. The core is native Z80; if you call none of its routines, nothing is included.

The sprite and its horizontal position are measured in characters (8x8), as in BLIT. The vertical position is sprDY characters plus sprPY pixels: with sprPY at 0 everything goes by characters; to move a sprite pixel by pixel, leave sprDY at 0 and use sprPY as the Y in pixels (0..191). Whatever goes off the right or bottom of the screen is clipped. Parameters (variables 200..211):

Variables Meaning
sprX, sprY sprite's corner in the buffer
sprW, sprH width and height
sprMX, sprMY its mask's corner in the buffer
sprDX, sprDY position on screen, in characters
sprPY pixels added to sprDY
sprAttr 0: the screen's colors don't change; 1: the sprite puts its colors in the cells where its mask isn't empty (with sprPY, in the cell where most of it falls)
sprSlot sprSave / sprRestore slot (0..3)
sprErr 1: what sprSave had to save doesn't fit in the slot; 2: no such slot
Routine Effect
sprDraw screen = (screen AND NOT mask) OR sprite
sprXor screen = screen XOR sprite (no mask; doing it again erases it)
sprSave saves, in slot sprSlot, what is on screen where the sprite would go
sprRestore puts what slot sprSlot saved back where it was

Example: a 2x3-character character over a scene.

[[
    INCLUDE LIB "sprites.cyd"
    PICTURE 1 : DISPLAY 1        /* the scene, on screen */
    PICTURE 2                    /* the sprite sheet, into the buffer (not shown) */
    SET sprX TO 0 : SET sprY TO 0 : SET sprW TO 2 : SET sprH TO 3
    SET sprMX TO 2 : SET sprMY TO 0      /* the mask, to its right */
    SET sprDX TO 14 : SET sprDY TO 10
    GOSUB sprDraw
]]

Moving sprites. Each step: sprSave saves the background where the sprite is going, sprDraw draws it and, before moving it, sprRestore puts the background back (where it was, even if you have already changed sprDX/sprDY). With several sprites, each uses its own slot (sprSlot) and they are restored in the reverse order they were saved (the last saved, first): that way the background stays right even when they cross. To animate them, point sprX/sprY at the next frame of the sheet each step.

There is a complete example in examples/sprites: a character walking by characters and a ball bouncing pixel by pixel, each in its own slot.

There are 4 slots of 8 characters (a 2x3 sprite that isn't aligned touches 2x4 cells); the SPR_SLOTS and SPR_SLOT_CHARS constants in the file change them, at 9 bytes per character. In all it takes about 1030 bytes (730 of code and 300 of slots), only when used; on 128K and +3 it goes in a paged bank, outside the main memory.

sprites_px.cyd — masked sprites with pixel X

The sprite and its horizontal position are measured in characters; sprites_px.cyd is the same library with one more variable, sprPX (212): the pixels added to sprDX. Everything else (routines, parameters and slots) works the same. To move a sprite pixel by pixel horizontally, leave sprDX at 0 and use sprPX as the X in pixels (0..255). With sprAttr at 1, the colors go to the column where most of each cell falls.

It is a separate library because pixel X has a cost. When it doesn't fall on a character boundary, each row of the sprite and of its mask is shifted as it is drawn, and a 2x3 sprite takes almost half a frame instead of 0.2. It also takes about 490 bytes more: the code, two row buffers and slots of 12 characters instead of 8 (a 2x3 sprite aligned neither in X nor in Y touches 3x4 cells). Include only one of the two: they share variables and labels.

[[
    INCLUDE LIB "sprites_px.cyd"
    PICTURE 1 : DISPLAY 1
    PICTURE 2
    SET sprX TO 0 : SET sprY TO 0 : SET sprW TO 2 : SET sprH TO 3
    SET sprMX TO 2 : SET sprMY TO 0
    SET sprDX TO 0 : SET sprPX TO 117    /* X = 117 pixels */
    SET sprDY TO 0 : SET sprPY TO 80     /* Y = 80 pixels */
    GOSUB sprDraw
]]

There is an example in examples/sprites_px: the examples/sprites one with the character walking pixel by pixel.


Native routines (IMPORT / CALL)

For jobs the virtual machine cannot do — reading or writing a hardware port, touching an arbitrary memory address, or a tight piece of number-crunching that needs to be fast — you can write a small routine in Z80 assembly and call it from your script.

Advanced, use at your own risk. This runs your own native code with no sandbox: a bug in the routine can hang or crash the machine, exactly like the BeepFx or WyzTracker code you already trust. If you are not comfortable with Z80 assembly, you do not need this feature.

Two keywords are involved:

[[
    IMPORT beeper FROM "routines/beeper.asm"   /* declare (compile-time) */
    ...
    CALL beeper                                /* run it (at runtime) */
]]
  • IMPORT name FROM "file.asm" registers a native routine under name. It is a compile-time declaration (like DECLARE or CONST, not like INCLUDE, which includes CYD source). A relative path is looked for next to the .cyd file with the IMPORT, then next to your main .cyd script, and then in the folders given with --import-path.
  • CALL name runs the routine. Think of it as the native counterpart of GOSUB: GOSUB label calls a subroutine written in CYD, CALL name calls one written in Z80.
  • CALL name as a value: inside an expression (SET x TO CALL name, IF CALL name = 1 THEN ..., PRINT CALL name + 1), the routine runs and its result is the byte it leaves in register A when it returns.

Writing the routine

You write only the body of the routine — no ORG, no directives, no SAVEBIN. The compiler frames it, assembles it in isolation (so a mistake in your file produces a clean error attributable to your file, without breaking the engine build) and places it in memory for you, re-assembling it at its final address so absolute addresses just work.

The contract (ABI) is deliberately small:

  • The routine is entered with DE = FLAGS, the base address of the 256-byte variable array. Every CYD variable n is the byte at FLAGS + n.
  • Inputs and outputs travel through variables. The script puts arguments in variables with SET, calls the routine, and reads results back with @var. The routine reads and writes them at FLAGS + n. A routine that returns a single byte can leave it in A and be used as a value (SET x TO CALL name); with a plain CALL, A is ignored.
  • It must end with RET and must not jump into the engine's internals on its own. It may freely use AF/BC/DE/HL/IX/IY (the engine saves and restores IX/IY, which it relies on internally). For what you do need — reaching arrays across banks, or calling another native routine — there are resident services documented below (CYD_PEEK/CYD_POKE, CYD_ARR_MAP/CYD_ARR_FLUSH, CYD_CALL).
  • It must fit in one 16 KB bank and must not leave the hardware in a state that breaks the engine on return (if it changes paging via $7FFD, it must restore it).

Example

[[
    IMPORT peek FROM "peek.asm"
    DECLARE 0 as addr_lo
    DECLARE 1 as addr_hi
    DECLARE 2 as result
    SET addr_lo TO 0 : SET addr_hi TO 0   /* address 0000h */
    CALL peek                             /* result <- byte at that address */
]]

with peek.asm (you write just this):

    ld a, (de)          ; DE = FLAGS -> A = FLAGS+0 = address low byte
    ld l, a
    inc de
    ld a, (de)          ; A = FLAGS+1 = address high byte
    ld h, a             ; HL = the address to read
    inc de              ; DE -> FLAGS+2
    ld a, (hl)          ; A = the byte at that address
    ld (de), a          ; FLAGS+2 = result
    ret

There is a full, runnable example in examples/import_demo.

Writing the routine inline (ASM … ENDASM)

You don't always want a separate file. You can write the body directly in the .cyd between ASM name and ENDASM, and call it with CALL as usual:

[[
    ASM put42
        ld a, 42
        ld (de), a          ; DE = FLAGS -> FLAGS+0 = 42
        ret
    ENDASM
    CALL put42
]]
  • The body is taken verbatim: ; comments, labels, 0x… numbers… all go to SjASMPlus without CYD interpreting them. You may indent the block however you like to line it up with the [[ ]]: CYD moves label (and EQU) lines to column 0 for you; just keep the instructions indented more than the labels.
  • The same ABI applies as with IMPORT (entered with DE = FLAGS, ends in RET) and the same CALL. ASM … ENDASM is just an IMPORT with the body inline. If SjASMPlus reports an error, CYD remaps it to your .cyd line.

Blocks with several entry points (EXPORTS)

A block can expose several routines that share private helpers and call each other with a plain call (they live in the same bank). Declare them with EXPORTS:

[[
    ASM matrix EXPORTS put_a, put_b
    put_a:
        ld a, 42
        jr store
    put_b:
        inc de
        ld a, 99
    store:
        ld (de), a          ; private, shared helper
        ret
    ENDASM
    CALL put_a             /* FLAGS+0 = 42 */
    CALL put_b             /* FLAGS+1 = 99 */
]]

Each EXPORTS name is a CALL target. The block is assembled and placed as one unit (the natural unit of a "library").

Reaching the engine's data

When it assembles your routine, CYD injects the addresses of the resident structures by name, so you don't have to guess them:

Symbol What it is
FLAGS base of the 256-variable array (same as DE on entry)
SCREEN_BUFFER_PXL / SCREEN_BUFFER_ATT the engine's image buffer (pixels / attributes)
VIDEO_PXL / VIDEO_ATT the physical Spectrum screen ($4000 / $5800)

So, for instance, ld hl, SCREEN_BUFFER_PXL gives you the image buffer directly.

Arrays

Your script's arrays (DIM) are reachable too. For each array <name> CYD injects:

Symbol What it is
ARR_<name> address of element 0
ARR_<name>_LEN element count
ARR_<name>_BANK physical bank it lives in, or $FF if resident

On 128K/+3 an array may live in a paged bank that your routine can't map without evicting itself. So access goes through resident services that do the paging for you (on 48K, or when the bank is $FF, they are direct access). All of them preserve BC/DE/HL/IX/IY (except the result):

  • CYD_PEEK — read a byte. In: A = bank, HL = address; out: A = byte.
  • CYD_POKE — write a byte. In: A = bank, HL = address, E = byte.
  • CYD_ARR_MAP — copy the whole array to a resident buffer and return a direct pointer so you can work without paging. In: A = bank, HL = ARR_<n>, BC = ARR_<n>_LEN; out: HL = working pointer.
  • CYD_ARR_FLUSH — write that buffer back to the array. Same input parameters. (Only one array mapped at a time.)

Example — increment element 3 of inv:

[[
    DIM inv(4) = {10, 20, 30, 40}
    ASM inc3
        ld a, ARR_inv_BANK
        ld hl, ARR_inv + 3
        call CYD_PEEK       ; A = inv[3]
        inc a
        ld e, a
        ld a, ARR_inv_BANK
        ld hl, ARR_inv + 3
        call CYD_POKE       ; inv[3] = inv[3] + 1
        ret
    ENDASM
    CALL inc3
]]

If you are going to touch many elements, CYD_ARR_MAP + CYD_ARR_FLUSH is faster: map once, walk the pointer directly, and flush at the end.

Calling another native routine (USES + CYD_CALL)

Two routines in the same block (EXPORTS) call each other with a plain call. To call a routine in another block (which on 128K/+3 may be in another bank), use the resident trampoline CYD_CALL and declare whom you call with USES:

[[
    ASM greeter EXPORTS greet
    greet:
        ld a, 55
        ld (FLAGS+1), a
        ret
    ENDASM
    ASM main USES greet
        ld a, 11
        ld (FLAGS), a
        ld a, RT_greet      ; index injected by USES
        call CYD_CALL       ; calls 'greet', whatever bank it is in
        ret
    ENDASM
    CALL main               /* FLAGS = [11, 55] */
]]
  • USES a, b, … declares the callees; for each one CYD injects an RT_<name> index.
  • ld a, RT_<name> : call CYD_CALL runs that callee. It is entered with DE = FLAGS (like a script CALL) and CYD does the paging for you.

Calling engine services (CYD_SYSCALL)

Some things are done by the engine, not the virtual machine: printing a character or reading the keyboard. Your routine can ask for them through a single entry point, CYD_SYSCALL, passing the service number in A (the SVC_* constants CYD injects) and the arguments in registers:

[[
    ASM greet
        ld e, 72            ; code for 'H'
        ld a, SVC_PRINT_CHAR
        call CYD_SYSCALL    ; prints 'H' at the cursor
        ret
    ENDASM
    CALL greet
]]

Available services (a small set to start with; it will grow):

Service In / out
SVC_PRINT_CHAR E = character — prints it at the cursor (advances it, honors ink/paper/window)
SVC_WAIT_KEY waits for a key → A = code
SVC_INKEY reads a key without waiting → A = code (0 if none)

The service numbers are a stable contract: even if the interpreter is rewritten internally, your routines keep working without recompiling. Treat CYD_SYSCALL like any call (it may clobber registers); in particular, do not touch IY before it.

Unused routines

An IMPORT/ASM routine that nobody calls is not assembled and takes no memory: CYD drops it automatically. So you can keep a "library" of routines and pay only for the ones you actually use. (The resident services above — the array broker, CYD_CALL, CYD_SYSCALL — are likewise removed from the engine if no routine uses them.)

There is an example with ASM, EXPORTS, arrays and CYD_CALL in examples/inline_asm.

Supported targets

Native routines work on all six targets (48K, 128K, +3, esxdos, mld and mld128). On the 128K, +3, esxdos and mld128 the routine is placed in a paged RAM bank and the engine pages it in around the CALL automatically. On the strict 48K mld (Dandanator, no banks) the routine is copied from flash to resident RAM at boot — just like a DIM array — and runs from there, so it also supports self-modifying routines or ones with their own DEFS scratch. If it does not fit in the resident RAM, compilation aborts with a clear error.


Variables and numeric expressions

Numeric constant values can be expressed in base 10 by default, in hexadecimal with the prefix 0x, or in binary with the prefix 0b. For example, 240 would be decimal, 0xF0 in hexadecimal, and 0b11110000 in binary.

There are 256 one-byte containers (from 0 to 255) available to the programmer to store values, perform operations, and compare them. They constitute the state of the program. From this point on, they may be called variables or flags interchangeably throughout this document.

To refer to a variable in a numeric expression, the number must be preceded by the @ character. But it is possible to give a meaningful name to variables using the DECLARE command as follows:

[[
DECLARE 7 AS InkColor
INK @InkColor
]]

It should be noted that a variable cannot be declared twice, nor can there be labels and variables with the same names, but synonyms are allowed as follows:

[[
DECLARE 10 AS SomeName
DECLARE 10 AS OtherName
]]

Thus, both SomeName and OtherName will serve to identify variable 10. Keep in mind that despite having different names, they are the same variable.

To assign values to a variable, we use the command SET varId TO varexpression, as follows:

[[
SET 0 TO 1 /* Set the variable zero to 1 */
SET variable TO 2 /* Set the variable named variable to 2 */
SET variable2 TO @variable + 2 /* Set the variable named variable2 to two plus the value of the variable named variable */
SET variable2 TO @variable2 - (@variable + 2) /* Allows parentheses */
]]

We also now have the following synonym with LET varId = varexpression, so the previous examples could be rewritten like this:

[[
LET 0 = 1 /* Set the variable zero to 1 */
LET variable = 2 /* Set the variable named variable to 2 */
LET variable2 = @variable + 2 /* We set the variable called variable2 to two plus the value of the variable called variable */
LET variable2 = @variable2 - (@variable + 2) /* Allows parentheses */
]]

As you can see, a variable can be assigned the value of a mathematical expression composed of numbers, functions and variables. As already indicated, variables within a numeric expression, that is, the right side of an assignment, must always be preceded by the @ character.

The available operators are:

  • Addition: SET variable TO @variable + 2
  • Subtraction: SET variable TO @variable - 2
  • Binary "AND": SET variable TO @variable & 2
  • Binary "OR": SET variable TO @variable | 2
  • Binary "NOT" or bit complement: SET variable TO !@variable
  • Bit shift left: SET variable TO @variable << 2
  • Bit shift right: SET variable TO @variable >> 2

Additionally, LET supports shorthand operators to modify a variable in place:

  • Increment: LET variable += 2 (equivalent to LET variable = @variable + 2)
  • Decrement: LET variable -= 2 (equivalent to LET variable = @variable - 2)

These also work with indirection and arrays: LET [variable] += 1 and LET myArray(0) += 1.

The result of a numeric expression cannot be greater than 255 (1 byte) or less than zero (negative numbers are not supported). If either limit is exceeded when performing the operations, the result will be adjusted to the corresponding limit, that is, if an addition exceeds 255, it will be adjusted to 255 and a subtraction that gives a result less than zero will be set to zero.

One thing to note is that binary operators are not the same as the logical operators of conditional expressions described below. An & is not the same as an AND. Binary operators perform the corresponding operations on the bits of the variable.

Most commands accept numeric expressions in their parameters, for example:

[[
INK 7
INK @7
]]

The first command will set the text color to white (color 7), while the second will set the text color to the value contained in variable number 7. Combining all of the above, you could do:

[[
INK 3+4
INK @Var-1
]]

Check the commands reference to find out which commands accept them.

Finally, there are a number of special commands called functions. These commands cannot be used on their own, but must be used within a numeric expression, since they return a value to be used within it.

  • RANDOM(expression): Returns a random number between 0 and the value specified in expression.
  • RANDOM(): Returns a random number between 0 and 255. This is equivalent to RANDOM(255).
  • RANDOM(expression,expression): Returns a random number between the value indicated in the first parameter and the second, both inclusive.
  • INKEY(): Waits until a key is pressed and returns the code of the key pressed. (Only for keyboard).
  • KEMPSTON(): Returns the buttons pressed on a Kempston joystick connected to the Spectrum.
  • MIN(varexpression,varexpression): Limits the value of the first parameter to the minimum indicated by the second. That is, if parameter 1 is less than parameter 2, parameter 2 is returned; otherwise, parameter 1 is returned.
  • MAX(varexpression,varexpression): Limits the value of the first parameter to the maximum indicated by the second. That is, if parameter 1 is greater than parameter 2, parameter 2 is returned; otherwise, parameter 1 is returned.
  • YPOS(): Returns the current row the cursor is on in 8x8 coordinates.
  • XPOS(): Returns the current column the cursor is on in 8x8 coordinates (due to the nature of the variable-width font, the returned value will be the 8x8 column where the cursor is currently located).
  • LASTPOS(ID): Returns the index of the last position in the given array.

So, for example, SET variable_no TO RANDOM(6) assigns to the variable variable_no a random number from 0 to 6. And in the same way, we can operate with them: SET variable_no TO RANDOM(6) + @var + 1


Flow control and conditional expressions

To control the flow of execution, we have different commands, which I will now describe:

  • GOTO ID

Jumps to the label ID.

  • GOSUB ID

Subroutine jump, jumps to the label ID, but returns execution to the instruction after the GOSUB as soon as it finds a RETURN command.

  • RETURN

Returns to the point after the subroutine call (see GOSUB).

  • IF condexpression THEN ... ENDIF

If the conditional expression condexpression is true, the text is printed and the commands from THEN to ENDIF are executed.

  • IF condexpression THEN ... ELSE ... ENDIF

If the conditional expression condexpression is true, the text is printed and the commands from THEN to ELSE are executed. Otherwise, the text is printed and the commands from ELSE to ENDIF are executed.

  • IF condexpression THEN ... ELSEIF condexpression THEN [... ELSEIF condexpression THEN] ... ELSE ... ENDIF

If the conditional expression condexpression1 evaluates to true, the text is printed and the commands from THEN to ELSE are executed. Otherwise, the conditional expression condexpression2 is checked and, if it is true, the text is printed and the commands from ELSEIF to the ELSE or another ELSEIF are executed. Multiple ELSEIFs can be chained together until a final ELSE clause is reached, which is executed if none of the previous conditions have been met.

  • WHILE (condexpression) ... WEND

The text and commands up to WEND are repeated as long as the condition condexpression evaluates to true. Evaluation is performed at the beginning of each iteration.

  • DO ... UNTIL (condexpression)

The text and commands from DO to UNTIL are repeated as long as the condexpression condition evaluates to false. Evaluation is performed at the end of each iteration.

  • FOR variable = start TO end [STEP step] ... NEXT [variable]

Counted loop: the text and commands up to NEXT are repeated, running variable from start to end. STEP is optional and defaults to 1; it may be negative (STEP -2) to count down. The step must be a constant (not a variable or a CONST), because the compiler needs to know the loop direction. The counter variable is written bare (as in SET/LET); inside the body you read its value with @variable. NEXT may optionally carry the variable name (NEXT i), which must match. The start and end limits may be expressions (even variables); end is re-evaluated on every iteration. If the counter has already passed the limit at the start, the loop runs zero times (BASIC semantics). Example:

[[
DECLARE 0 AS i
FOR i = 1 TO 5           /* i = 1, 2, 3, 4, 5 */
  PRINT @i
NEXT
FOR i = 10 TO 0 STEP -2  /* count down: 10, 8, 6, 4, 2, 0 */
  PRINT @i
NEXT
]]

The counter is a byte (0..255). The loop is internally protected against byte overflow, so FOR i = 0 TO 255 and FOR i = 10 TO 0 STEP -1 work correctly (they do not become infinite loops). Do keep in mind, though, that the limits must fit in a byte.

As you can see, many of these commands are executed depending on whether a condition is met. For example:

[[IF @var = 0 THEN GOTO jump ENDIF]]

For the jump to be executed, the variable var must be equal to zero. This is what is called a conditional expression.

A condition is always a comparison between two numeric expressions:

  • Equal to: IF @variable = 0 THEN GOTO jump ENDIF
  • Greater than: IF @variable > 0 THEN GOTO jump ENDIF
  • Less than: IF @variable2 < @variable THEN GOTO jump ENDIF
  • Not equal to: IF @variable <> 0 THEN GOTO jump ENDIF
  • Less than or equal to: IF @variable <= 0 THEN GOTO jump ENDIF
  • Greater than or equal to: IF @variable >= 0 THEN GOTO jump ENDIF

In addition, conditions can be combined into conditional expressions using logical operations. For example:

[[IF (@variable = 0 AND @variable2 = 1) AND NOT @variable3 = 1 THEN GOTO jump ENDIF]]
  • Cond1 AND Cond2: True if both Cond1 and Cond2 are true.
  • Cond1 OR Cond2: True if either Cond1 or Cond2 is true.
  • NOT Cond1: True if the condition Cond1 is false.

Again, remember that the logical operators of conditional expressions are not the same as binary operators.

Also, for those with advanced programming knowledge, conditions are not "short-circuiting", that is, all logical operations and comparisons are evaluated until the end.


Assignments and indirection

We have already seen assignments and numerical expressions in their section, but we are going to explain in more detail how they work with indirection, which deserves a separate section.

Indirection is done by putting a numerical expression in single brackets, for example [@var+1]. What we are trying to say is that we are going to refer to the variable or variables with the number calculated by the numerical expression enclosed in brackets. Let's see it with examples:

  • SET var to [2+2]: indicates that we are going to assign to var the content of the variable 2+2, that is, 4. This is equivalent to SET var TO @4, but it allows us to reinforce the idea.
  • SET var TO [@index]: this is where it really becomes useful, since we are indicating that we are saving in var the content of the variable whose number corresponds to the content of the variable index. That is, we can dynamically change the variable to which we make the assignment.
  • SET var TO [@index+2]: indirection supports any numeric expression; this means that we save in var the content of the variable that corresponds to the content of index plus two.
  • SET [var] TO 0: Indirection can also be used on the left-hand side, and in this case, numeric expressions are not supported, only the number or the variable identifier if it has been declared. This means "assign zero to the variable whose index corresponds to the content of the variable var."
  • INK [@var]: Indirection is also supported by those commands that accept numeric expressions.
  • SET [@@var] TO 0: For completeness, since we operate with pointers, using @@ we have the complementary operation to indirection, that is, it returns the index number of a given variable, so in the example, the operation would be equivalent to SET var TO 0.

Using plain numbers with variables (e.g. @0) is not very useful. Its real use is with variable identifiers, such that if we have:

[[
DECLARE 20 AS var : DECLARE 10 AS index: SET index TO @@var : SET [index] TO 0
]]

We see that this allows us to initialize variables to be used for indirection with the identifier of another variable.

Indirection is a powerful tool that allows us to implement arrays in variables, but be careful, we only have 256! Also, we must not confuse them with the arrays described in the next section, which are of a different nature.

Finally, we can perform multiple assignments using the following construction:

[[
DECLARE 10 AS var
SET var TO {0, 1, 2, 3}
]]

This would be equivalent to:

[[
SET 10 TO 0
SET 11 TO 1
SET 12 TO 2
SET 13 TO 3
]]

That is, we can consecutively assign a sequence of values to a sequence of variables, starting with the variable indicated on the left side. This allows multiple values to be assigned consecutively.


Constants

During development, we may need to have values with a meaningful name. Just like with variables, we can name them with CONST name = value, and then use name instead. For example:

[[
CONST maxBalas = 10 /* we declare the constant maxBalas with value 10 */
PRINT maxBalas /* we print the value 10 */
]]

Unlike variables, we can use as many constants as we want, since during the compilation process they will be replaced by their corresponding value.

The name of the constant cannot match that of another variable, label or any of the commands.


Arrays or "sequences"

In the previous section we have described the use of indirection to use variables as an array, but CYD also has an alternative way of creating data arrays using the DIM command, such that with DIM name(size) we declare an array with name name and size size. The size of an array cannot be zero or greater than 256. We access each of the elements of the array with the notation name(pos), where pos is the position number of the element to be accessed within the array, starting from zero. Let's see it with examples:

[[
DIM myArray(5) /* We declare an array of 5 elements from 0 to 4 */
LET myArray(3) = 1 /* We assign 1 to position 3 of the array, which would be the fourth */
PRINT myArray(3) /* We print the value stored in position 3 */
]]

If we try to access a position outside the range, the engine will fail and give an error. To find out which is the last accessible position of the array, we have the LASTPOS function:

[[
DIM myArray(5) /* We declare an array of 5 elements */
PRINT LASTPOS(myArray) /* It would return 4 */
]]

Assigning initial values to an array can be done in the following way: DIM array_name(size) = {value1, value2, ...}. Following the previous example:

[[
DIM myArray(5) = {1, 2, 3, 4, 5} /* We assign values to the array */
PRINT myArray(1) /* This would print 2 */
]]

Uninitialized positions will always have a value of 0 by default, so we can have an array with more positions than values. The opposite would give us an error:

[[
DIM myArray(5) = {1, 2, 3} /* This is allowed */
DIM myArray(3) = {1, 2, 3, 4, 5} /* This would give an error */
]]

Finally, and as a convenience, we can leave the number of positions of the array empty when declaring it with values. The compiler will create an array with as many positions as there are elements in the initialization:

[[
DIM myArray() = {1, 2, 3} /* This is allowed, myArray would have 3 positions */
DIM myArray() /* This would give an error */
]]

This type of array has a series of limitations that must be taken into account when using them. The most obvious one is that they cannot have more than 256 elements, are one-dimensional and cannot be resized.

Another limitation is that you cannot save or retrieve data from these arrays using SAVE and LOAD directly. The only option is to move the array data to or from variables and perform save or retrieve operations on them.

Finally, if you modify the data in an array, you cannot retrieve the original values unless you make a copy to another array first.

Immutable data (DATA / READ / RESTORE / DATAEND())

When you need a read-only block of data (tables, maps, byte-by-byte packed text, sequences…), CYD offers the DATA mechanism, analogous to BASIC's. Unlike DIM arrays — which are writable and limited to 256 elements — DATA is immutable and forms a single global stream that can be up to 16 KB (over 16000 elements). Since it is never modified, it takes 0 bytes of RAM on Dandanator/MLD (it is read straight from flash).

Each DATA statement appends its bytes, in source order, to that global stream. They are read sequentially with READ, which uses the same bare destination as SET/LET:

[[
  DECLARE 0 AS v

  DATA 10, 20, 30      /* these five values form a single stream:  */
  DATA 40, 50          /* 10, 20, 30, 40, 50                       */

  READ v               /* v = 10, and the cursor advances     */
  READ [v]             /* indirect destination (index in v), like LET [v] */
]]

There is a single global cursor that starts at the beginning of the stream. RESTORE rewinds it to the start, and RESTORE label places it at the first DATA appearing after that label (same semantics as BASIC's RESTORE line; it reuses LABELs):

[[
  DECLARE 0 AS v

  DATA 11, 22, 33
  LABEL second
  DATA 44, 55

  RESTORE second       /* the cursor is placed at '44' */
  READ v               /* v = 44                       */
]]

The DATAEND() function returns 1 if the cursor has reached the end of the stream and 0 otherwise. It is useful to walk all the data with a loop (note it is a function, with parentheses, and to use it as a condition you compare it, e.g. DATAEND() = 0):

[[
  DECLARE 0 AS v

  DATA 65, 66, 67

  WHILE (DATAEND() = 0)  /* while we have not reached the end */
    READ v
    CHAR @v              /* prints the character A, B, C      */
  WEND
]]

Things to keep in mind:

  • DATA statements are not executed: they can be placed anywhere in the script (the compiler gathers them all and removes them from the code stream). Grouping them helps readability.
  • Endless tape: reading past the end automatically rewinds the cursor to the start of the stream (it is not an error). Use DATAEND() if you want to detect the end and stop.
  • Values are byte constants (they accept the same expressions and named constants as a DIM initializer).
  • If a program does not use DATA, the corresponding opcodes are stripped from the interpreter (zero cost).

Wide constants (WORD / DWORD / strings)

CYD works with bytes, but you often need to place 16-bit (0..65535) or 32-bit (compatible with the math16_32 library) values in memory, or the character codes of a string. That is what wide constants are for: values the compiler expands into a fixed sequence of consecutive bytes in little-endian order (low byte first). Everything happens at compile time: they add no runtime cost.

They can be used in three places: in DATA, in a DIM initializer and in LET/SET of a variable.

  • Auto-detection by magnitude (only in DATA and DIM): a value from 0 to 255 takes 1 byte, from 256 to 65535 takes 2 bytes, and 65536 upwards takes 4 bytes, automatically.
  • WORD and DWORD markers: force 2 or 4 bytes even if the value fits in fewer (WORD 5 = 2 bytes). WORD does not accept values larger than 16 bits and DWORD not larger than 32 bits.
  • Strings "...": expand to their character codes (no terminator; you know the length because you wrote it). A string must be closed on the same line and cannot contain " or ]]; an unclosed quote is reported as Unterminated string.
[[
  DATA WORD 1000, 5, "HI"          /* 2 bytes + 1 byte + 2 bytes */
  DIM table() = { DWORD 100000, 42 }   /* 4 bytes + 1 byte -> 5-byte array */
]]

Arrays stay byte by byte (byte-flat): there is no "wide" access to an array; you recompose the value yourself by reading the bytes you need (with math16_32 if you are going to operate on it).

In LET/SET, the width is always set by the keyword (WORD/DWORD) or the string; the bytes are written into the destination variable and the following consecutive ones. There is no auto-detection here (the number of variables used must be known at compile time, so a LET v = 1000 without a marker would still be 1 byte and would give an error because it does not fit):

[[
  DECLARE 0 AS score      /* uses variables 0 and 1 */
  DECLARE 2 AS name       /* uses variables 2 and 3 */
  LET score = WORD 1000   /* var 0 = low byte (232), var 1 = high byte (3) */
  LET name = "AB"         /* var 2 = code of 'A', var 3 = code of 'B'       */
]]

Only a direct destination is allowed (known consecutive indices): the LET [v] indirection cannot be used with wide constants.


Handy literals (character, ranges, repetition)

To avoid memorizing codes or writing long sequences by hand, CYD offers several literals the compiler expands at compile time (no runtime cost):

  • Character literal 'A' -> the glyph code of the character. Valid anywhere a number goes (DATA, DIM, LET, expressions, CASE...). E.g. LET key = 'A' is the same as LET key = 65.
  • Ranges {a..b} -> the byte sequence a, a+1, ..., b (or descending if a > b). The bounds are byte constants and accept characters: 'A'..'Z'. E.g. DIM count() = { 1..8 }.
  • Repetition { v REPEAT n } -> n copies of v (which may be a value, a wide constant, a string or a range). E.g. DIM buffer() = { 0 REPEAT 16 } (sixteen zeros).

Ranges and repetition only make sense in list contexts (DATA, DIM initializers), and combine with each other: DATA 255 REPEAT 4, 1..3, 'A'.


List of commands

Before describing the commands, let's briefly discuss the legend used:

  • ID is an identifier and is a string of numbers, letters or underscores that starts with a letter or an underscore. Accented letters and ñ are not allowed.
  • expression is a numeric expression without variables. It is a decimal or hexadecimal number, but simple arithmetic operations are also allowed and will be calculated at compile time.
  • varexpression, numeric expression as described in its corresponding section. It can contain variables with @ and indirections.
  • condexpression, conditional expression as described in its corresponding section. It consists of one or several comparisons with logical operations between them.
  • varID, variable identifier, can be an expression if we use its numeric index or an ID if we have declared it like this with DECLARE.

Here is the full list of commands:

INCLUDE "path/to/file.cyd"

Compile-time directive that inserts another .cyd file in the current source. It must be used inside [[ ]] blocks. It is resolved before parsing, supports nested includes, and prevents circular references.

LABEL ID

Declares the label ID at this point. All jumps with reference to this label will direct execution to this point.

#ID

Shortened version for declaring the label ID, such that #LabelId is the same as LABEL LabelId.

DECLARE expression AS ID

Declares the identifier ID as a symbol representing the variable expression instead.

CONST ID = expression

Declares the constant ID with the value of expression.

DIM ID(expression)

Creates an array named ID with as many elements as indicated by expression. The number of elements cannot exceed 256.

DIM ID(expression) = {expression, expression...}

Same as DIM ID(expression), but assigning comma-separated values. Elements may be byte constants, wide constants (WORD/DWORD or auto-detected) or strings; the array stays byte by byte (see Wide constants).

DATA expression, expression...

Appends the values to the global read-only immutable data stream, in source order. All DATA statements in the script form a single stream (16 KB max). They are not executed; the compiler extracts them from the code. Each element may be a byte constant, a wide constant (WORD/DWORD or auto-detected by magnitude) or a string; see Wide constants.

READ varID

Reads the next byte of the data stream into variable varID and advances the cursor.

READ [varID]

Same as READ varID, but the destination is the variable whose index matches the content of varID (indirect destination).

RESTORE

Rewinds the data stream cursor to the beginning.

RESTORE ID

Places the data stream cursor at the first DATA appearing after the ID label in the source.

DATAEND()

Returns 1 if the data stream cursor has reached the end, 0 otherwise.

GOTO ID

Jumps to the ID label.

GOSUB ID

Subroutine jump, jumps to the ID label, but returns to the next command when it encounters a RETURN command.

The interpreter keeps the return address on a stack with room for about 250 nested GOSUBs, and doesn't check it. So:

  • A subroutine must always end with RETURN. If it leaves with GOTO (for example, going back to the location), its return address stays on the stack; repeated a few hundred times, the stack runs into the variables' memory and the game hangs or resets.
  • A subroutine must only be reached with GOSUB, OPTION GOSUB or the THEN GOSUB of CHOOSE. If it is entered with GOTO, or by running into it from the code above (for example, by including a file of subroutines at the top without a GOTO that skips them), its RETURN has nowhere to return to.

The compiler also warns about a GOSUB to a label that never reaches a RETURN, such as a CHOOSE IF WAIT ... THEN GOSUB to an ordinary place of the game: that needs GOTO. Each warning shows up even when the script has another mistake of this kind, so you don't need to fix one to see the next.

The compiler follows the program's flow and warns about both cases (WARNING [CODEGEN]) with the line where they happen; --no-warn-gosub turns this off. To check it at runtime as well, build with --debug-stack (see Error codes).

RETURN

Returns to the point after the subroutine call (see GOSUB). If no GOSUB is pending, the result is unpredictable.

IF condexpression THEN ... ENDIF

If the conditional expression condexpression is true, the text is printed and the commands from THEN to ENDIF are executed.

IF condexpression THEN ... ELSE ... ENDIF

If the conditional expression condexpression is true, the text is printed and the commands from THEN to ELSE are executed. Otherwise, the text is printed and the commands from ELSE to ENDIF are executed.

IF condexpression1 THEN ... ELSEIF condexpression2 THEN ... ELSE ... ENDIF

If the conditional expression condexpression1 is true, the text is printed and the commands from THEN to ELSE are executed. Otherwise, the conditional expression condexpression2 is checked and, if it is true, the text is printed and the commands from ELSEIF to the ELSE or another ELSEIF are executed. Several ELSEIFs can be chained together until a final ELSE clause is reached, which is executed if none of the previous conditions have been met.

WHILE (condexpression) ... WEND

Text and commands up to WEND are repeated as long as the condexpression condition evaluates to true. Evaluation is performed at the beginning of each iteration.

DO ... UNTIL (condexpression)

Text and commands from DO to UNTIL are repeated as long as the condexpression condition evaluates to false. Evaluation is performed at the end of each iteration.

SELECT varexpression ... CASE value[,value...] ... [CASE ELSE ...] ENDSELECT

Multi-branch: evaluates varexpression and runs the CASE branch whose value matches (CASE 1, 2, 3 = several values for the same branch). CASE ELSE (optional) is the default branch. No fall-through: when a branch ends it jumps to the end (BASIC semantics). The subject is re-evaluated on each comparison (like the FOR limit), so keep it a variable or a side-effect-free expression. See flow control.

ENUM [name] { A, B=value, C, ... }

Declares sequential constants (like several CONST): auto-increment from 0, or from the last explicit value (C style). ENUM { NORTH, SOUTH, EAST } -> 0, 1, 2. The names are global constants; the optional name is only for grouping/readability. Explicit values must be numeric literals.

SWAP varID, varID

Exchanges the contents of two variables with no temporary. Bare operands (they are destinations). Each side may also be an indirect destination: SWAP [a], [b], SWAP a, [b].

FOR varID = varexpression TO varexpression [STEP expression] ... NEXT [varID]

Counted loop: runs varID from the start value to the end value. STEP is optional (defaults to 1) and must be a constant (it may be negative). The counter is a byte and is written bare; read it in the body with @varID. If the start has already passed the limit, it runs zero times. See the flow control section for details.

SET varID TO varexpression

Assigns the value of varexpression to the variable varID.

SET varID TO WORD expression / DWORD expression / "string"

Assigns a wide constant to varID and the following consecutive variables: WORD writes 2 bytes (little-endian), DWORD 4 bytes and a string its character codes. See Wide constants. (Also valid with LET varID = ....)

SET [varID] TO varexpression

Assigns the value of varexpression to the variable whose index corresponds to the contents of varID.

SET varID TO {varexpression1, varexpression2,...}

Assigns the value of varexpression1 to the variable varID, varexpression2 to the variable varID+1, and so on.

SET [varID] TO {varexpression1, varexpression2,...}

Assigns the value of varexpression1 to the variable whose index corresponds to the content of varID, varexpression2 to the variable whose index corresponds to the content of varID+1, and so on.

LET varID = varexpression

Assigns the value of varexpression to the variable varID.

LET [varID] = varexpression

Assigns the value of varexpression to the variable whose index corresponds to the content of varID.

LET varID = {varexpression1, varexpression2,...}

Assigns the value of varexpression1 to the variable varID, varexpression2 to the variable varID+1, and so on.

LET [varID] = {varexpression1, varexpression2,...}

Assigns the value of varexpression1 to the variable whose index corresponds to the contents of varID, varexpression2 to the variable whose index corresponds to the contents of varID+1, and so on.

LET varID += varexpression

Increments the variable varID by the value of varexpression. Equivalent to LET varID = @varID + varexpression.

LET [varID] += varexpression

Increments the variable whose index corresponds to the contents of varID by the value of varexpression.

LET arrayID(varexpression) += varexpression

Increments the element at position varexpression of the array arrayID by the value of the second varexpression.

LET varID -= varexpression

Decrements the variable varID by the value of varexpression. Equivalent to LET varID = @varID - varexpression.

LET [varID] -= varexpression

Decrements the variable whose index corresponds to the contents of varID by the value of varexpression.

LET arrayID(varexpression) -= varexpression

Decrements the element at position varexpression of the array arrayID by the value of the second varexpression.

END

Ends the adventure and restarts the computer.

CLEAR

Clears the defined text area.

CENTER

Sets the print cursor to the center of the line.

WAITKEY

Waits for the confirmation key to continue, displaying an animated wait icon. Ideal for separating paragraphs or screens.

OPTION GOTO ID

Creates an option point that the user can select (see CHOOSE). If the choice is confirmed, it jumps to the ID label. If the screen is cleared, the option point is deleted, and a maximum of 32 are allowed on a screen. Option points are accumulated, in the order they are declared, in a list that is traversed according to the keys pressed. If it is the selected option in the menu, the value returned by OPTIONVAL() is its position within the list of menu options.

OPTION GOSUB ID

Creates an option point that the user can select (see CHOOSE). If this option is confirmed, it jumps to label ID, returning after the CHOOSE when it encounters a RETURN. If the screen is cleared, the option point is deleted, and a maximum of 32 are allowed on a screen. Option points are accumulated, in the order they are declared, in a list that is traversed according to the keys pressed. If it is the selected option in the menu, the value returned by OPTIONVAL() is its position within the list of menu options.

OPTION VALUE(varexpression) GOTO ID

Works the same as OPTION GOTO ID, but we assign it a specific value that is returned by OPTIONVAL() if it is the chosen option in the menu.

OPTION VALUE(varexpression) GOSUB ID

Works the same as OPTION GOSUB ID, but we assign it a specific value that will be returned by OPTIONVAL() if it is the chosen option in the menu.

CHOOSE

Stops execution and allows the player to select one of the options currently on the screen. It will jump to the label indicated in the corresponding option.

Selection is made with the O and P keys for horizontal movement and Q and A for vertical movement. The corresponding directions on the Kempston joystick and the cursor keys can also be used.

When these keys are pressed, a pointer moves over the list of options, incrementing or decrementing the selected option according to the current configuration (see MENUCONFIG). By default, only vertical movement is configured with the Q and A keys or up and down on the Kempston joystick or cursor keys. The keys can be changed with MENUKEY, and MENUJOY adds a Sinclair or cursor joystick. It is the user's responsibility to place the option points on the screen in a manner consistent with the configured menu movement.

Remember that if you clear the screen before this command, you will lose the options and a system error will be given.

CHOOSE IF WAIT expression THEN GOTO ID

It works exactly the same as CHOOSE, but with the exception that a timeout is set; if it expires with no option selected, execution jumps to the ID label. The timeout has a maximum of 65535 (16 bits).

CHOOSE IF WAIT expression THEN GOSUB ID

The same, but when the time runs out it makes a subroutine jump to the ID label. Its RETURN, like that of an OPTION GOSUB option, comes back to the command after the CHOOSE. It is useful, for example, to make enemies attack if the player stands still.

CHOOSE IF CHANGED THEN GOSUB ID

It works exactly the same as CHOOSE, but a subroutine jump is made to the ID label each time the option is changed. Therefore, the routine should RETURN as soon as possible to avoid slowness. To know the chosen option and the total number of options in our menu, we can use the OPTIONSEL() and NUMOPTIONS() functions respectively.

OPTIONSEL()

Function that returns the currently selected option in the currently active menu. If we do not have an active menu, the result of this function is undefined.

NUMOPTIONS()

Function that returns the number of options in the currently active menu. If we do not have an active menu, the result of this function is undefined.

OPTIONVAL()

Function that returns the value assigned to the option selected and accepted in the menu; it is only updated when an option is chosen and the menu is exited.

CLEAROPTIONS

Deletes the options stored in the menu.

Configures the options menu. The parameters that can be configured are the following:

  • The first parameter determines the increment or decrement of the selected option number when we press P and O respectively (or the right and left cursor keys or the joystick).
  • The second parameter determines the increment or decrement of the selected option number when we press A and Q respectively (or the down and up cursor keys or the joystick).
  • The third parameter is the option that will be selected at the beginning when the menu is started with CHOOSE. The default value is zero (the first option registered).
  • The fourth parameter, if zero, does not show the selection icon and if non-zero, does.

The behavior when starting the interpreter is as if MENUCONFIG 0,1,0,1 had been executed. If you change the configuration for a menu, it is recommended to do so first, before setting the options.

If the fourth parameter is omitted, MENUCONFIG x,y,d is equivalent to MENUCONFIG x,y,d,1.

If the third and fourth parameters are omitted, MENUCONFIG x,y is equivalent to MENUCONFIG x,y,0,1.

Changes the key of a menu action. The first parameter is the action and the second one, the key:

Action What it does Key at start
0 up Q
1 down A
2 left O
3 right P
4 select SPACE

The key is the code INKEY returns, so the natural way to redefine it is to ask the player for it with INKEY(0). With 0, the action is left without a key. The previous key stops working.

It affects everything that waits for the player: the CHOOSE menus, WAITKEY, PAUSE and the page pause. Besides the keys set up, the cursor keys, ENTER to select and the Kempston joystick always work, so the player can never be left unable to use the menu.

An action outside 0 to 4 is a compile error if it is a constant; if it is calculated at run time, the statement does nothing.

The setting lives in the interpreter, not in the variables: it takes none, it is not saved with the game (SAVE, RAMSAVE) and the script cannot read it. It goes back to the keys at start when the program is loaded again.

[[
    /* tmp is any temporary variable */
    ]]Up: [[   LET tmp = INKEY(0) : MENUKEY 0, @tmp : CHAR @tmp : NEWLINE
    ]]Down: [[ LET tmp = INKEY(0) : MENUKEY 1, @tmp : CHAR @tmp : NEWLINE
]]

Chooses the joystick that goes through the keyboard, which works at the same time as the keys of MENUKEY:

Type Joystick Up Down Left Right Fire
0 none (at start)
1 Sinclair, port 1 9 8 6 7 0
2 Sinclair, port 2 4 3 1 2 5
3 cursor (Protek, AGF) 7 6 5 8 0

To the Spectrum, these joysticks are keys of the keyboard, and both types use the same keys with different meanings: that is why one has to be chosen. The Kempston joystick needs no MENUJOY: it is read separately and always works.

A type outside 0 to 3 is a compile error if it is a constant; if it is calculated at run time, it counts as 0. Like MENUKEY, it takes no variables and is not saved with the game.

[[
    OPTION GOTO NoJoy    ]]Keyboard or Kempston[[
    OPTION GOTO Sinclair ]]Sinclair[[
    OPTION GOTO Cursor   ]]Cursor[[
    CHOOSE
#NoJoy
    MENUJOY 0 : GOTO Menu
#Sinclair
    MENUJOY 1 : GOTO Menu
#Cursor
    MENUJOY 3 : GOTO Menu
]]

CHAR varexpression

Prints the character indicated by its corresponding number.

REPCHAR expression, expression

Prints the character indicated in the first parameter as many times as the number indicated in the second parameter. Both values have a size of 1 byte, that is, values from 0 to 255. Also, if the number of times is zero, the character will be repeated 256 times instead of none.

TAB expression

Prints as many spaces as indicated in the parameter. It is the equivalent of REPCHAR 32, expression, but it takes up less memory.

Prints the indicated numeric value.

PAGEPAUSE expression

Controls whether the player is prompted to continue after the current text area is completely filled, displaying an animated wait icon (parameter \<> 0) or scrolling up the text and continuing printing (parameter = 0).

INK varexpression

Defines the character color (ink). Values 0-7, corresponding to the Spectrum colors.

PAPER varexpression

Defines the background color (paper). Values 0-7, corresponding to the Spectrum colors.

BORDER varexpression

Defines the border color, values 0-7.

BRIGHT varexpression

Turns brightness on or off (0 off, 1 on).

FLASH varexpression

Turns flashing on or off (0 off, 1 on).

NEWLINE expression

Prints as many newlines as specified in the parameter (0 means 256).

NEWLINE

Equivalent to NEWLINE 1.

BACKSPACE expression

Moves the print cursor back by the number of positions specified in the parameter (0 means 256), deleting the character at the new position and replacing it with a space. The width used is that of the space character (number 32). Note that if characters of a different width from the space are used, this operation will not work properly.

BACKSPACE

Equivalent to BACKSPACE 1.

SFX varexpression

If a sound effects file has been loaded, plays the specified effect. If no such file has been loaded, the command is ignored.

PICTURE varexpression

Loads the image specified as the parameter into the buffer. For example, if 3 is specified, the file 003.CSC will be loaded. The image is not displayed, which allows control over when the file is loaded.

DISPLAY varexpression

Displays the current content of the buffer on the screen. The parameter indicates whether or not the image is displayed; a value of 0 does not display it, and any other value displays it. As many lines as have been defined in the corresponding image are displayed and the screen content will be overwritten.

BLIT varexpression, varexpression, varexpression, varexpression AT varexpression, varexpression

Copies a part of the image loaded in the buffer to the screen. The parameters define a rectangle within the buffer that will be copied to the screen from the indicated position.

The parameters, in order, are:

  • Source column of the rectangle to be copied from the buffer.
  • Source row of the rectangle to be copied from the buffer.
  • Width of the rectangle to be copied from the buffer.
  • Height of the rectangle to be copied from the buffer.
  • Destination column on the screen.
  • Destination row on the screen.

The unit of measurement used in all parameters is the 8x8 character and all of them accept variables.

WAIT expression

Pauses. The parameter is the number of "frames" (50 per second) to wait, and is a 16-bit number.

PAUSE expression

Same as WAIT, but with the exception that the player can abort the pause by pressing the confirmation key.

TYPERATE expression

Indicates the pause that must occur between the printing of each character. Minimum 0, maximum 65535. It is a wait loop, not frame based: each unit is 31 clock cycles (about 9 µs), so the pause shows from a few thousand up; with TYPERATE 10000 about 11 characters are printed per second.

Before version 1.7.0, TYPERATE used the two bytes of the value the other way round: TYPERATE 100 waited like today's TYPERATE 25600. To keep an old game at the same speed, multiply the value by 256.

MARGINS expression, expression, expression, expression

Defines the screen area where the text will be written. The parameters, in order, are:

  • Initial column.
  • Initial row.
  • Width (in characters).
  • Height (in characters).

Sizes and positions are always defined as if they were 8x8 characters.

FADEOUT expression, expression, expression, expression

Fades out the screen area defined by the parameters, which in order are:

  • Initial column.
  • Initial row.
  • Width (in characters).
  • Height (in characters).

Sizes and positions are always defined as if they were 8x8 characters.

AT varexpression, varexpression

Places the cursor at a given position, relative to the area defined by the MARGINS command. The parameters, in order, are:

  • Column relative to the origin of the text area.
  • Row relative to the origin of the text area.

Positions are assumed to be 8x8 character size.

FILLATTR varexpression, varexpression, varexpression, varexpression, varexpression

Fills a rectangle on the screen with a given attribute value. The pixels are not altered. The parameters, in order, are:

  • Column of origin of the rectangle to be filled.
  • Row of origin of the rectangle to be filled.
  • Width of the rectangle to be filled.
  • Height of the rectangle to be filled.
  • Value of attributes in Spectrum screen format, that is, a byte with bits in FBPPPIII format (F = Flash, B = Bright, P = Paper, I = Ink).

PUTATTR varexpression, varexpression AT varexpression, varexpression

Sets the attributes of an 8x8 character on the screen to given values. The pixels are not altered. The parameters, in order, are:

  • Value of attributes in Spectrum screen format, that is, a byte with bits in FBPPPIII format (F = Flash, B = Bright, P = Paper, I = Ink).
  • Mask to be applied to the attributes already existing on the screen. If the bit is zero, we keep the one on the screen, and if it is one we use the new value.
  • Column of the 8x8 character.
  • Row of the 8x8 character.

PUTATTR varexpression AT varexpression, varexpression

Equivalent to PUTATTR varexpression, 0xFF AT varexpression, varexpression

GETATTR (varexpression, varexpression)

Function that returns the attribute value of an 8x8 character on the screen, in Spectrum screen format, that is, a byte with bits in FBPPPIII format (F = Flash, B = Bright, P = Paper, I = Ink).

The parameters, in order, are:

  • Column of the 8x8 character.
  • Row of the 8x8 character.

ATTRVAL (expression COMMA expression COMMA expression COMMA expression)

Function that returns the attribute value in Spectrum screen format, that is, a byte with bits in FBPPPIII format (F = Flash, B = Bright, P = Paper, I = Ink), used in the PUTATTR and FILLATTR commands.

The parameters, in order, are:

  • Ink color (0 to 7).
  • Paper color (0 to 7).
  • Use of bright (0 or 1).
  • Use of flash (0 or 1).

ATTRMASK (expression COMMA expression COMMA expression COMMA expression)

Function that returns a mask value, used in the PUTATTR and FILLATTR commands.

The parameters, in order, are:

  • Ink mask. If the value is zero, we preserve the screen value, and if it is one we use the new value.
  • Paper mask. If the value is zero, we preserve the screen value, and if it is one we use the new value.
  • Bright mask. If the value is zero, we preserve the screen value, and if it is one we use the new value.
  • Flash mask. If the value is zero, we preserve the screen value, and if it is one we use the new value.

RANDOM(expression)

Function that returns a random number between 0 and the value specified in expression. The maximum value is 255.

RANDOM()

Function that returns a random number between 0 and 255. It is the equivalent of RANDOM(255).

RANDOM(expression, expression)

Function that returns a random number between the value indicated in the first parameter and the second, both inclusive.

INKEY(expression)

Function that returns the code of the key pressed. If the parameter is zero, it waits until a key is pressed. If it is non-zero, it returns the code of the key pressed at that moment, and zero if no key is pressed. Only responds to keyboard presses, not the joystick.

INKEY()

Function that waits until a key is pressed and returns the code of the key pressed. It is equivalent to INKEY(0).

KEMPSTON()

Function that returns the buttons pressed on a connected Kempston joystick. The following bits will be set to one if the corresponding button is pressed:

  • Bit 0 = Right.
  • Bit 1 = Left.
  • Bit 2 = Down.
  • Bit 3 = Up.
  • Bit 4 = Fire.

MIN(varexpression,varexpression)

Function that limits the value of the first parameter to the minimum indicated by the second. That is, if parameter 1 is less than parameter 2, parameter 2 is returned; otherwise, parameter 1 is returned.

MAX(varexpression,varexpression)

Function that limits the value of the first parameter to the maximum indicated by the second. That is, if parameter 1 is greater than parameter 2, parameter 2 is returned; otherwise, parameter 1 is returned.

YPOS()

Function that returns the current row in which the cursor is located in 8x8 coordinates.

XPOS()

Function that returns the current column where the cursor is located in 8x8 coordinates (due to the nature of the variable-width font, the value returned will be the 8x8 column where the cursor is currently located).

WINDOW expression

Switches to the "window" indicated by the parameter and supports up to 8 windows (from 0 to 7). By default, the initial window is 0. A CYD "window" is a screen area defined by its origin position, width, height, cursor position, and current attributes. This allows you to have different independent text areas on screen simultaneously without having to keep changing margins and cursor position to move from one area to another. Note that if windows overlap, the content of a window is not preserved if it is overwritten by another window.

CHARSET expression

Switches the character set used when printing text. With the parameter set to zero, the lower set (characters 0 through 127) is used, and with a non-zero value, the upper set (characters 128 through 255) is used. Remember that characters 0 through 32 and 127 through 143 are non-printable. This instruction does not affect REPCHAR and CHAR.

RANDOMIZE expression

Initializes the random number generator with the parameter value as the seed. Random number generation is not truly "random," and this can cause the generator to always return the same results if used in an emulator. Therefore, some source of randomness or entropy is needed. If we use this command with a value of zero as the parameter, the generator is initialized using the elapsed number of frames. This ensures randomness if it is executed in response to an arbitrary event, such as a key press. If we use a non-zero value, RANDOM() will always produce the same sequence of results, but it can be used as a procedural generator.

RANDOMIZE

This is equivalent to RANDOMIZE 0, which loads the random number generator with the elapsed number of frames.

TRACK varexpression

Loads into memory the Vortex Tracker file given as the parameter. For example, if 3 is specified, it will load the music track from file 003.PT3 (or 003.mus when using WyzTracker). If a track was previously loaded, it will be overwritten.

PLAY varexpression

If the parameter is non-zero and music is off, it plays the loaded music track. If it is currently playing, and 0 is passed as a parameter, it stops playing.

LOOP varexpression

Sets whether or not to repeat the music track after the end of the currently loaded music track. A value of 0 means false and non-zero means true. This command does not work with WyzTracker.

RAMSAVE varID, expression

Copies from the variable specified in the first parameter, as many variables as were specified in the second parameter (if zero, it is treated as 256) to temporary storage. Before copying, the temporary storage is filled with zeros, so that the variables not copied will have this value in the temporary storage.

RAMSAVE varID

This is the equivalent of RAMSAVE varId, 0, that is, it copies all the variables from the first parameter to the end to the temporary storage.

RAMSAVE

This is the equivalent of RAMSAVE 0, 0, that is, it copies all the variables to the temporary storage.

RAMLOAD varID, expression

This is the inverse operation of RAMSAVE. It copies from temporary storage to the variables, from the variable indicated in the first parameter and as many variables as those indicated in the second (if it is zero, it is treated as 256).

RAMLOAD varID

This is the equivalent of RAMLOAD varId, 0, that is, it copies all the variables from the first parameter to the end from the temporary storage.

RAMLOAD

This is the equivalent of RAMLOAD 0, 0, that is, it copies all variables from the temporary storage.

SAVE varexpression, varId, expression

Saves a series of variables to tape or disk. The first parameter indicates the file number to save, the second parameter is the initial variable of the range of variables to save, and the third parameter is the number of variables to save in that range (if zero, it is treated as 256). Anything in the temporary storage that was loaded with RAMSAVE will be removed, since it will be used to store the file temporarily.

  • In the case of disk, the file with the indicated three-digit number and .SAV extension will be saved. For example, the file for number 16 would be 016.SAV. If the file already exists, it will be overwritten.
  • In the case of tape, it will be saved to tape. The system will immediately start saving, so the author is responsible for telling the player that recording is about to start and that they must set the cassette unit (or equivalent) to record. The process can be interrupted with the BREAK key.

The result of the operation can be checked with the SAVERESULT() function.

SAVE varexpression, varId

This is the equivalent of SAVE varexpression, varId, 0, that is, it saves all variables from the second parameter to the end.

SAVE varexpression

This is the equivalent of SAVE varexpression, 0, 0, that is, it saves all variables.

LOAD varexpression

Loads a series of variables from tape or disk. The parameter indicates the file number to load, and the range of variables that was indicated when saving the file will be loaded. Anything in the temporary storage that was loaded with RAMSAVE will be deleted, since it will be used to store the file temporarily.

  • In the case of disk, the file with the indicated three-digit number and .SAV extension will be loaded. For example, the file for number 16 would be 016.SAV.
  • In the case of a tape, the first block without a header that is found will be loaded, so the user must advance the tape to the correct position. The system will immediately start loading, so the author is responsible for telling the player that loading is about to start and that they must set the cassette unit (or equivalent) to play. The process can be interrupted with the BREAK key.

The result of the load can be checked with the SAVERESULT() function.

SAVERESULT()

Function that returns the result of the last SAVE or LOAD operation. The possible values are the following:

  1. Success.
  2. Error when loading/saving on tape/disk. In the case of a tape, operation interrupted with BREAK.
  3. The saved game does not correspond to the current game.
  4. The selected slot of the saved game does not correspond to the one requested.
  5. Error checking the saved game file.

Any other value should be treated as undefined.

ISDISK()

Function that returns 1 if the target loads its resources (images, music, savegames) from a filesystem — that is, the +3 disk or the esxDOS SD card — and 0 otherwise (tape or Dandanator cartridge, where resources are resident in memory). Useful for the adventure to know whether media is loaded on demand.

LASTPOS(ID)

Function that returns the last accessible position of the given array. In effect, the size of the array minus 1.

Images

The engine supports a maximum of 256 images, subject to what fits on disk or in memory. They must be named with a 3-digit number, corresponding to the image number that will be invoked from the program. For example, image 0 should be called 000.scr, image 1 001.scr, and so on up to 255. Images must be in the Spectrum display format.

To display images, the compiler compresses the SCR format files from the Spectrum display into compressed files with a csc extension. The compression process can be lengthy, so the compiler keeps the compressed images in the cyd_cache folder of the output folder, and only compresses an image again when its scr file changes or when it has to be compressed differently (another number of lines, or another symmetry setting). The images folder is only read: a csc file you put there without its scr is used as an image already compressed.

You can configure the number of horizontal lines to display in the image using the corresponding parameter in the compiler to further reduce the size. Additionally, if the compiler detects that the right half of the image is a mirror image of the left half, it discards the right half to further reduce the size, although we can force this behavior with any image. To do this, create a file called images.json in the images directory.

The structure of the images.json file is as follows:

[
{
"id": 0,
"num_lines": 192,
"force_mirror": false
},
{
"id": 1,
"num_lines": 64,
"force_mirror": true
}
]

It is a list of records with the following fields:

  • id : This is the image number corresponding to this entry. In the example, "id":0 corresponds to the image 000.scr and "id":1 corresponds to the image 001.scr.
  • num_lines: Indicates the number of lines to include in the compressed file. The minimum is 1 and the maximum (full screen) is 192.
  • force_mirror: With a value of true, we force the image to be considered symmetrical. This will cause the right half of the image to be discarded, and when it is decompressed in memory, the mirrored left half will be drawn in its place. Otherwise, this field must be set to false.

We must specify in the JSON as many records as images whose behavior we want to define. Images not defined in the images.json file will be treated with normal behavior, which is to use the number of lines defined with the -il parameter, or 192 by default, and to use mirroring only for images detected as symmetrical.

There are two commands required to display an image: the PICTURE n command will load image number n into a buffer. That is, if you type PICTURE 1, it will load the 001.CSC file into the buffer. Any operation on an image requires first loading it into the buffer. This is useful for controlling when the image should be loaded, as it will require waiting for the image to load from disk, in addition to allowing some time to decompress the image on both tape and disk. Therefore, it is recommended to run this command at an appropriate time, for example, at the start of a chapter. If we try to load an image that doesn't exist, we'll receive an error 1, and if we try to load an image whose file doesn't exist on disk, we'll generate a disk error 23.

To display an image loaded into the buffer, we use DISPLAY n, where n must be non-zero to execute. The image displayed will be the last one loaded into the buffer (if it exists). The image starts painting from the top left corner of the screen, drawing as many lines as were specified when the file was compressed, overwriting everything previously on the screen.

There is also an alternative method for displaying images: the BLIT command. This allows us to copy a fragment of the image onto the screen instead of the entire image, and also allows us to specify its position on the screen. The command format is BLIT xo, yo, width, height AT xd, yd, and you can find more details about it in its corresponding section. BLIT is more versatile than DISPLAY, but it is also slower, and it also requires an image to be loaded into the image buffer with PICTURE beforehand, and it will overwrite anything that was on the screen at the drawing position.


Sound effects

Adding sound effects with the beeper is very simple. To do this we have to create an effects bank with the BeepFx utility. We must export the effects file as an assembly file using the File->Compile option from the top menu. In the floating window that appears, we must make sure that we have Assembly and Include Player Code selected; the rest of the options are irrelevant, since the compiler will modify the source file to embed it in the interpreter.

To invoke an effect, we use the command SFX n, where n is the number of the effect to be played. If this command is called without an effect file loaded, it will be ignored and execution will continue.

Calling an effect number that does not exist in the included file is not handled, so it is the author's responsibility to take care of this, since the behavior in that case is unpredictable.

The effects go inside the interpreter, and the interpreter must fit in 32 KB on 48K and in 16 KB on the other targets (from $8000 to $BFFF, as the banks are paged in at $C000). A large bank of effects may not fit on 128K even if it fits on 48K, as happens to the CYD_presents example. If the interpreter does not fit, the compiler says how much the effects, the music player, the abbreviations, the character set and the rest take, so you know what to cut:

ERROR: The interpreter takes 22272 bytes and on 128k it must fit in 16384 (16 KB):
  Sound effects (-sfx)   : 12410 bytes
  Text abbreviations     :    28 bytes
  Character set          :  2304 bytes
  Rest of the interpreter:  7530 bytes
  With -trim, the code of the commands the game does not use is left out.

Vortex Tracker music

The CYD engine allows you to play music modules created with Vortex Tracker in PT3 format. Its operation replicates the image loading mechanism; that is, modules must be named with three digits representing the track number that the interpreter will load with the TRACK command. For example, if the interpreter encounters the TRACK 3 command, it will search for the track in the 003.PT3 file and load the module into memory for playback. Similarly, the maximum number of modules that can be loaded is 256 (from 0 to 255), and the module cannot exceed 16 KB for tape and 8 KB for +3.

Once a module is loaded, it can be played with the PLAY command. As indicated in the command reference, if the parameter is non-zero, the module will be played; if it is equal to zero, playback will stop.

When the end of the module is reached, playback will automatically stop, but we can change this behavior with the LOOP command. Again, as indicated in the reference, if the parameter is equal to zero, playback will stop when the end is reached, as indicated above. However, if the parameter is non-zero, the module will restart from the beginning.


WyzTracker music

CYD also allows you to play music modules created with WyzTracker v2.0. It works similarly to Vortex Tracker melodies and images; module file names must be three-digit numbers from 0 to 255, so with TRACK 3, we would load the corresponding 003.mus module.

Once a module is loaded, it can be played with the PLAY command. As indicated in the command reference, if the parameter is non-zero, the module will play; and if it is equal to zero, playback will stop.

Unlike with Vortex Tracker modules, the LOOP command is not fully supported, as the modules themselves define whether they will loop or not.

Due to the peculiarities of the WyzTracker format, several considerations must be taken into account that will affect the use of the engine with this music player:

  • All modules must share the same instruments. The instrument file must be named instruments.asm and must be stored with the module files in the TRACKS directory.
  • The entire bank 1 of the Spectrum's memory will be reserved, where the player code, instruments, and melodies will be stored. This means that 16 KB less will be available for the tape version, and 8 KB less for the +3 version.
  • The different melodies will be compressed to save space, and each time one is loaded, it will be decompressed into the remaining space in bank 1. The compiler will generate an error if any of the included melodies do not fit in this remaining space.
  • Sound effects are not supported.

How to generate an adventure

The first thing to do is to generate a script for the adventure in any text editor, using the syntax described above. It is HIGHLY recommended to write the script before programming the logic, since it is important to have the text outlined beforehand to ensure proper compression (more details later).

It is important that the file is encoded in UTF-8, but it must be taken into account that characters over 128 will not be printed correctly and only the characters specific to Spanish are allowed, indicated in the Character set section, which will be converted to the codes indicated there.

Once we have the adventure, we use the CYDC compiler to generate a DSK or TAP file. The compiler looks for the best abbreviations to compress the text as much as possible. The process can be very long depending on the size of the adventure. That is why it is important to have the adventure outlined beforehand, to carry out this process at the beginning. We will compile the file with the parameter -T, so that with -T abbreviations.json, for example, we will export the abbreviations found to the file abbreviations.json.

From this point on, if we run the compiler with the parameter -t abbreviations.json, it will not search for abbreviations and will use the ones we had already found before, so the compilation will be almost instantaneous. When we consider that the adventure is finished, we can perform a new search for abbreviations to try to achieve a little more compression.

To add sound effects, images and melodies, see the corresponding sections.

The process is quite simple, but it has some dependent steps, so CYD includes tools that do all of it for us: the make_adventure.py program, the make_adv.cmd (Windows) and make_adv.sh (UNIX) scripts that run it, and a graphical interface. All of them work on a project.

Projects

Each adventure lives in its own folder: the project. CYD's own folder (the one with make_adventure.py and make_adv.cmd) can't be a project, but any other folder can, wherever it is: so a game doesn't have to be copied when CYD is upgraded, and several games can be worked on at the same time. The examples in examples/ are projects too.

A project has:

  • The main script (for example my_game.cyd) and the files it includes with INCLUDE, which can be in subfolders.
  • IMAGES/ with the images (000.scr, 001.scr...; see Images) and TRACKS/ with the music (see Vortex Tracker music).
  • SFX.ASM with the sound effects, if any (see Sound effects), and IMAGES/LOAD.scr with the loading screen, if any.
  • tokens.json with the abbreviations: it is created the first time the project is built. If you want to regenerate it (it's recommended to do so when you're running out of memory or are finishing the adventure), delete it and the next build will search for them again.
  • charset.json with the character set, if you want one other than the default one (see CYD character set converter).
  • cyd_project.ini, optional, with the project's settings.

The compiled files go to the project's OUTPUT/ folder: the .tap, the .DSK, the .MLD, or the files for the SD card with esxDOS (and the .map with --debug-errors). The compiler makes its intermediate files in OUTPUT/cyd_tmp/ and removes them when the build ends well (see --keep-temp), and it keeps the compressed images in OUTPUT/cyd_cache/, so it only compresses an image again when it changes. You can delete OUTPUT/ at any time.

To make a new project with a short game to start from, use the GUI's New… button or:

make_adventure.py --new my_game 128k

cyd_project.ini

All its settings are optional: without the file (or without a setting), the default ones are used. Paths are relative to the project's folder; the lines that start with ; are comments (a comment goes on its own line, not after a value). These are all of them, with their default values:

; My adventure
[project]
; the game's name; by default, the main file's without .cyd
name = my_game
; the main script; by default <name>.cyd, or the only .cyd there is
main = my_game.cyd
; 48k, 128k, plus3, esxdos, mld or mld128
target = 128k

[paths]
images = IMAGES
tracks = TRACKS
sfx = SFX.ASM
load_scr = IMAGES/LOAD.scr
tokens = tokens.json
charset = charset.json
output = OUTPUT
; more folders for INCLUDE, separated by ";"
include_paths =
; folders for INCLUDE LIB, before CYD's lib/
lib_paths =
; more folders for IMPORT
import_paths =

[options]
; lines of the images (-il)
image_lines = 192
; abbreviations (-l, -L, -s)
min_length = 3
max_length = 30
superset_limit = 100
; --token-format
token_format = auto
; -S
slice_texts = no
; -trim
trim_interpreter = no
; -dce
dead_code_elimination = no
; -code
show_bytecode = no
; --no-strict-colons
no_strict_colons = no
; -wyz
use_wyz = no
; -720
disk_720 = no
; -autoboot (esxdos)
autoboot = no
; -pause
pause_after_load =
; --max-errors
max_errors = 20
; no: --no-warn-unused
warn_unused = yes
; no: --no-warn-gosub
warn_gosub = yes
; no: --no-warn-shared-vars
warn_shared_vars = yes
; --debug-stack
debug_stack = no
; --debug-errors
debug_errors = no
; --keep-temp
keep_temp = no
; copy the main script to the project's BACKUP/ after each build
backup = no

The [options] are the compiler's options of the same name. The GUI writes this file for you, keeping your comments; you can also edit it by hand.

make_adventure.py (CLI helper)

make_adventure.py builds a project: it gathers its images, music, effects, loading screen, abbreviations and character set, runs the compiler with the project's settings, and leaves the result in its output folder. The make_adv scripts and the GUI use it.

make_adventure.py [options] [TARGET] [PROJECT]
  • PROJECT is the project's folder, or its main script (.cyd). The target and the project can be given in any order.
  • TARGET is one of 48k, 128k, plus3, esxdos, mld, mld128 (the last two are EXPERIMENTAL). Without it, the project's is used.

Main options: - --new FOLDER: makes a new project in FOLDER (a short game, IMAGES/, TRACKS/ and its cyd_project.ini) and exits. With -n NAME, its name; with a target, its target. - --describe: prints the project's folder, main script, name, target, output folder and backup setting as KEY=value lines, and exits (the make_adv scripts use it). - --check: only checks the script for errors, without building it (SjASMPlus is not needed). - --sjasmplus PATH: the SjASMPlus to use; by default, the one that comes with CYD. - --compiler PATH: the compiler to run instead of dist/cydc_cli.py (for development: src/cydc/cydc/cydc.py). - --lang {en,es}: language of the messages (also with the CYD_LANG environment variable). - -n, --name NAME, -o, --output-path, -img, --images-path, -trk, --tracks-path, -sfx, --sfx-asm-file, -scr, --load-scr-file, -tok, --tokens-file, -chr, --charset-file, -I, --include-path, --lib-path, --import-path: instead of the project's. - -T, -t, -C, -c: export or import the abbreviations or the character set from other files, instead of the project's tokens.json and charset.json. - -il, -l, -L, -s, -S, -trim, -dce, -code, --no-strict-colons, --max-errors, --token-format, --no-warn-unused, --no-warn-gosub, --no-warn-shared-vars, --debug-stack, --debug-errors, --keep-temp, -pause, -720, -autoboot, -wyz, -v: the compiler's options.

What is given on the command line wins over the project's cyd_project.ini, which wins over the default values.

On Windows it runs with the Python that comes with CYD, for example:

dist\python\python make_adventure.py --new ..\my_game
dist\python\python make_adventure.py ..\my_game
dist\python\python make_adventure.py plus3 examples\test

The compiler's messages say where each problem is, with the path of the file relative to the project: ERROR [PARSER] chapters/chapter 1.cyd:12:5: Syntax error: ....

Windows version

The make_adv.cmd script builds a project and, if you want, runs it in an emulator and makes a backup copy of the script. Give it the project's folder (or its main script), and optionally a target:

make_adv.cmd ..\my_game
make_adv.cmd examples\test 48k

You can also drag the project's folder (or its .cyd) onto make_adv.cmd in the file explorer.

The game's settings are in its cyd_project.ini. The variables in the script's header are for your computer:

REM The project to compile when none is given: the folder of the game (or its
REM main .cyd file). Relative to this script's folder, or absolute.
SET PROJECT=

REM Target platform, instead of the project's. Empty: the project's.
SET TARGET=

REM Name of the game, instead of the project's (empty: the project's).
SET GAME=

REM Extra parameters for make_adventure.py (optional)
SET CYDC_EXTRA_PARAMS=

REM Run emulator after successful compilation (none/internal/default)
SET RUN_EMULATOR=none

REM Path to zesarux.exe (internal). Empty: .\tools\zesarux\, the newest .\tools\ZEsarUX*\ or the PATH
SET ZESARUX_PATH=

REM Backup the main .cyd file after compilation, to the project's BACKUP folder
REM (yes/no; empty: the project's "backup" setting)
SET BACKUP_CYD=

REM Maximum number of backup files to keep (0 = unlimited)
SET BACKUP_MAX_FILES=0
  • The variable PROJECT is the project that is compiled when the script is run without one (for example, with a double click).
  • The variable TARGET is the output system and format, if you want one other than the project's: -- 48k: Generates a TAP file for Spectrum 48K, without AY music support. -- 128k: Generates a TAP file for Spectrum 128K. -- plus3: Generates a DSK file for Spectrum +3, with higher capacity and dynamic loading of resources. -- mld (EXPERIMENTAL): Generates a strict 48K (non-banked) MLD file for Dandanator. -- mld128 (EXPERIMENTAL): Generates an MLD file for Dandanator targeting Spectrum 128K. The RAM banks are used for music and for the DIM arrays (which must be writable); the rest of the adventure data (text/images/bytecode) is read directly from the cartridge slots. -- esxdos: Generates a boot TAP and the files for the SD card of a divMMC/divIDE with esxDOS (see cydc).
  • The variable CYDC_EXTRA_PARAMS is used to add extra parameters to make_adventure.py.
  • The variable RUN_EMULATOR indicates if we want the compiled program to be executed under an emulator with the following possible values: -- none: If we do not want it to do this. -- internal: Executes the compiled file under ZEsarUX (see ZESARUX_PATH). The +3 boots as a +3 with ROM 4.1, and esxdos as a 128K with divMMC and the project's output folder as its SD card. -- default: If the file extension is associated under Windows with another emulator, it will be executed with this one.
  • The variable ZESARUX_PATH is the path to zesarux.exe for internal. If left empty, it is looked for in .\tools\zesarux\, then in the .\tools\ZEsarUX*\ folder with the highest version (for example .\tools\ZEsarUX_windows-13.0\) and last on the PATH.
  • The variable BACKUP_CYD with the value yes makes a backup copy of the main script inside the project's BACKUP folder after each build. Each copy adds the date on which it was created to the file name. Empty, the project's backup setting is used.
  • The variable BACKUP_MAX_FILES limits how many backups are kept per game (0 means unlimited).

The script will produce a DSK or TAP file (depending on the target) in the project's output folder, which you can run with your favorite emulator. To speed up the work even more, download ZEsarUX and unpack it inside .\tools\ (it ends up as .\tools\ZEsarUX_windows-<version>\): with RUN_EMULATOR=internal it will run automatically after compilation with the appropriate options.

GUI compiler (make_adventure_gui)

For those who prefer a graphical interface instead of editing scripts or command lines, the make_adventure_gui tool provides a cross-platform GUI for compiling Choose Your Destiny adventures.

Features: - Cross-platform support (Windows, Linux, macOS with Python 3.11+) - Embedded Python on Windows (no separate Python installation needed) - Works on projects: New… makes one with a short game to start from, Open… opens the folder of a game, and Recent lists the last ones. The last project is opened again when the GUI starts. Without a project open, it explains what to do and has a How to migrate it button for games made with an older version - 30 configurable options including compilation targets, paths, abbreviation format, warnings about unused symbols and GOSUB/RETURN problems, a runtime check of the GOSUB stack (--debug-stack) and post-build actions - A Check button that looks for errors in the script without assembling it (--check), in about a second and without SjASMPlus - The project's settings are saved in its cyd_project.ini (only what isn't a default value, keeping your comments), and the GUI's own (SjASMPlus, emulator, appearance, recent projects) in cyd_gui_settings.ini, in CYD's folder. The settings of earlier versions (cyd_gui_settings.json) are moved there the first time; their game options are applied to the first project made with New… - Full internationalization support (English and Spanish) with runtime language switching via dropdown - Real-time compilation output display, with errors in red, warnings in orange and a summary at the end. Double-clicking a file.cyd:12 in the log opens the file at that line - A Run button, which opens the last compiled game in the emulator without compiling it again, and an Open folder button, which opens the output folder. The internal emulator is ZEsarUX: the GUI looks for it in tools/zesarux/, in the newest tools/ZEsarUX-<version>/ folder (where tools/build_emu_tools.sh leaves it on Linux) or on the PATH - A Game error field: with a game compiled with "Show where system errors happen" (--debug-errors), paste the SYSTEM ERROR message and it tells you the line of the script where it happened (see Error codes) - The compiler options are grouped (Optimization, Warnings, Debugging and Compatibility) and each one explains what it does when you hover over it - Auto-hide console window on Windows for clean startup

Launching the GUI:

Windows:

make_adventure_gui.cmd

Linux/macOS:

./make_adventure_gui.sh

Language selection:

The GUI supports Spanish and English languages with automatic detection from your system locale. You can change the language at any time using the Language dropdown in the header - all UI text will update immediately. The language preference is saved and restored automatically.

You can also pre-set the language with the CYD_LANG environment variable before launching:

REM Windows
set CYD_LANG=es
make_adventure_gui.cmd
# Linux/macOS
export CYD_LANG=es
./make_adventure_gui.sh

Configurable options:

Category Options
Project Folder (New…, Open…, Recent), Main file, Game name, Target (48k/128k/plus3/mld/mld128/esxdos)
Paths The project's (relative to its folder): output folder, images, tracks, SFX file, loading screen, tokens file, character set, INCLUDE / INCLUDE LIB / IMPORT folders. This computer's: SjASMPlus executable
Compiler Image display lines, Text abbreviation limits, Superset limit, Verbose mode, Slice texts between banks, Trim interpreter code, Show bytecode, Keep the intermediate files, Strict colon compatibility, Pause-after-load, WyzTracker support, 720 KB disk
Post-Build Run emulator after compilation, Backup the main script
Appearance Font size, Log font family/size, Log text/background colors

All compiled output files are placed in the project's output folder, and the GUI will display detailed compilation messages for debugging if needed.

Linux, BSDs and Unices version

The make_adv.sh script works like the Windows one: give it the project's folder (or its main script), and optionally a target:

./make_adv.sh ../my_game
./make_adv.sh examples/test 48k

The game's settings are in its cyd_project.ini. The variables in the script's header are for your computer:

# The project to compile when none is given: the folder of the game (or its
# main .cyd file). Relative to this script's folder, or absolute.
PROJECT=""

# Target platform, instead of the project's. Empty: the project's.
TARGET=""

# Name of the game, instead of the project's (empty: the project's).
GAME=""

# Extra parameters for make_adventure.py (optional)
CYDC_EXTRA_PARAMS=""

# Run emulator after successful compilation (none/internal/custom)
RUN_EMULATOR="none"

# Custom emulator command (used when RUN_EMULATOR=custom)
CUSTOM_EMULATOR_CMD="fuse \${OUTPUT_FILE}"

# Path to ZEsarUX (used when RUN_EMULATOR=internal). Empty: ./tools/zesarux/,
# the newest ./tools/ZEsarUX-<version>/ or the PATH
ZESARUX_PATH=""

# Backup the main .cyd file after compilation, to the project's BACKUP folder
# (yes/no; empty: the project's "backup" setting)
BACKUP_CYD=""

# Maximum number of backup files to keep (0 = unlimited)
BACKUP_MAX_FILES=0
  • PROJECT, TARGET, GAME, CYDC_EXTRA_PARAMS, BACKUP_CYD and BACKUP_MAX_FILES work as in the Windows version.
  • RUN_EMULATOR supports none, internal (ZEsarUX), or custom.
  • CUSTOM_EMULATOR_CMD is used when RUN_EMULATOR=custom.
  • ZESARUX_PATH defines the emulator executable path for internal mode. If left empty, it is looked for in ./tools/zesarux/, then in the highest ./tools/ZEsarUX-<version>/ folder (where tools/build_emu_tools.sh leaves it) and last on the PATH. As on Windows, the +3 boots as a +3 with ROM 4.1, and esxdos as a 128K with divMMC and the project's output folder as its SD card.

Migrating a game from an older version

Up to version 1.6.6, a game was made in CYD's own folder: its script, IMAGES, TRACKS and the rest were next to make_adv.cmd, which was configured with the GAME, TARGET, IMGLINES and LOAD_SCR variables. Now each game is a project in its own folder, and CYD's folder can't be one. To move a game:

  1. Make the project's folder, outside CYD's folder: with make_adventure.py --new FOLDER, with the GUI's New…, or just a new folder. (If you use --new or New…, delete the short game it makes.)
  2. Copy into it the game's script and the files it includes, IMAGES/, TRACKS/, SFX.ASM, tokens.json, charset.json and the loading screen (IMAGES/LOAD.scr by default).
  3. The libraries are now included with INCLUDE LIB: change INCLUDE "lib/strings.cyd" (or INCLUDE "../../lib/strings.cyd") to INCLUDE LIB "strings.cyd". The compiler suggests it when it doesn't find the old path.
  4. Move what the make_adv script had to the project's cyd_project.ini: GAME to name (or main, the script's name), TARGET to target, IMGLINES to image_lines, LOAD_SCR to load_scr, and each option of CYDC_EXTRA_PARAMS to its key in [options].
  5. The GUI's settings move on their own the first time it is opened.
  6. The compiled files are now in the project's OUTPUT/ folder.

Then build it with make_adv.cmd FOLDER (or dragging the folder onto make_adv.cmd), ./make_adv.sh FOLDER, or the GUI's Open….

Two changes of 1.7.0 show in an old game even if it builds without errors:

  • TYPERATE used the two bytes of its value the other way round. To keep the text at the same speed as before, multiply the value by 256: TYPERATE 100 becomes TYPERATE 25600. The compiler warns about values from 1 to 255.
  • The menus no longer select with the M key, but with SPACE or ENTER. If your game tells the player to use M, change that text or give it that key with MENUKEY.

Examples

A comprehensive set of examples is available to test the engine's capabilities and learn from them. Each example is designed to illustrate specific features of the CYD language, from basic concepts to advanced techniques.

Basic examples

examples\test - Engine introduction

Level: Beginner | Requirements: ZX Spectrum 128K

This is the perfect starting point. It demonstrates the fundamental concepts of the engine: - Options and navigation system: Implements a basic menu with OPTION and CHOOSE, showing how to create story branching. - Variables and operations: Uses variables to keep track of objects ("gamusinos") and perform basic arithmetic operations. - Music and sound: Includes a sample song in the TRACKS directory and demonstrates how to play music with PLAY and LOOP. - Images: Loads and displays SCR images from the IMAGES directory using PICTURE and DISPLAY. - Flow control: Illustrates the use of GOTO, LABEL, WAITKEY, and screen clearing with CLEAR.

This example is an expanded version of the code shown in the Syntax section of the manual.

examples\multicolumn_menu - Multi-column menus

Level: Beginner

Demonstrates how to organize options in multiple columns to create more compact and visually appealing menus: - Menu configuration: Uses MENUCONFIG 1,2 to define a menu with 1 row and 2 columns. - Visual layout: Shows how to place options side-by-side instead of vertically. - Use cases: Ideal for games with many options, character selection, inventories, etc.

examples\guess_the_number - Guessing game

Level: Beginner-Intermediate

A complete "guess the number" game that illustrates: - Random numbers: Generates a secret number using RANDOM(1, 32). - 6-column menu: Uses MENUCONFIG 1,6 to create a compact menu with 32 options (numbers 1 to 32). - Game logic: Compares the player's guess with the secret number and provides hints ("higher"/"lower"). - Variable management: Demonstrates how to use variables to store the secret number and player attempts.

This example is excellent for learning how to create simple interactive games.

examples\input_test - Keyboard input and arrays

Level: Intermediate

Technical example showcasing advanced data handling features: - Keyboard reading: Captures user input using INKEY() to read pressed keys. - Array simulation: Uses indirection with brackets [@ptr] to create and manipulate character arrays. - String management: Implements functions to print and edit text strings up to 16 characters. - Subroutines: Demonstrates the use of GOSUB and RETURN to create reusable functions (inputStr and printStr). - Interactive editing: Allows character deletion with DELETE and displays a blinking cursor.

This example is fundamental for understanding how to work with complex data and create custom input interfaces.

examples\menu_keys - Menu keys and joystick

Level: Basic

A short program that lets the player choose their controls: - Redefine the keys: asks for the key of each action with INKEY(0) and applies it with MENUKEY. - Choose the joystick: Sinclair (port 1 or 2) or cursor with MENUJOY; the Kempston joystick always works. - Go back to the original keys with MENUKEY. - Try the controls on a 3×3 grid of numbers (MENUCONFIG 1, 3) that says which one was chosen with OPTIONVAL().

The tutorial explains it step by step, in the chapter on the menu keys and joystick. The controls screen of examples\Delerict is a fuller version, which refuses repeated keys.

examples\math_library - 16/32-bit arithmetic

Level: Intermediate

Shows how to use the lib/math16_32.cyd library to work with numbers that exceed 8 (and 16) bits: - Including libraries: Adds the library with INCLUDE LIB at the start of the program. - Overflow-free multiplication: Uses mul1632 (C(32) = A(16) * B(16)) to compute a score. - 32-bit addition and printing: Combines add32 and print32 to show the result in decimal. - Loading wide literals: Uses the multiple assignment SET reg TO {b0, b1, ...}.

examples\strings_library - Text strings

Level: Intermediate

Shows how to use the lib/strings.cyd library for string input and handling: - Keyboard input: Reads a name with strInput (cursor, ENTER, DELETE). - Printing and length: Shows the string with strPrint and its length with strLen. - Configurable buffer: The author chooses where and how large the string is (stBase, stLen).

examples\windows - Multiple windows

Level: Beginner-Intermediate

Illustrates the window system for dividing the screen into different areas: - Window definition: Creates 4 windows using WINDOW and MARGINS. - Independent areas: Each window has its own text color (INK) and can be cleared independently. - Window navigation: Demonstrates how to switch between windows to print text in different areas. - Use cases: Useful for creating SCUMM-like interfaces, separating description from actions, displaying permanent stats, etc.

Intermediate examples

examples\ETPA_ejemplo - "Choose Your Own Adventure" book

Level: Intermediate | Requirements: Images in IMAGES

Complete implementation of the first paragraphs of a "Choose Your Own Adventure" book (CYOA): - Branching narrative: Demonstrates how to create a story with multiple paths and endings using OPTION and GOTO. - Configuration variables: Uses variables to control display modes (text-only vs. with images, image position). - Color system: Differentiates between narrative text and options using different ink colors. - Image management: Loads SCR images to illustrate key scenes in the adventure. - Modular structure: Organizes code with labels for each paragraph/section (LABEL s1, LABEL s2, etc.). - Screen subroutines: Uses GOSUB Pantalla to manage different presentation modes.

This example is ideal for creating text adventures or interactive gamebooks.

examples\include_demo - Multi-file organization

Level: Intermediate

Demonstrates the use of the INCLUDE system to organize large projects: - Code separation: The main file main.cyd includes other files with INCLUDE "file.cyd". - Modular organization: - variables.cyd: Variable declarations - common.cyd: Shared subroutines - intro.cyd: Introduction sequence - chapter1.cyd and chapter2.cyd: Independent chapters - Maintainability: Facilitates teamwork and complex project organization. - Reusability: Common subroutines can be shared between multiple chapters.

See the examples\include_demo\README.md file for more details.

examples\import_demo - Native routines (IMPORT / CALL)

Level: Advanced

Shows how to call a Z80 routine from a script with IMPORT / CALL: - Native code: a tiny peek.asm reads a byte from an arbitrary memory address, something the virtual machine cannot do on its own. - ABI: the routine is entered with DE = FLAGS and exchanges data through variables. - Advanced, at your own risk: see the "Native routines (IMPORT / CALL)" section above.

See the examples\import_demo\README.md file for more details.

examples\inline_asm - Inline assembly (ASM / EXPORTS / USES / CYD_CALL)

Level: Advanced

Write native Z80 routines inside the script itself with ASM … ENDASM and combine them into a small "library":

  • ASM / EXPORTS: one block with two entry points that share code, no separate file.
  • Array broker: the routines read a script DIM array by name (ARR_stats) with CYD_ARR_MAP, working even when the array is in a paged bank.
  • USES / CYD_CALL: one routine calls others in another block (and another bank) through the resident trampoline.
  • Dead code: routines nothing reaches are dropped automatically.

See the examples\inline_asm\README.md file for more details.

Advanced graphics examples

examples\blit - Introduction to BLIT

Level: Intermediate | Requirements: Images in IMAGES

Introduction to the BLIT command for copying sprites and graphics: - Basic graphics copying: Uses BLIT x, y, width, height AT col, row to copy image sections. - Rendering loop: Combines BLIT with WHILE loops to fill the screen with a pattern. - Fundamental concept: Foundation for understanding animations and more complex graphics.

examples\blit_island - Advanced graphics

Level: Intermediate-Advanced

More sophisticated example of BLIT usage: - Scene composition: Builds complex scenes by combining multiple sprites. - Optimization: Demonstrates techniques for efficient drawing. - Multiple sprites: Management of several graphic elements on screen.

examples\sprites - Masked sprites

Level: Intermediate | Requires: Images in IMAGES

Shows how to use the lib/sprites.cyd library: a walking character and a bouncing ball over a night scene, without erasing it: - Masks: Each sprite covers only its silhouette (sprDraw); the sky and the stars show around it. - Animation: The character has 4 frames in the sprite sheet; each step sprX points at the next one. - Moving by characters and by pixels: The character moves character by character and the ball goes up and down pixel by pixel (sprPY). - Several save slots: Each one saves its background in its own slot (sprSlot) and they are restored in reverse order, so the background stays right when they cross.

examples\sprites_px - Sprites with pixel X

Level: Intermediate | Requires: Images in IMAGES

The same scene with the lib/sprites_px.cyd library: - Pixel X: The character walks 2 pixels per step with sprPX, instead of character by character. - Cost: Shows the alternative that takes more memory and draws sprites that don't fall on a character boundary more slowly; if pixel X isn't needed, lib/sprites.cyd is enough.

examples\Rocky_Horror_Show - Character animation

Level: Advanced

Implements an animated intro screen: - Frame-by-frame animation: Uses BLIT to create animations by changing frames. - Precise timing: Combines WAIT with BLIT to control animation speed. - Large sprites: Handling larger characters on screen.

examples\CYD_presents - Complex visual effects

Level: Advanced

Example of visual effects: - Presentation effects: Implements Spectrum demoscene-style animations. - Synchronization: Coordinates multiple visual elements with music. - Advanced techniques: Combines BLIT, WAIT, PICTURE, and color effects.

The series blit → blit_island → Rocky_Horror_Show → CYD_presents forms a natural progression for mastering graphics in CYD.

examples\Golden_Axe_select_character - Dynamic selection with colors

Level: Advanced | Requirements: Images in IMAGES

Recreates a Golden Axe-style character selection screen: - Option change detection: Uses CHOOSE IF CHANGED THEN GOSUB to execute code when the player moves the cursor. - Dynamic color effects: Uses FILLATTR to change color attributes of screen areas in real time. - Selection highlighting: Illuminates the selected character with a blinking effect using loops. - Fade-out effects: Implements a fade-out effect by dividing the screen into 4 sections with FADEOUT. - Contextual information: Displays descriptive text that changes based on the selected character. - Helper functions: OPTIONSEL() returns the index of the currently selected option.

This example is perfect for creating visually appealing and interactive selection menus.

Complete project examples

examples\SCUMM_16 - SCUMM/LucasArts-style interface

Level: Advanced

Complete implementation of a SCUMM-style graphic adventure interface (like Monkey Island or Maniac Mansion): - Multiple windows: Divides the screen into graphics area, text area, and verb area. - Verb menu: Implements a 9-verb menu (3x3) at the bottom of the screen. - Two-level system: First level for selecting a verb, second level for selecting an object/direction. - Sprite display: Uses BLIT to copy the location image and verbs. - Object management: Prints a list of visible objects in the location. - Custom charset: Loads a 4x8 character set for more compact text using CHARSET 1. - Visual feedback: Changes the color of the selected verb with FILLATTR. - Modular organization: Uses subroutines to print objects, directions, and manage selection.

This example is an excellent template for creating point-and-click graphic adventures.

examples\Delerict - Complete adventure with custom engine

Level: Advanced-Expert | Requirements: Images in IMAGES | Target: 128K

A small but complete space adventure, with a beginning, an ending and ten illustrated locations. You are the only survivor of the crew of the "Carl Sagan": you must board an alien wreck, recover the artifact it holds and get back to your pod before the creature guarding it catches you. It shows how to build a complete adventure engine on top of CYD: - Menu interface: verbs on a 3×3 grid (MENUCONFIG) with three pages (actions, more actions and options) and a movement menu with eight directions (N, S, E, W, Up, Down, Enter, Exit). The object is chosen in a selector with icons copied with BLIT. - Object system: attributes in bit masks (0b00000001) that say which verbs each object accepts, and the location of each object in a variable (in a location, carried, worn or out of play). - Location pictures: one picture per location, and variants that show its state (a forced door, a dark gallery, a powered console...), drawn with PICTURE and BLIT. - Puzzles and state: exits that depend on what you have done, dynamic text, turn counters (radiation, the creature, the final escape) and several endings: escaping with the artifact, dying and abandoning the mission. - Save and load: saves the game to memory with RAMSAVE and restores it with RAMLOAD; it can also restart. - Controls: chooses a Sinclair or cursor joystick with MENUJOY and redefines the menu keys with MENUKEY, asking for them with INKEY(0). - Generated graphics: the pictures are generated by make_images.py, a pure Python script that draws with perspective and dithering while respecting the Spectrum's attributes.

This is the most complex example, and a foundation for traditional text adventures or hybrid (text and graphics) ones. The example's README.md file describes its structure and contains the walkthrough.

How to use the examples

To test without compiling: Each directory includes a precompiled .tap file that you can load directly into your favorite ZX Spectrum emulator.

To compile them yourself: Each example is a project: its cyd_project.ini specifies its main script and its target. Build it where it is, without copying anything: - Windows: make_adv.cmd examples\test, or drag the example's folder onto make_adv.cmd. - Linux/macOS: ./make_adv.sh examples/test. - GUI: Open… and the example's folder.

The compiled file is left in the example's OUTPUT/ folder (and, the first time, a tokens.json in the example's folder if it doesn't have one).

Recommended study order: It's recommended to study the examples in this order for a gradual learning curve: 1. test → Basic concepts 2. multicolumn_menu → menu_keys → Menus 3. guess_the_number → Game logic 4. windows → Split interface 5. input_test → Advanced input 6. ETPA_ejemplo → Branching narrative 7. include_demo → Code organization 8. blit → blit_island → Rocky_Horror_Show → CYD_presents → Progressively complex graphics 9. Golden_Axe_select_character → Dynamic visual effects 10. SCUMM_16 → LucasArts-style interface 11. Delerict → A complete adventure with its own engine


Character set

The engine supports a character set of 256 characters, with a height of 8 pixels and a variable width of 1 to 8 pixels. The default character set included is 6x8 in size, along with an alternative set of 4x8 size starting from character 144. This is the default character set, ordered from left to right and top to bottom:

Default character set

The characters correspond to standard ASCII, except for the Spanish characters, which correspond to the following positions for both character sets:

Character Position 6x8 Position 4x8
'ª' 16 144
'¡' 17 145
'¿' 18 146
'«' 19 147
'»' 20 148
'á' 21 149
'é' 22 150
'í' 23 151
'ó' 24 152
'ú' 25 153
'ñ' 26 154
'Ñ' 27 155
'ç' 28 156
'Ç' 29 157
'ü' 30 158
'Ü' 31 159

Characters 127 to 143 (starting from zero, both inclusive) are special. They are used as icons in options, i.e. where an option appears when the OPTION command is processed, and as wait indicators with a WAITKEY or when changing pages if the PAGEPAUSE command is active.

  • Character 127 is the character used when an option is not selected in a menu. (In red in the screenshot below)
  • Characters 128 to 135 form the animation cycle of an option selected in a menu. (In green in the screenshot below)
  • Characters 136 to 143 form the animation cycle of the wait indicator. (In blue in the screenshot below)

Special characters

The compiler has two parameters: -c to import a new character set, and -C to export the currently used character set, in case it can be used as a template or for customizations.

This is the import/export format for the character set:

[{"Id": 0, "Character": [255, 128, ...], "Width":8}, {"Id": 1, "Character": [0, 1, ...], "Width":6}, ...]

It is a JSON file with an array of records with three fields:

  • Id: character number from 0 to 255, which cannot be repeated.
  • Character: an array of 8 numbers that corresponds to the value of the bytes of the character and, therefore, there cannot be values greater than 255. Each byte corresponds to the pixels of each line of the character.
  • Width: the width in pixels of the character (the values cannot be less than 1 or greater than 8). Since the size of each character line in the above field is 8, any extra pixels on the right will be discarded.

To make it easier to create an alternative character set, the CYD character set converter or cyd_chr_conv tool has been included. This tool allows you to convert fonts in .chr, .ch8, .ch6 and .ch4 formats created with ZxPaintbrush into the aforementioned JSON format. In addition, in the assets directory of the distribution you can find the default_charset.chr file with the default font so you can edit and customize it with that program.


Error codes

The application may generate errors at runtime. There are two types of errors: disk errors and engine errors.

Engine errors are, as their name indicates, errors that occur when the engine detects an anomalous situation. They are the following:

  • System Error 1: The accessed resource does not exist. This is because PICTURE or TRACK is being executed with an index that does not exist in the adventure, since the corresponding image or track was not loaded during compilation. Without --debug-stack, a RETURN without a prior GOSUB usually ends in this error too.
  • System Error 2: Too many options have been created; the limit of possible options has been exceeded.
  • System Error 3: There are no options available; a CHOOSE command has been executed without having any OPTION before.
  • System Error 4: A character of the character set is more than 8 pixels wide.
  • System Error 5: There is no music module loaded to play.
  • System Error 6: Invalid instruction code.
  • System Error 7: Access to array position out of range.
  • System Error 8: Missing option. When scrolling, the declared options shift upwards. If one of them goes over the top of the margins, this error is generated.
  • System Error 9: RETURN with no GOSUB pending. Only checked when building with --debug-stack.
  • System Error 10: Too many nested GOSUBs: the call stack is full, usually because a subroutine leaves with GOTO instead of RETURN and it happens again and again. Only checked when building with --debug-stack.

To find where a system error happened, compile with --debug-errors. The message adds the position of the instruction that caused it, for example SYSTEM ERROR No:7 at 0:42582 (chunk 0, address 42582), and the compiler writes a .map file next to the game with the position of every statement of the script:

0:42577 adventure.cyd:12    SET_D   1
0:42580 adventure.cyd:13    PUSH_I  15
0:42582 adventure.cyd:13    PUSH_VAL_ARRAY  15
0:42586 adventure.cyd:13    POP_SET 15

The statement you are looking for is the last one of that chunk whose address is not greater than the one in the message. The last column is where the statement starts on its line. In the GUI you don't need to look for it: paste the message, or just 0:42582, in the Game error field and it tells you the line and opens the file at it. Errors 9 and 10 only exist with --debug-stack, so for them use both options.

Without --debug-errors the interpreter doesn't change. With it, each instruction that can give a system error and that the game uses (those that print text, GOSUB/RETURN, OPTION/CHOOSE, PICTURE, TRACK/PLAY/LOOP and the arrays) notes where it is, which adds 3 bytes to it, and the error message takes about 43 more; the other instructions don't get slower. Since the interpreter's instruction table is aligned, those bytes sometimes fit in the alignment gap and sometimes make the interpreter grow by 256 bytes.

Disk errors are errors that could be caused when the game engine accesses the disk or the storage card. They are shown on screen as DISK ERROR No: followed by the code, and they halt the game (unlike the recoverable SAVE/LOAD errors, which are queried with SAVERESULT()).

On the +3 target they correspond to +3DOS errors:

  • Disk Error 0: Drive not ready
  • Disk Error 1: Disk is write protected
  • Disk Error 2: Seek fail
  • Disk Error 3: CRC data error
  • Disk Error 4: No data
  • Disk Error 5: Missing address mark
  • Disk Error 6: Unrecognised disk format
  • Disk Error 7: Unknown disk error
  • Disk Error 8: Disk changed whilst +3DOS was using it
  • Disk Error 9: Unsuitable media for drive
  • Disk Error 20: Bad filename
  • Disk Error 21: Bad parameter
  • Disk Error 22: Drive not found
  • Disk Error 23: File not found
  • Disk Error 24: File already exists
  • Disk Error 25: End of file
  • Disk Error 26: Disk full
  • Disk Error 27: Directory full
  • Disk Error 28: Read-only file
  • Disk Error 29: File number not open (or open with wrong access)
  • Disk Error 30: Access denied (file is in use already)
  • Disk Error 31: Cannot rename between drives
  • Disk Error 32: Extent missing (which should be there)
  • Disk Error 33: Uncached (software error)
  • Disk Error 34: File too big (trying to read or write past 8 megabytes)
  • Disk Error 35: Disk not bootable (boot sector is not acceptable to DOS BOOT)
  • Disk Error 36: Drive in use (trying to re-map or remove a drive with files open)

These errors appear when accessing the disk, when searching for more pieces of text, images, etc. If error 23 appears (File not found), it is usually because you have forgotten to include a necessary file on the disk. Other errors indicate a problem with the disk drive or the disk itself.

On the esxDOS target (divMMC/divIDE interfaces with an SD card) they correspond to the esxDOS error codes:

  • Disk Error 1: O.K. (no error)
  • Disk Error 2: Nonsense in esxDOS
  • Disk Error 3: Statement end error
  • Disk Error 4: Wrong file type
  • Disk Error 5: No such file or directory
  • Disk Error 6: I/O error
  • Disk Error 7: Invalid filename
  • Disk Error 8: Access denied
  • Disk Error 9: Drive full
  • Disk Error 10: Invalid I/O request
  • Disk Error 11: No such drive
  • Disk Error 12: Too many open files
  • Disk Error 13: Bad file descriptor
  • Disk Error 14: No such device
  • Disk Error 15: File pointer overflow
  • Disk Error 16: Is a directory
  • Disk Error 17: Not a directory
  • Disk Error 18: File already exists
  • Disk Error 19: Invalid path
  • Disk Error 20: No SYS
  • Disk Error 21: Path too long
  • Disk Error 22: No such command
  • Disk Error 23: File in use
  • Disk Error 24: File is read only
  • Disk Error 25: Verify failed
  • Disk Error 26: Loading .KO failed
  • Disk Error 27: Directory not empty
  • Disk Error 28: MAPRAM is active
  • Disk Error 29: Drive is busy
  • Disk Error 30: Unknown filesystem
  • Disk Error 31: Device is busy

For esxDOS, the most common error is 5 (No such file or directory), which usually means you have forgotten to copy some required file onto the SD card (the .CSC image, the .BIN music, the .SAV save, or the game's own .DAT data file).


External tools

Tools by other authors to make adventures with CYD and to play them. They are not part of CYD: each has its own author, license and way of use.

CYD Studio

A visual gamebook editor for CYD that runs in the browser, offline too. You draw the story as a graph of scenes, with broken links in red; each scene is written in CYD's syntax and can be tried in a built-in Spectrum simulator. It exports the .cyd script, or a .zip project ready to build with its cyd_project.ini, the images and the build scripts, and it turns PNG or JPG images into .scr screens.

CYD Player

A library of adventures made with CYD that you play in the browser, with nothing to install, on a built-in Spectrum emulator. Each game has its page, cover and controls, and can be played with the keyboard or a Kempston joystick.

ZX Story Flow

A visual editor for choice-based adventures that runs in the browser. Each screen of the story is a node, and you connect its options to the screens they lead to by dragging with the mouse, so you can see the whole map of the adventure at a glance. It can export the adventure as a CYD script, and also as a BASIC TAP ready to play or as a script for the MuCho engine.


Acknowledgements


Licenses

This software package is subject to different licenses depending on its components:

Choose Your Destiny

Copyright (c) 2025 Sergio Chico (Cronomantic)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

- The above copyright notice and/or one of the project logos must be prominently displayed both on the loading screen and/or within the programs that include this Software, as well as on the download website in the case of a digital copy and/or on the cover page in the case of a physical copy.

- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

In simple terms, this means that if you use this engine to make a game, you must always indicate on the loading screen or within the game itself that it was made with CYD or use one of the project logos (included in the assets directory). You must also do so on the download website if you distribute the game online, and on the box or media container if you distribute it physically. Aside from the above condition, you ALWAYS remain the owner and author of the game you create; you can sell or distribute it without having to publish the source code or artwork. However, the tool is licensed under the AGPL, which means that if you modify it or create your own version, you are required to publish the code and indicate that it is based on this project.