C
Macaw OS runs programs written in C as well as Lua. It's C89, the C of the late 1980s and 1990s, with its whole standard library, plus a few later additions like // comments, long long and <stdint.h>. A C program gets its own memory with real addresses (see Memory), and its window works the same way a Lua program's does.
Your first C program
In Terminal, type:
new hello.c
That makes /home/hello.c from a template and opens it in Code. Press Ctrl+R to compile and run it. Double-clicking a .c file opens it in Code, and run hello.c in Terminal runs it. There's a whole game in C, Worm, at the end of this page.
#include <macaw.h>
int x = 60, y = 40;
void _update(void) {
if (btn("left")) x--;
if (btn("right")) x++;
}
void _draw(void) {
cls(NAVY);
circfill(x, y, 8, ORANGE);
}
int main(void) {
window(160, 100, "Hello from C");
realtime(1);
return 0;
}
main runs once when the program starts. If the program defines _init, _update, _draw or _close, Macaw OS calls them the same way it calls a Lua program's. window(w, h, title) and realtime(1) take the place of Lua's WINDOW table.
A program with no window and no _draw is a console program. Whatever it prints shows in a window of its own, like a terminal.
#include <stdio.h>
int main(void) {
int i;
for (i = 1; i <= 10; i++) printf("%d squared is %d\n", i, i * i);
return 0;
}
Programs in more than one file
Give cc every file, and a name for the program with -o:
cc main.c util.c -o game.mx
Each file is compiled on its own, then they're linked into one program. A function or global that one file uses has to be defined in exactly one of them. One marked static belongs to its own file, so two files can each have a static int count without a clash.
/* util.c */
static int calls = 0;
int twice(int n) { calls++; return n * 2; }
int calls_so_far(void) { return calls; }
/* main.c */
#include <stdio.h>
int twice(int n);
int calls_so_far(void);
int main(void) {
printf("%d %d\n", twice(21), calls_so_far());
return 0;
}
The .mx file is the compiled program. Double-click it, or type game in Terminal, to run it. You don't need the .c files to run it. With no -o, cc only checks that the files compile and link.
Today a .mx holds the program compiled to Lua. A faster interpreter for C is on the way, and its programs will be .mx files too. A version of Macaw OS that can't run a .mx says so instead of trying.
When something's wrong
A mistake that stops the program compiling is shown before anything runs, with the line it's on:
/home/hello.c:12: y isn't declared
So is one that stops it linking:
/home/main.c:3: twice is used but never defined (in any of the files)
A mistake while it runs, like using a NULL pointer, reading memory that malloc didn't give out or dividing by zero, stops the program with the line it happened on:
/home/hello.c:20: bad address 0x00000004: that's the null page (a NULL pointer?)
It only ever stops that program. A bad pointer can't touch anything else.
The language
All of C89 is there:
char,short,intandlong, signed and unsigned,floatanddouble, pluslong longand_Bool. Anintand alongare 32 bits, along longis 64, and pointers are 32. Whole numbers wrap round on overflow.- Pointers and pointer arithmetic, arrays and arrays of arrays,
struct,union,enum,typedefand bit-fields. - Structs passed to and returned from functions by value, and assigned with
=. - Functions that take
..., using<stdarg.h>. - Pointers to functions, so
qsorttakes a comparison function. if,while,do,for,switchwith fall-through,break,continueandgoto.- The preprocessor:
#include,#define(with arguments,#and##),#if,#ifdef,#elif,#error,__LINE__,__FILE__,__DATE__and__TIME__. - Initialisers with or without inner braces, like
int grid[2][2] = { 1, 2, 3, 4 };, andstruct point p = { .x = 3, .y = 4 };. - Old-style function definitions, implicit
int, wide strings (L"...") and trigraphs.
Numbers bigger than a byte are stored most significant byte first, as on a PowerPC.
A few things work differently from a C compiler on another computer:
- A
caselabel has to be right inside itsswitch's braces, not inside a block within them, so Duff's device won't compile. setjmphas to start a statement of its own:setjmp(b);,x = setjmp(b);,if (setjmp(b) == 0)orswitch (setjmp(b)). Abreak,continueorgotocan't jump from after it to outside the block it's in. After alongjmp, local variables keep their latest values, as if they were allvolatile.- Characters are single bytes, and the only locale is
"C".
Headers
| Header | What's in it |
|---|---|
<stdio.h> | printf and the rest of its family, scanf's family, and files: fopen, fclose, fgets, fputs, fread, fwrite, fseek, ftell, fflush, remove, rename and the rest |
<stdlib.h> | malloc, calloc, realloc and free, atoi, atof, strtol, strtoul, strtod, rand and srand (RAND_MAX is 32767), qsort, bsearch, abs, div, exit, atexit, abort and getenv |
<string.h> | strlen, strcpy, strcat, strcmp and their n versions, strchr, strrchr, strstr, strspn, strcspn, strpbrk, strtok, strerror, memcpy, memmove, memset, memcmp and memchr |
<math.h> | sin, cos, tan and their inverses, sinh, cosh, tanh, exp, log, log10, pow, sqrt, fabs, floor, ceil, fmod, frexp, ldexp and modf, and M_PI |
<ctype.h> | isdigit, isalpha, isspace, isprint and the rest, toupper and tolower |
<time.h> | time, clock, difftime, mktime, localtime, gmtime, asctime, ctime and strftime |
<setjmp.h>, <signal.h> | setjmp and longjmp; signal and raise |
<errno.h>, <assert.h>, <locale.h>, <stdarg.h> | errno, assert, setlocale and localeconv, and va_list |
<stddef.h>, <limits.h>, <float.h>, <stdbool.h>, <stdint.h> | size_t and NULL, INT_MAX, DBL_MAX and so on, bool, and int32_t and its friends |
<macaw.h> | stdio, stdlib, string and math, plus Macaw OS's own calls (below) |
<macaw3d.h> | 3D: scenes, meshes, textures and the graphics card (below) |
<macawgpu.h> | The graphics chip's gpu.* calls |
<macawlevel.h> | Levels: opening, drawing, colliding with, building and baking them |
<macawui.h> | The toolkit of buttons, sliders and lists, and the dialogs |
Every call in Macaw OS's own headers has its own entry in the C reference, which says what it does and what each of its parameters is for: the window and drawing, input, sound and the system, 3D, the graphics chip, levels, and buttons, lists and dialogs.
A file's name is looked up from the program's own folder, unless it starts with /. A file is read when it's opened, and written when it's flushed or closed, or when the program ends. Nobody can type into a program's stdin, so getchar and scanf find nothing there: use textinput instead.
Macaw OS's calls
<macaw.h> names every colour in capitals, so NAVY, ORANGE and WHITE are the same numbers as colors.navy and the rest in Lua. Its calls work the way the Lua ones of the same name do:
| Kind | Calls |
|---|---|
| The window | window, windowscale (each pixel 2 x 2 or bigger), resizable, realtime, windowmin (the smallest it can be made), windowcolors and windowcursor (in main, as WINDOW would), redraw, close, settitle, fullscreen, focused |
| Drawing | cls, pset, pget, line, rect, rectfill, box, circ, circfill, tri, text, textscaled, centertext, shadowtext, textwidth, wraptext and wrapline, clip, noclip, camera |
| Colours | pal, palreset, drawpal (draw one colour as another), drawpalreset, nearestcolor |
| The screen | display_width, display_height, display_current, display_sizes and display_size, display_request |
| Screen memory | screenmem (the window picture's address), screenwidth, screenheight |
| Pictures | newpicture, loadpicture (a .pxl or .png), savepicture, parsepicture, decodepicture and decodepicturefile (a PNG, shrunk to fit), importpicture and importpicturefile (a PNG for editing), freepicture, picturewidth, pictureheight, picturesize, pictureget, pictureset, pictureclear, picturecopy, picturegetrgb, picturesetrgb, drawpicture, drawpart, drawpictureex and drawpartex (scaled and flipped), drawinto |
| Sprites and the map | spr, sprex (a block of sprites, flipped), sspr, sprimage, spritesheet, fget, fset, map, mget, mset, mapwidth, mapheight, maplayers, maplayername, importmap and importmapimage (read with imap_layers, imap_layername, imap_size, imap_get, imap_picture, imap_used, imap_notes, imap_note, and let go with imap_free) |
| Input | btn, btnp, keysp and keyspname, mouse (three int * to fill in with the position and buttons), textinput (what's been typed since last time) |
| Sound | sfx, play, tone, note, stop, music, which plays a song from Tracker (music(NULL) stops it), playsong, stopsong, loadsong, playloadedsong, freesong, music_volume, music_note, music_release, notenumber, notename |
| Time | now, the seconds since Macaw OS started, as a double, and deltatime, the seconds since your last _update |
| Folders and files | fileexists, isfolder, makefolder, fileinfo, and listfolder, which gives the name of a folder's first, second, third ... thing |
| Text | markdown (as HTML, with its title) |
| The clipboard | getclipboard, setclipboard |
| The desktop | openpath (opens a file or program, as a double-click does), getpref, setpref |
| The network | net_online, net_dial, net_connect, net_listen, net_accept, net_port, net_send, net_receive, net_readline, net_read, net_status, net_peer, net_close |
| The system | platform, ismac, modkey, memory, sys_version, sys_fps, sys_display, sys_volume, sys_screenshot, sys_title, sys_cursor, sys_clipboard, sys_setclipboard |
| Passwords | nest_set, nest_get, nest_has, nest_remove, nest_list (read with nest_listitem, nest_listlabel, nest_listchanged), nest_request, nest_choose, nest_keep |
| Handy for games | rnd, mid, clamp, sgn, lerp, flr (floor, ceil and round are math.h's, and round(-2.5) there is -3) |
A picture, a song, an imported map, a connection and a listener are each a number, and 0 means it didn't work. The last number you give drawpicture and drawpart is a colour to leave out, or -1 to draw every pixel. drawinto(p) draws into picture p instead of the window, and drawinto(0) goes back to the window.
A call that gives back text takes a buffer and its size, like notename(n, buf, sizeof buf), and returns the whole text's length, so a buffer that's too small still tells you how big it should be. Most give -1 when there's nothing to give. A list comes in two steps: one call says how many, like wraptext(s, 30) or keysp(), and another gives item i, counting from 0, like wrapline(i, buf, sizeof buf).
Calls that ask the person take a function to call with the answer, as Lua's do: display_request(800, 600, COLORS_THOUSANDS, done) calls done(1) once the screen has changed, and nest_request(service, account, got) calls got(password, why), with the password NULL if they said no. Text your function is given is yours only while it runs, so copy it if you want to keep it. Colours for the screen are 8, 256 or COLORS_THOUSANDS.
A program can define _drop(const char **paths, int n, int x, int y) for files dropped on its window, and _display(int w, int h, int colours) for when the screen changes, as well as _init, _update, _draw, _resize and _close.
The network calls never wait. net_receive takes whatever has arrived so far, and net_readline gives -1 until a whole line is there, so call them from _update. net_status is 0 while connecting, 1 when open (or closed with some still to read), 2 once closed and 3 if it failed. To go online, call net_dial(): Dial-Up opens if it's needed, and net_online() is 1 once the line is up. Lua's spawn, wait_online and sleep wait inside a task; C does the same by checking in _update. listfolder(path, i, name, size) counts from 0, and gives 0 once there's nothing left.
The sprites and the map are the program's own: gfx.pxl, gfx.flags and map.map in its folder, made with Sprites and Map as for a cart. A map layer is given by name, like mget(x, y, "Terrain"), and NULL means the first. map(cx, cy, x, y, 0, 0, NULL) draws a whole layer, and camera(x, y) scrolls it. Where Lua has true or false, such as for flipping, C gives 1 or 0.
How Lua's calls look in C
Every call in this guide is in C too, apart from a few that only make sense in Lua: ext.* (extensions are written in Lua), the table helpers add, del and all, and spawn, wait_online and sleep (above). They follow the same rules:
- Something Lua gives you as a table you call methods on (a 3D thing, a mesh, a level) is a number in C, and its methods are calls that take that number first.
cube:position(x, y, z)isposition3d(cube, x, y, z, 0). 0 means there isn't one. - Where Lua lets you leave an argument out, C needs every one. Each header says what to give for "the usual" (usually -1, 0 or
NULL). - A call that gives back several numbers fills in pointers you pass it, like
mousedoes. You can passNULLfor any you don't want. - Lists count from 0 in C, where Lua counts from 1.
- Where Lua takes a function, C takes a pointer to one of yours.
- Text comes back the way
getclipboardgives it: you pass a buffer and its size, and it returns how long the whole text is.
Here's a program that draws straight into its window's memory:
#include <macaw.h>
void _draw(void) {
unsigned char *pixels = (unsigned char *)screenmem();
int w = screenwidth(), h = screenheight(), x, y;
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
pixels[y * w + x] = (x ^ y) & 31;
}
int main(void) {
window(128, 128, "Pattern");
realtime(1);
return 0;
}
3D
#include <macaw3d.h> for everything on the 3D page. Here's that page's first scene in C:
#include <macaw3d.h>
int cam, box;
void _update(void) {
if (btn("left")) turn3d(cam, -2, 0, 0);
if (btn("right")) turn3d(cam, 2, 0, 0);
if (btn("up")) move3d(cam, 0, 0, 0.1);
turn3d(box, 1, 0, 0);
updateworld();
}
void _draw(void) { render(0); }
int main(void) {
int ground;
window(240, 160, "My World");
windowscale(2);
cam = newcamera();
position3d(cam, 0, 1.5, -6, 0);
clscolor3d(cam, SKY);
newlight("sun", -1, -1);
ground = newplane(0, 20);
scale3d(ground, 30, 1, 30);
color3d(ground, GREEN);
box = newcube(0, -1);
position3d(box, 0, 1, 2, 0);
color3d(box, ORANGE);
return 0;
}
| Lua | C |
|---|---|
newcamera(), newlight(kind, [radius], [strength]), newcube, newsphere, newcylinder, newcone, newplane, newpivot, newsprite | The same names. Each gives a number for the thing |
newterrain(cells, height, ...) | newterrain with a height picture, or newterrainfn with your own double height(double u, double v) |
newmesh(verts, tris, ...), newmodel(path, ...) | The same, with the corners as an array of float (5 each: x, y, z, u, v), the triangles as int (3 each, from 0), and textures as an array of picture numbers |
e:position, move, translate, rotate, turn, scale, parent, hide, show, visible, texture, color, fullbright, twosided, free | position3d(e, ...), move3d(e, ...) and so on |
e:point(other), e:point(x, y, z) | point3d(e, other), pointat3d(e, x, y, z) |
e:pos(), e:forward(), e:up() | pos3d(e, &x, &y, &z), forward3d, up3d |
e:dist(other), terrain:height(x, z) | dist3d(e, other), height3d(terrain, x, z, &h), which is 1 if it's over the terrain |
e:collide(type, radius), e.hits, e:pickable(shape) | collide3d, hitcount3d(e) and gethit3d(e, i, &hit), pickable3d |
cam:fov, cam:clscolor, cam:fog, cam:project, cam:pick | fov3d, clscolor3d (-1 to not clear), camfog3d, camproject3d, campick3d |
render([cam]), updateworld, collisions, resetcollisions, pick, ambient, clearworld | The same names. render(0) uses the first camera |
clear3d, camera3d, light3d, pointlight3d, fog3d, project3d, line3d, stats3d | The same names. fog3d() with nothing is nofog3d(), and lamps count from 0 |
cube3d, room3d, loadobj, mesh3d, billboard3d | The same names, plus cube3dsides for a box with its own top and bottom |
m:draw, m:drawm, m:texture, m:size | drawmesh(m, ...), drawmeshm, meshtexture, meshsize, and freemesh when you're done with it |
loadtexture(path, [size]) | The same, giving a picture number |
glr, glr.vram(), glr.info(), cubemaps() | glrpresent(), glrvram(&used, &allowed), glrinfotext(field, buf, size) and glrinfonumber(field), cubemaps() |
What a ray, a click or a bump hits comes back in a hit3d: x, y, z, the way the surface faces (nx, ny, nz), dist, and entity, the thing it hit.
The graphics chip
#include <macawgpu.h> for the graphics chip's calls. They're Lua's gpu.* with gpu_ in front, and modes and features are the same words: gpu_enable("depth_test") (one a call), gpu_begin("triangles"). A buffer, an index buffer and a cube map are each a number. Lights are 0 to 7, and indices and gpu_drawarrays's first corner count from 0. Matrices are 16 floats, column by column. gpu_water's options are a gpu_wateropts: start it with gpu_wateropts w = GPU_WATER_DEFAULTS;, then set what you want, with drips in w.drops and how many in w.ndrops.
| Call | What it does |
|---|---|
gpu_enable(cap), gpu_disable(cap), gpu_isenabled(cap) | Switch a feature on or off, and say whether it's on |
gpu_depthmask(on), gpu_cullface(side), gpu_frontface(way) | Depth writing, which side culling hides, which way round a front face goes |
gpu_viewport(x, y, w, h) | Draw into part of the window (w or h 0: the whole window) |
gpu_clearcolor(c), gpu_clear(what), gpu_reset() | Clear the picture and depth (NULL: both), and put everything back |
gpu_matrixmode(m), gpu_loadidentity(), gpu_pushmatrix(), gpu_popmatrix() | Pick and reset a matrix, save it and get it back |
gpu_translate, gpu_rotate, gpu_scale | Move, turn and grow (gpu_scale takes all three sizes) |
gpu_perspective, gpu_ortho, gpu_frustum, gpu_lookat | Projections (0 for the usual aspect, near and far), and looking from an eye at a target |
gpu_loadmatrix(m), gpu_multmatrix(m), gpu_getmatrix(which, m) | Your own 16 floats in, or a matrix out |
gpu_project(x, y, z, &sx, &sy, &depth) | Where a point lands in the window: 0 if it's behind the camera |
gpu_begin(mode) ... gpu_done() | A corner at a time, with gpu_vertex, gpu_vertex4, gpu_color, gpu_colorex (with a brightness), gpu_texcoord and gpu_normal |
gpu_buffer(floats, count, layout), gpu_bufferset, gpu_buffercount, gpu_freebuffer | A vertex buffer |
gpu_indices(list, count), gpu_freeindices | An index buffer |
gpu_drawarrays(mode, buf, first, count), gpu_drawelements(mode, buf, indices) | Draw a buffer in order (count -1: the rest), or by its indices |
gpu_bindtexture(picture) | Draw with a texture (0: none) |
gpu_light(n, x, y, z, w, strength, radius), gpu_lightoff(n) | Light n (strength -1: the usual) |
gpu_ambient, gpu_shademodel, gpu_material, gpu_fog, gpu_pointsize | Light everywhere, shading, shininess, fog, point size |
gpu_stats(&tris, &corners, &used, &made, &missed) | What was drawn |
gpu_mask(on), gpu_clearmask(), gpu_water(reflection, &opts) | Reflecting water (&opts can be NULL) |
gpu_envmap(faces, x, y, z, box), gpu_envmapbytes(bytes, n, x, y, z, box) | A cube map from six pictures, or from gpu_envpixels's bytes (box can be NULL) |
gpu_envloaded, gpu_envunload, gpu_envpixels(env, buf, size, &across), gpu_freeenvmap | Whether it's on the card, taking it off, its bytes, letting it go |
Levels
#include <macawlevel.h> for Levels. A level is a number: openlevel, loadlevel and newlevel each give one, and 0 means it didn't work (levelerror says why). openlevel builds it and puts on its baked light. After loadlevel, newlevel or a change, buildlevel builds it. Lua's L.lvl:tracebox(...) is leveltracebox(L, ...), and so on. A camera is a levelcam, with x, y, z, yaw, pitch, fov (fov 0 means 90). Where Lua takes a function to draw a view, such as for water's reflection, C takes void draw(const levelcam *c, double above, void *user): point camera3d at c and call leveldrawabove(L, above). A list (of entities, lights or water) is a count, then a call for item i. Here's the page's walk round a level:
#include <macawlevel.h>
int L;
double x, y, z, yaw;
void _update(void) {
double step = (btn("up") ? 0.08 : 0) - (btn("down") ? 0.08 : 0), dx, dz, f;
if (btn("left")) yaw -= 3;
if (btn("right")) yaw += 3;
dx = sin(yaw * M_PI / 180) * step;
dz = cos(yaw * M_PI / 180) * step;
f = leveltracebox(L, x, y + 0.8, z, x + dx, y + 0.8, z + dz, 0.3, 0.8, 0.3, NULL, NULL, NULL, NULL);
x += dx * f;
z += dz * f;
}
void _draw(void) {
clear3d(BLACK);
camera3d(x, y + 1.5, z, yaw, 0, 0);
leveldrawbsp(L, NULL);
}
int main(void) {
L = openlevel("/system/maps/sample.lvl");
levelstart(L, &x, &y, &z, &yaw);
window(320, 180, "Walk");
realtime(1);
return 0;
}
| Call | What it does |
|---|---|
openlevel(path), loadlevel(path), newlevel() | A level: opened, built and lit; only read; or empty |
buildlevel(L), savelevel(L, path), freelevel(L) | Build it (and its water and probes), write its .lvl, let it go |
levelerror(buf, size), levelbuilt, levellit, levelpath, levellitpath, levelprobepath | Why it didn't work, and about a level |
leveldrawbsp(L, &faces), leveldraw(L), leveldrawabove(L, y), leveldrawgpu(L), leveldrawgpuabove(L, y) | Draw it: through the BSP, all of it, only above a height, or with the graphics chip's camera |
leveltracebox(L, a, b, half-size, &nx, &ny, &nz, &hit) | How far a box gets (0 to 1), and what stopped it |
leveltrace, levelraycast (-1: nothing), levelboxsolid, levelboxinside | Lines, rays and boxes |
watercount(L), newwater(L, x0, z0, x1, z1, y), waterinfo | Its water |
waterreflect(L, i, &cam, draw, user), waterdraw(L, i, &cam, t, how) | A live reflection, then the water (how: NULL, "plain" or "baked") |
waterbake, waterbaked, waterreflections(L, i, on), watercamera(&cam) | Baked reflections, live ones on (1), off (0) or asking (-1), and the chip's camera |
bakeprobes(L), levelprobelimit(L, n) | Bake its probes a face a call (1 when done), and how many are on the card (0 asks) |
probecount, probeat(L, i), newprobe(x, y, z, size), probepos, probebake(p, draw, user, L), probebaked, probeenv | Probes, baked a face a call. probeenv is a <macawgpu.h> cube map |
levelsetprobes(L, envs, n), levelprobedata(L, buf, size), applylevelprobes(L, data, n) | Which cube maps it reflects, and its .prb bytes |
levelstart, levellightcount and levellight, levelwatercount and levelwater, levelprobecount and levelprobe | What's in it |
levelentitycount(L, class), levelentity(L, class, i, &x, &y, &z) | Its entities of a class (NULL: all of them), with their class's defaults |
levelentitynum, levelentitytext, levelentityhas, levelentityfield | An entity's field by name, as a number or text, what kind it is, and its names |
entityclasses(path), entityclasscount, entityclassname, entityclassinfo, entityclassfieldcount, entityclassfield | The kinds of entity and their fields |
leveladdbox(L, x0, y0, z0, x1, y1, z1, tex), leveladdshape(L, planes, n, tex) | Add a box (six texture names, NULL: stone) or a convex shape (4 floats a plane) |
levelbrushtexture, levelbrushwater, levelbrushglow(L, b, face, strength, colour), levelbrushshine(L, b, face, shine) | A brush's faces, water, glow and shine (face -1: all of it) |
levelbrushcount, levelbrushbox, levelremovebrush | Its brushes |
leveladdentity(L, class, x, y, z), levelentitysetnum, levelentitysettext, levelentitysetbool, levelmoveentity, levelremoveentity | Entities and their fields |
levelsetting, levelsettingtext, levelsetsetting, levelsetsettingtext | ambient, bounce, luxel, skylight and sky |
levelskies(i, buf, size), levelsky(name, pictures, &r, &g, &b), leveltexture(name), leveltexturename(i, buf, size) | Skies and the built-in textures, as pictures |
levelbake(L, lights, n, ambient, bounce, softness), levelbakestep(L, ms, &progress, what, size) | Bake its light (NULL lights: its own) |
levellightdata(L, buf, size), levelsetlight(L, data, n), levelunbake(L) | Its light as bytes to keep, putting it back, and plain shading |
levelsetsky(L, pictures), levelfacecount, levelface, levelstat(L, name) | A sky (NULL: none), its faces, and numbers like "faces" and "baked" |
Windows with controls
#include <macawui.h> for the toolkit and the dialogs. Call the widgets from _draw, between ui_begin() and ui_finish(). A value a widget changes, such as a box's tick or a text box's text, lives in your program, and you pass a pointer to it. A widget gives 1 in the frame it's changed or clicked. A list is an array of strings and how many, numbered from 0, with -1 for nothing picked. Dialogs don't wait: they call a function of yours with the answer, and don't call it if the person cancels. Text a dialog gives your function only lasts for that call, so copy it to keep it.
#include <macawui.h>
static char name[32] = "";
static int loud = 0;
static double volume = 5;
static void hello(const char *answer) {
char msg[64];
sprintf(msg, "Hello, %s!", answer);
alert(msg);
}
void _draw(void) {
ui_begin();
ui_heading("Settings");
ui_textboxex("name", name, sizeof name, "your name", 0, 0);
ui_checkbox("Loud", &loud);
ui_slider("Volume", &volume, 0, 10, 1);
ui_row(2, NULL);
if (ui_button("Greet", 0)) alert(name[0] ? name : "Hello!");
if (ui_button("Ask", 0)) askstring("Who's there?", "", hello);
ui_finish();
}
int main(void) {
window(220, 130, "Settings");
return 0;
}
| Call | What it does |
|---|---|
ui_begin(), ui_finish() | Start and end the widgets for this frame |
ui_beginex(x, y, w, bg) | The same with a margin (-1: 8), a width (0: the window's) and a background (UI_DEFAULT, or UI_KEEP to keep what's drawn) |
ui_label(s, colour), ui_heading(s), ui_separator() | Text (colour -1: the usual), a heading, a line across |
ui_button(label, w) | A button (w 0 fits the label) |
ui_checkbox(label, &on), ui_radio(label, &choice, value) | A tick box, and one of a set: ticked while choice is value, and a click sets it |
ui_slider(label, &v, min, max, step) | A slider for a double (step 0: any value) |
ui_textbox(id, buf, size), ui_textboxex(id, buf, size, placeholder, w, password) | A box to type in. It gives 1 when Enter is pressed |
ui_listbox(id, items, n, &selected, rows), ui_dropdown(id, items, n, &selected, w), ui_tabs(id, names, n, ¤t) | A list (1 on a double-click), a drop-down menu, tabs |
ui_progress(fraction, label), ui_swatches(&colour, all), ui_image(picture, scale) | A progress bar, colours to pick from, a picture |
ui_row(n, weights), ui_space(pixels), ui_group(title) ... ui_endgroup(), ui_at(x, y, w) | Side by side (NULL weights: equal), a gap, a box round some widgets, an exact place |
ui_disabled(on) | Grey out the widgets after it. It gives what it was before |
ui_focus(buf, size), ui_setfocus(id), ui_typing(), ui_rect(id, &x, &y, &w, &h), ui_nexty() | The keyboard's widget, and where widgets are |
alert(message), confirm(question, fn), askstring(prompt, initial, fn) | A message, an OK or Cancel question, a question with typing |
openfile(fn, dir, exts, n), savefile(fn, dir, name) | The Open and Save dialogs |
pickcolour(fn, hex, title) | The colour picker. fn gets "#rrggbb", and the same as 0xRRGGBB |
ondrop(fn), pickfiles(), canpickfiles(), startdrag(paths, n, label), putondesktop(path, buf, size) | Files dropped on the window, picked from the computer (the website only), dragged out, or put on the desktop |
A whole game in C
Worm is a small game written in C. It's in /home/examples/worm.c, so open it in Code and press Ctrl+R to play. Steer the worm to the red berries with the arrow keys. Each berry makes it longer, and every fifth makes it faster. It's over when the worm runs into a wall or into itself, and Enter starts another game.
It uses a lot of what's on this page:
#definenames the garden's size and the file the best score is kept in. ChangeCOLSorROWSand the window, the walls and the drawing all change with it.- Two
structs hold the game. Apointis one square, and awormis an array of points with its length and direction.w.body[i] = w.body[i - 1]copies one point over another, andsquare(w.body[i], GREEN)passes one to a function by value. on_wormis given a pointer to the worm,const worm *wm, and reads it throughwm->body.randputs each berry somewhere new.srand(time(NULL))makes every game different.fopen,fscanfandfprintfkeep the best score in/home/worm.txt, so it's still there next time.sprintfturns the score into text, andtextwidthlines text up on the right or in the middle._updatemoves the worm one square every few frames._drawdraws the whole garden again each time, from what's in the structs.
Here's all of it:
/* Worm: a whole game in C. Steer the worm to the berries with the arrow keys. Each one
makes it longer, and every fifth makes it faster. Don't hit the walls or yourself.
Ctrl+R in Code compiles and runs it. The best score is kept in /home/worm.txt. */
#include <macaw.h>
#include <time.h>
#define CELL 8 /* each square of the garden, in pixels */
#define COLS 20
#define ROWS 14
#define TOP 12 /* the score bar's height */
#define MAXLEN (COLS * ROWS)
#define BEST_FILE "/home/worm.txt"
typedef struct {
int x, y;
} point;
typedef struct {
point body[MAXLEN]; /* body[0] is the head */
int length;
int dx, dy; /* the way it's going */
int nextdx, nextdy; /* the way the keys last said to go */
} worm;
static worm w;
static point berry;
static int score, best, over, ticks, speed;
/* the best score so far, from its file (0 if there isn't one yet) */
static int load_best(void) {
FILE *f = fopen(BEST_FILE, "r");
int n = 0;
if (f) {
if (fscanf(f, "%d", &n) != 1) n = 0;
fclose(f);
}
return n;
}
static void save_best(int n) {
FILE *f = fopen(BEST_FILE, "w");
if (f) {
fprintf(f, "%d\n", n);
fclose(f);
}
}
/* is p on one of the first n squares of the worm? */
static int on_worm(const worm *wm, point p, int n) {
int i;
for (i = 0; i < n; i++)
if (wm->body[i].x == p.x && wm->body[i].y == p.y) return 1;
return 0;
}
/* a berry somewhere the worm isn't */
static void place_berry(void) {
do {
berry.x = rand() % COLS;
berry.y = rand() % ROWS;
} while (on_worm(&w, berry, w.length));
}
static void restart(void) {
int i;
w.length = 4;
for (i = 0; i < w.length; i++) {
w.body[i].x = 8 - i;
w.body[i].y = ROWS / 2;
}
w.dx = w.nextdx = 1;
w.dy = w.nextdy = 0;
score = 0;
over = 0;
ticks = 0;
speed = 8; /* frames between moves */
place_berry();
}
/* turn, but never straight back on itself */
static void steer(int dx, int dy) {
if (dx != -w.dx || dy != -w.dy) {
w.nextdx = dx;
w.nextdy = dy;
}
}
static void game_over(void) {
over = 1;
sfx("lose");
if (score > best) {
best = score;
save_best(best);
}
}
/* one move of one square */
static void step(void) {
point head;
int i, grow;
w.dx = w.nextdx;
w.dy = w.nextdy;
head.x = w.body[0].x + w.dx;
head.y = w.body[0].y + w.dy;
grow = head.x == berry.x && head.y == berry.y;
/* the tail moves out of the way, unless the worm is growing */
if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= ROWS
|| on_worm(&w, head, grow ? w.length : w.length - 1)) {
game_over();
return;
}
if (grow) w.length++;
for (i = w.length - 1; i > 0; i--) w.body[i] = w.body[i - 1];
w.body[0] = head;
if (grow) {
score++;
sfx("coin");
if (score % 5 == 0 && speed > 3) speed--;
if (w.length == MAXLEN) game_over(); /* the whole garden is worm */
else place_berry();
}
}
void _update(void) {
if (over) {
if (btnp("enter") || btnp("space")) restart();
return;
}
if (btnp("left")) steer(-1, 0);
if (btnp("right")) steer(1, 0);
if (btnp("up")) steer(0, -1);
if (btnp("down")) steer(0, 1);
if (++ticks >= speed) {
ticks = 0;
step();
}
}
static void square(point p, int colour) {
rectfill(p.x * CELL, TOP + p.y * CELL, CELL - 1, CELL - 1, colour);
}
static void centred(const char *s, int y, int colour) {
text(s, (COLS * CELL - textwidth(s)) / 2, y, colour);
}
void _draw(void) {
char line[32];
int i;
cls(FOREST);
rectfill(0, 0, COLS * CELL, TOP, NIGHT);
sprintf(line, "Score %d", score);
text(line, 2, 2, WHITE);
sprintf(line, "Best %d", best);
text(line, COLS * CELL - textwidth(line) - 2, 2, YELLOW);
circfill(berry.x * CELL + 3, TOP + berry.y * CELL + 3, 3, RED);
for (i = w.length - 1; i > 0; i--) square(w.body[i], GREEN);
square(w.body[0], LIME);
if (over) {
rectfill(16, 44, COLS * CELL - 32, 36, NIGHT);
centred("Game over", 50, WHITE);
centred("Enter plays again", 64, SILVER);
}
}
int main(void) {
srand((unsigned)time(NULL));
best = load_best();
restart();
window(COLS * CELL, TOP + ROWS * CELL, "Worm");
realtime(1);
return 0;
}
Some things to try: make the worm come out the other side when it reaches an edge instead of crashing, put a few rocks in the garden, or give it a second berry that makes it shorter.