Writing a Sprite Game in C with cc65, Step by Step
C on a 6502 is no longer a curiosity. The cc65 compiler produces Atari executables that are small and fast enough for real games, and its Atari library gives you named access to every hardware register. This guide builds Gem Grab, a complete game in about 150 lines of C. You move a smiley hero around the screen with the joystick, collect green gems, and keep away from a red ghost that homes in on you and speeds up as your score rises.
Everything that moves is a player (hardware sprite), and all hit detection uses the GTIA collision registers, so the program never has to compare coordinates.
What you'll learn: reserving aligned player/missile memory without a custom linker file, turning on sprites through the ANTIC, GTIA_WRITE and OS structures, drawing and moving shapes with memset and memcpy, a loop locked to the TV frame with waitvsync(), the cc65 joystick driver, reading collisions, sound with _sound(), and text with conio.
What you need: cc65 (the program was built with cl65 V2.19), a text editor and an emulator. Setting up cc65 and the difference between the atari and atarixl targets are covered in Programming the Atari 8-bit in C with cc65. Here we go straight to the game.
1. Build and run
Save the complete listing from section 9 as gemgrab.c and build it with:
cl65 -t atari -O -o gemgrab.xex gemgrab.c
-t atari selects the standard Atari target, which also suits the 400/800. -O turns on the optimiser. The result is a DOS executable of about 4.4 KB. The default atari memory layout assumes the BASIC ROM is off, so boot with BASIC disabled, for example atari800 -xl -nobasic gemgrab.xex. (This small program happened to start with BASIC on as well, but larger ones will not.) On real hardware, load it from DOS or through an SD-card device or FujiNet.
2. Player/missile memory without a linker config
ANTIC fetches sprite data from a block of memory whose start address is set in the PMBASE register. Only the high byte of the address is stored, and in double-line resolution the block must start on a 1K boundary. In assembly you would just pick a free page. In C, the usual answer is a custom linker configuration, but there is a simpler trick: declare a static array twice the size you need and find the aligned 1K inside it.
static unsigned char pmbuf[2048]; /* holds one 1K-aligned P/M area */
static unsigned char *pm;
#define PLAYER(n) (pm + 512 + 128 * (n))
pm = (unsigned char *)(((unsigned)pmbuf + 1023) & 0xFC00);
Adding 1023 and clearing the low ten bits rounds the address up to the next multiple of 1024. Wherever the linker happens to place pmbuf, there is always a full 1K block inside it. You waste up to 1K of RAM, but the program needs no special build setup and keeps working as the code grows.
In double-line resolution the block is laid out like this: the first 384 bytes are unused, the missiles start at +384, and players 0 to 3 start at +512, +640, +768 and +896, 128 bytes each. The PLAYER(n) macro does that arithmetic. Each byte is one row of 8 pixels, two scan lines tall.
3. Switching the sprites on
static void pm_on(void)
{
pm = (unsigned char *)(((unsigned)pmbuf + 1023) & 0xFC00);
memset(pm, 0, 1024);
ANTIC.pmbase = (unsigned)pm >> 8;
OS.sdmctl = 0x2E; /* playfield + players + missiles, double-line */
GTIA_WRITE.gractl = 3; /* let GTIA display players and missiles */
OS.gprior = 1; /* players in front of the playfield */
OS.pcolr0 = 0x1E; /* yellow hero */
OS.pcolr1 = 0xBA; /* green gem */
OS.pcolr2 = 0x36; /* red ghost */
}
<atari.h> defines structures laid over the hardware and the OS variables, so you write ANTIC.pmbase instead of POKE 54279. Note the split between hardware and shadow registers:
ANTIC.pmbaseandGTIA_WRITE.gractlare written directly. PMBASE has no OS shadow.OS.sdmctl(location 559),OS.gprior(623) andOS.pcolr0–pcolr3(704–707) are shadows. The OS copies them to the hardware every vertical blank, which is why writing them works at all. If you write the hardware registers DMACTL or PRIOR directly, the OS overwrites your value 1/60 second later.
The value $2E sets normal-width playfield, missile DMA, player DMA and display-list DMA, with bit 4 clear for double-line resolution. $3E would select single-line resolution and a 2K block on a 2K boundary.
pm_off() does the reverse for the title screen: sdmctl back to $22, GRACTL to 0, and the horizontal positions to 0 so no sprite is left on screen.
4. Drawing and moving a sprite
Horizontal movement is one register write, GTIA_WRITE.hposp0 = hx. Vertical movement means moving the shape within its 128-byte strip. One small function handles all three sprites:
static void put(unsigned char n, unsigned char oldy, unsigned char y,
const unsigned char *shape)
{
unsigned char *p = PLAYER(n);
memset(p + oldy, 0, 8);
memcpy(p + y, shape, 8);
}
It wipes the eight bytes at the old height and copies the shape to the new one. Both library calls are tight machine-code loops, so moving all three sprites takes a small fraction of a frame. The shapes are const arrays of eight bytes, one per row:
static const unsigned char hero[8] = {0x3C,0x7E,0xDB,0xFF,0xBD,0xC3,0x7E,0x3C};
The constants at the top of the program define the play area. In double-line resolution, a GRAPHICS 0 screen covers player bytes 16 to 111, so an eight-byte shape can sit anywhere from TOP (16) to BOTTOM (104). Horizontal positions from 48 to 192 keep an 8-pixel player inside the normal-width playfield.
5. A frame-locked loop
for (;;) {
waitvsync();
/* 1. collisions seen during the last frame */
if (GTIA_READ.p0pl & 4) break; /* touched player 2 */
if (GTIA_READ.p0pl & 2) { /* touched player 1 */
++score; status(); new_gem();
beep = 8;
}
GTIA_WRITE.hitclr = 0;
waitvsync() returns at the start of the next frame, so the loop runs exactly once per frame: 60 times a second on NTSC, 50 on PAL. That gives smooth movement and a speed that doesn't depend on how much work each pass does.
The first job each frame is to look at what happened while the previous frame was drawn. P0PL (GTIA_READ.p0pl) has one bit for each player that player 0 has overlapped: value 2 for player 1 (the gem), 4 for player 2 (the ghost). The test is pixel-exact. Writing anything to HITCLR clears all the collision registers ready for the next frame. Without that write, a collision stays latched and the game would score the same gem every frame.
6. Joystick input with the cc65 driver
j = joy_read(JOY_1);
oy = hy;
if (JOY_LEFT(j) && hx > LEFT) --hx;
if (JOY_RIGHT(j) && hx < RIGHT) ++hx;
if (JOY_UP(j) && hy > TOP) --hy;
if (JOY_DOWN(j) && hy < BOTTOM) ++hy;
put(0, oy, hy, hero);
GTIA_WRITE.hposp0 = hx;
main() calls joy_install(joy_static_stddrv) once, which links the standard Atari joystick driver into the program. After that, joy_read(JOY_1) returns a bit mask and the macros JOY_UP, JOY_LEFT, JOY_BTN_1 and so on test it. Because each direction is tested separately, diagonals work for free. The same code compiles for other cc65 targets, which is the point of the driver. On the Atari you could equally read OS.stick0 (location 632) and OS.strig0 (644) directly.
The fire button is handled the same way in wait_fire(), which waits for a release and then a fresh press so that a held button can't skip a screen.
7. A homing enemy that speeds up
if (++tick >= (score < 20 ? 3 - score / 10 : 1)) {
tick = 0;
oy = cy;
if (cx < hx) ++cx; else if (cx > hx) --cx;
if (cy < hy) ++cy; else if (cy > hy) --cy;
put(2, oy, cy, ghost);
GTIA_WRITE.hposp2 = cx;
}
The ghost takes one step towards the hero on each axis, but only every third frame while the score is below 10, every second frame from 10 to 19, and every frame after that. At full speed it is as fast as the hero, so you can only escape by moving diagonally away while it lines up. Simple rules like this are the core of many early arcade enemies.
Random gem positions come from rand(). To avoid the same sequence every game, title() seeds it with srand(OS.rtclok[2]), the frame counter, at the moment the player presses fire. Human reaction times make that value unpredictable.
8. Text, sound and game over
The score line and title use conio: clrscr(), gotoxy(), cputs() and cprintf() write straight to the GRAPHICS 0 screen that the cc65 runtime sets up, and cursor(0) hides the cursor. The background and border are made black through OS.color2 and OS.color4 (locations 710 and 712).
_sound(voice, frequency, distortion, volume) works like BASIC's SOUND statement. Each gem sets beep to 8, and every frame the loop plays a slightly lower, quieter note until it reaches zero. That makes a short falling chirp without ever pausing the game. When the ghost catches you, the loop breaks, a low buzz plays, the best score is updated, and wait_fire() waits before returning to the title.
9. The complete program
/* GEM GRAB - a small cc65 game with player/missile graphics */
#include <atari.h>
#include <conio.h>
#include <joystick.h>
#include <stdlib.h>
#include <string.h>
#define TOP 16 /* first visible byte of a double-line player */
#define BOTTOM 104 /* lowest y for an 8-byte shape */
#define LEFT 48 /* horizontal limits for an 8-pixel-wide player */
#define RIGHT 192
static unsigned char pmbuf[2048]; /* holds one 1K-aligned P/M area */
static unsigned char *pm;
#define PLAYER(n) (pm + 512 + 128 * (n))
static const unsigned char hero[8] = {0x3C,0x7E,0xDB,0xFF,0xBD,0xC3,0x7E,0x3C};
static const unsigned char gem[8] = {0x18,0x3C,0x7E,0xFF,0x7E,0x3C,0x18,0x00};
static const unsigned char ghost[8] = {0x3C,0x7E,0xDB,0xFF,0xFF,0xFF,0xDB,0x91};
static unsigned char hx, hy, gx, gy, cx, cy, tick, beep;
static unsigned int score, best;
static void pm_on(void)
{
pm = (unsigned char *)(((unsigned)pmbuf + 1023) & 0xFC00);
memset(pm, 0, 1024);
ANTIC.pmbase = (unsigned)pm >> 8;
OS.sdmctl = 0x2E; /* playfield + players + missiles, double-line */
GTIA_WRITE.gractl = 3; /* let GTIA display players and missiles */
OS.gprior = 1; /* players in front of the playfield */
OS.pcolr0 = 0x1E; /* yellow hero */
OS.pcolr1 = 0xBA; /* green gem */
OS.pcolr2 = 0x36; /* red ghost */
}
static void pm_off(void)
{
OS.sdmctl = 0x22;
GTIA_WRITE.gractl = 0;
GTIA_WRITE.hposp0 = GTIA_WRITE.hposp1 = GTIA_WRITE.hposp2 = 0;
}
/* erase a shape at its old height and draw it at the new one */
static void put(unsigned char n, unsigned char oldy, unsigned char y,
const unsigned char *shape)
{
unsigned char *p = PLAYER(n);
memset(p + oldy, 0, 8);
memcpy(p + y, shape, 8);
}
static void status(void)
{
gotoxy(2, 0);
cprintf("SCORE %u BEST %u ", score, best);
}
static void wait_fire(void)
{
while (JOY_BTN_1(joy_read(JOY_1))) ; /* wait for release */
while (!JOY_BTN_1(joy_read(JOY_1))) ; /* wait for press */
}
static void new_gem(void)
{
unsigned char oldy = gy;
gx = LEFT + rand() % (RIGHT - LEFT);
gy = TOP + rand() % (BOTTOM - TOP);
put(1, oldy, gy, gem);
GTIA_WRITE.hposp1 = gx;
}
static void title(void)
{
pm_off();
clrscr();
gotoxy(15, 6); cputs("GEM GRAB");
gotoxy(8, 10); cputs("Grab the green gems,");
gotoxy(8, 11); cputs("dodge the red ghost.");
gotoxy(12, 16); cprintf("Best score: %u", best);
gotoxy(13, 20); cputs("PRESS FIRE");
wait_fire();
srand(OS.rtclok[2]);
}
static void play(void)
{
unsigned char j, oy;
clrscr();
score = 0; tick = 0; beep = 0;
pm_on();
hx = 60; hy = 60; put(0, hy, hy, hero);
cx = 180; cy = 30; put(2, cy, cy, ghost);
gy = TOP; new_gem();
GTIA_WRITE.hposp0 = hx; GTIA_WRITE.hposp2 = cx;
status();
waitvsync();
GTIA_WRITE.hitclr = 0;
for (;;) {
waitvsync();
/* 1. collisions seen during the last frame */
if (GTIA_READ.p0pl & 4) break; /* touched player 2 */
if (GTIA_READ.p0pl & 2) { /* touched player 1 */
++score; status(); new_gem();
beep = 8;
}
GTIA_WRITE.hitclr = 0;
/* 2. move the hero */
j = joy_read(JOY_1);
oy = hy;
if (JOY_LEFT(j) && hx > LEFT) --hx;
if (JOY_RIGHT(j) && hx < RIGHT) ++hx;
if (JOY_UP(j) && hy > TOP) --hy;
if (JOY_DOWN(j) && hy < BOTTOM) ++hy;
put(0, oy, hy, hero);
GTIA_WRITE.hposp0 = hx;
/* 3. the ghost steps towards the hero, faster as the score rises */
if (++tick >= (score < 20 ? 3 - score / 10 : 1)) {
tick = 0;
oy = cy;
if (cx < hx) ++cx; else if (cx > hx) --cx;
if (cy < hy) ++cy; else if (cy > hy) --cy;
put(2, oy, cy, ghost);
GTIA_WRITE.hposp2 = cx;
}
/* 4. a short falling beep for each gem */
if (beep) { _sound(0, 40 + beep * 4, 10, beep); --beep; }
else _sound(0, 0, 0, 0);
}
_sound(0, 200, 8, 12);
if (score > best) best = score;
gotoxy(11, 12); cputs("CAUGHT! PRESS FIRE");
wait_fire();
_sound(0, 0, 0, 0);
}
int main(void)
{
joy_install(joy_static_stddrv);
cursor(0);
OS.color2 = 0x00; /* black background */
OS.color4 = 0x00; /* black border */
for (;;) {
title();
play();
}
}
Where to take it next
- Single-line sprites: change
sdmctlto$3E, use a 4K buffer with 2K alignment (+ 2047and& 0xF800), move players to +1024, +1280 and so on, and double the vertical limits. Shapes can then be twice as detailed. - A second ghost: player 3 is free. Give it a different speed or a different rule (for example, it moves towards where the hero is heading).
- Missiles as gems: the four missiles share one strip at +384, two bits each. Small gems as missiles would leave players free for more enemies. Use
GTIA_READ.m0pland friends to detect them. - A real level: draw walls with conio characters and check P0PF (
GTIA_READ.p0pf), the player-to-playfield collision register, to stop the hero walking through them. - Bigger projects: move to a custom linker configuration so that the P/M area, character sets and display lists sit at fixed, aligned addresses (see Programming the Atari 8-bit in C with cc65, section 7).
Troubleshooting
- Nothing appears: check
GTIA_WRITE.gractl = 3as well asOS.sdmctl. DMA fetches the data, but GTIA only shows it when GRACTL is set. - Sprites appear as vertical bars or garbage: PMBASE isn't aligned, or the strip wasn't cleared. Use the rounding trick and
memsetthe whole block first. - Scoring runs away: you forgot to write
GTIA_WRITE.hitclrafter reading the collisions. - Colours or priority won't stick: write the OS shadows (
OS.pcolr0,OS.gprior,OS.sdmctl), not the hardware registers. - A larger program crashes on load: run it with BASIC disabled. The default
atarilinker configuration assumes the memory from$A000up is free RAM. - Same gem positions every game: seed
rand()from the frame counter at a moment the player chooses.
Further reading
- The cc65 documentation for the Atari target (
atari.htmlin the cc65 docs), for the joystick drivers,waitvsync(),_sound()and the hardware structures in<atari.h>. - Chris Crawford and others, De Re Atari, chapter 4, on player/missile graphics.
- Ian Chadwick, Mapping the Atari, for PMBASE, SDMCTL, GPRIOR, GRACTL and the collision registers.
- On this site: Programming the Atari 8-bit in C with cc65, Player/Missile Graphics in Atari BASIC, Collision Detection in Depth, Writing a Game in FastBasic, Step by Step.
Credits
- Picture: Gem Grab running: the yellow hero has just collected a gem; the red ghost is closing in. — Program authors; screenshot by the site
- cc65 documentation — Atari-specific information (atari.sgml / atari.html) — cc65.github.io
- cc65 headers atari.h, _gtia.h, _antic.h, _atarios.h, joystick.h (cc65 V2.19) — GitHub project authors
- De Re Atari — Chapter 4, Player-Missile Graphics — Chris Crawford (Section 4 of De Re Atari)
- Mapping the Atari — PMBASE, SDMCTL 559, GPRIOR 623, PCOLR0-3 704-707, GRACTL, P0PL, HITCLR — AtariArchives.org
