CHIVO-8 MANUAL
Commands, keys, programming functions and step-by-step lessons · version 0.9.5
🚀 Getting started
Chivo-8 is a fantasy video game console: you draw the characters, build the level, make the sounds, program the game and play it, all on a 128x128 pixel screen with 16 colors (or 240x136, inspired by TIC-80).
- When it opens you see the command line: type
HELPto see the commands. - Type
LEARNto see the lessons andLEARN 1to start the first one. - Rather start from a game that already works?
NEW WORLD,NEW PLATFORM,NEW SHIP,NEW CATCH,NEW MAZEorNEW RACE: at the top of the code it says «CHANGE HERE». - If something breaks, the game screen tells you what happened and on which line.
- Esc takes you to the editors; F6 plays.
- Your work is saved on this device by itself;
SAVE MYGAME(or any name) gives it a name andGOOGLE+UPLOADtakes it to the cloud. - Type
LANG ESto switch the console to Spanish (IDIOMA ENswitches back).
A game has three parts that the console calls by itself:
function _init() -- once, at the start
end
function _update() -- 30 times per second: move, collide, count
end
function _draw() -- after each _update: draw
cls(1)
print('HELLO', 52, 60, 7)
end🧩 Templates: start with a ready-made game
Instead of starting from scratch, type NEW and the name
of a template: it is a short game that already works, made with shapes (you do not need to draw first). At the top of the code there is a
«CHANGE HERE» block with the numbers that decide how it feels: speed, jump, colors, difficulty.
NEW WORLD | A 3-screen platformer with sprites, map and markers already made: edit everything in Sprites and Map. |
NEW PLATFORM | Platformer: you walk, jump and collect coins. |
NEW SHIP | A ship that shoots what comes down. Change CADA to make it harder. |
NEW CATCH | Catch what falls with a basket; it falls faster and faster. |
NEW MAZE | A maze seen from above. Add walls in the paredes table. |
NEW RACE | Dodge the cars by changing lanes. |
At the end of each template's code there are 3 challenges to keep practicing.
Ideas to keep going: draw your character in Sprites and change rectfill(x, y, 8, 8, ...) to spr(1, x, y) (lesson 16);
add sounds from the library (SOUNDS); add enemies with lesson 9.
Open a library game
OPEN SALTARIN (or the ✎ button next to each game in the Play Library) puts a whole Chivo-8 game in your editors: the code in CODE and its drawings in SPRITES. Change a sprite or a number and press RUN: the game uses yours. At the top of the code a note says where everything is; SAVE MI-SALTARIN saves it as yours. OPEN alone shows the list.
⌨️ Keys and shortcuts
F1 … F5 | Editors: Code, Sprites, Map, Effects and Music. |
F6 | Play on the Game Boy, with the game library. |
Esc | Back to the command line (or to the lesson editor). |
Ctrl+R | Run the game from the code editor. |
Ctrl+Z · Ctrl+Y | Undo · redo. |
Ctrl+F · Ctrl+G · Ctrl+O | Code: find · go to a line · list of functions. |
Tab | Map: see the whole world. |
F7 · F8 · F9 | In Play: photo · GIF · video of the game (with its sound). WAV downloads the song as audio. |
Arrows + Z / X | Player 1 controls (also WASD and N / M). Player 2: J L I K + U / O. |
Bluetooth or USB controller | Xbox, PlayStation, 8BitDo and most others: pair it with your phone or PC and press a button. The 1st is player 1 and the 2nd is player 2. D-pad or stick = arrows; bottom = Z, right = X, left = C, top = V. CONTROLLER lists them and LEARN 31 tests them. |
P · O | Sound effects and Music: P opens the piano and O the wave view (on the phone, tap the bottom line or the TON column). |
R · W | Music: R records as you play (the pattern loops with a metronome and each note lands on the step that is playing; on the phone, the piano + button turns into REC) · W changes the swing (0, 1, 2). |
Shift + ↑ ↓ · Ctrl+C / Ctrl+V | Sound effects and Music: transpose the whole pattern one semitone · copy and paste the whole pattern. In the terminal: TRANSPOSE, COPYPATTERN, SWING and DRUMS. |
On-screen keyboard (phone)
Open it with the ⌨ button and close it with ▼. The numbers are on the
third row (1 … 0 and ⌫), below the symbols row and above Q W E R T Y.
- Shift once (green): only the next key comes out with Shift.
- Shift twice quickly (yellow): it stays on; with it the numbers turn into
! @ # $ % ^ & * ( )and letters come out in CAPITALS. Tap it again to turn it off and get the numbers back. - On the command line upper or lower case does not matter; in the code it does.
🖌️ The editors
With Esc you go back and forth between the command line and the last editor. The F keys switch editors.
F2 · Sprites
- Top left, the sprite, big (8x8 pixels); on the right, the palette; at the bottom, the sheet with the sprites (512 in 4 tabs).
- Tools: pencil, fill, pick color, undo and redo, horizontal and vertical flip, and rotate.
- 1× 2× 4× edits 1, 2x2 or 4x4 sprites together (bigger characters).
- Under the sprite number are its 8 flags: boxes your code reads with
fget(n, flag). By convention, flag 0 = solid (the character cannot go through it). - Tap a palette color twice to change it (red, green and blue). Also with
COLOR N #RRGGBB. - Your sprite is drawn in the game with
spr(number, x, y). Leave #0 empty: it is the «air» of the map.
F3 · Map
- The map is 240x136 tiles; each tile is a sprite. Tap a sprite at the bottom and paint by dragging.
- Tools: paint, erase, pick tile, move the view, undo, redo, zoom and whole world (also with Tab).
- In the game it is drawn with
map(x, y, ...)and read withmget(x, y). WithBANK Nyou get up to 8 sets of sprites + map per cartridge.
F4 · Effects and F5 · Music
Both editors work the same: 16 steps, each with its note, volume, octave and command. It is all explained in Sound and music.
F1 · Code
- You write in Lua (or JavaScript). The text colors help you spot keywords, numbers and strings.
- Ctrl+R runs the game · Ctrl+F find · Ctrl+G go to a line · Ctrl+O list of functions · Ctrl+/ comment lines.
- If something breaks, the game screen tells you what happened and on which line (see Common errors).
F6 · Play
- The console turns into a Game Boy: the LIBRARY has the example games, the TIC-80 classics and the community games.
- Buttons for a photo (F7), GIF (F8) and video (F9) of your game.
CRT 1toCRT 5add an old-screen filter.
🎨 The 16 colors
Colors are used by number: cls(1) paints the background dark blue and
print('HELLO', 2, 2, 7) writes in white. These are the usual palette (PICO-8); with PALETTE you pick another of the 12
and the numbers stay the same, only the shade changes.
0 | black |
1 | dark blue |
2 | dark purple |
3 | dark green |
4 | brown |
5 | dark gray |
6 | light gray |
7 | white |
8 | red |
9 | orange |
10 | yellow |
11 | green |
12 | blue |
13 | indigo |
14 | pink |
15 | peach |
🔊 Sound and music
There are two kinds of sound: effects (short: jump, coin, explosion) and music (melodies that loop).
Effects (F4)
- 64 slots. Built in:
0coin,1jump,2hit,3power-up,4explosion. In your code:sfx(1).
Music (F5)
- 20 patterns (little pieces of music).
music(0)loops pattern 0 andmusic(-1)stops it. - The song (SONG button) puts patterns together: 4 channels that play at once (melody, bass, drums…) over 8 slots in a row.
track()plays it all.
How a sound is made
- Each effect or pattern has 16 steps. On each step you choose the note (you draw the bars; 16 notes from C to D#, one semitone apart), the volume (1 to 4), the octave (−2 to +2) and a command (CMD row: tap it to change it; its name shows below): M major chord, m minor chord, 5 fifth, A major arpeggio and a minor arpeggio (the chord notes one after another, very fast: the classic console sound), V vibrato (wobble), S slide (glides in from the previous note) and C drop (the note plunges: shots, hits, something falling).
- The wave is the timbre of the whole sound: square (classic video game), triangle (soft, good for bass), saw (harsh), sine (clean) and noise (explosions and percussion). With ED you draw 4 waves of your own.
- Speed goes from 0.5x to 2x.
- Piano: the keys
Z S X D C V G B H N J M , L . ;play the notes like a keyboard and write them into the selected step. On the phone, tap the bottom line (or thePkey): a 16-key piano shows up with 4 buttons on the left: the command it plays with (A, C, V…), the octave, + write (puts the note with that command and octave into the step and moves on; off = it only plays) and X close. Use it to hear each effect before writing it. tono(262, 0.2, 1)plays a single note from your code: frequency (262 = C), duration in seconds and wave (0 square, 1 triangle, 2 saw, 3 sine, 4 noise).
Sounds, music and waves are saved with your cartridge: if you share the game, its sounds go with it.
Library: SOUNDS and SONG
SOUNDS PUT copies 20 ready-made effects into your cartridge (from 5 to 24) and SOUNDS 5 lets you hear them.
SONG HAPPY, SONG ADVENTURE or SONG MYSTERY load a short song (patterns 10 to 18) that plays with track().
Afterwards you can change them in the editors.
sfx(5) | Laser |
sfx(6) | Shot |
sfx(7) | Extra life |
sfx(8) | Lose |
sfx(9) | Menu |
sfx(10) | Accept |
sfx(11) | Cancel |
sfx(12) | Step |
sfx(13) | Door |
sfx(14) | Pick up |
sfx(15) | Damage |
sfx(16) | Big explosion |
sfx(17) | Boing |
sfx(18) | Bell |
sfx(19) | Alarm |
sfx(20) | Teleport |
sfx(21) | Buzz |
sfx(22) | Double coin |
sfx(23) | Bubble |
sfx(24) | Win |
💬 Console commands
They are typed on the command line (upper or lower case). What goes between < > is required; between [ ], optional. HELP COMMAND explains one. Every command also works with its Spanish name.
HELP [COMMAND]also: AYUDA | Help, or help for one command |
LSalso: DIR, CARTS | Your cartridges on this device |
LOAD <NAME>also: CARGAR | Open a saved cartridge |
OPEN [GAME]also: ABRIR, REMIX | Open a library game in the editors to change it |
SAVE [NAME]also: GUARDAR | Save the cartridge |
NEW [TEMPLATE]also: NUEVO | Blank cartridge or one from a game template |
DEL <NAME>also: BORRAR | Delete a saved cartridge |
RENAME <OLD> <NEW>also: RENOMBRAR | Change the name |
EXPORT [HTML|PNG [N]]also: EXPORTAR, DESCARGAR | .json, html for itch.io or sprites as png |
IMPORT [PNG]also: IMPORTAR | Open a .json, chivo-8 code (.lua/.js), a tic-80 game (.lua, .js, .fnl or .tic) or a png image |
SCREEN [128|240]also: PANTALLA | Your game screen size: 128×128 or 240×136 (the tic-80 one) |
LEARN [NUMBER]also: APRENDE, LECCION, LECCIÓN | Step-by-step lessons |
LUA [NUMBER] | The lua language, part by part |
CONTROLLERalso: CONTROL, MANDO, GAMEPAD | Bluetooth or usb controller |
LANGUAGES [NUMBER]also: LENGUAJES | Lua next to other languages |
NEXTalso: SIGUE, SIGUIENTE | Next step of the lesson |
BACKalso: ATRAS, ATRÁS | Previous step |
PUTalso: PONER, USAR, USE | Put in the code from this step |
RUNalso: CORRER, JUGAR | Play the cartridge |
CODEalso: CODIGO, CÓDIGO | Code editor |
SPRITES | Sprite editor |
MAPalso: MAPA | Map editor |
SFXalso: EFECTOS | Sound effects |
SHELL [COLOR]also: CARCASA, GAMEBOY | Color of the play game boy |
SOUNDS [PUT|N]also: SONIDOS | Library of ready-to-use sound effects |
SONG [NAME]also: CANCION, CANCIÓN | Short songs ready for your game |
DRUMS [STYLE]also: BATERIA, BATERÍA | Ready-made drum beats for your song |
TRANSPOSE <+N|-N> [PATTERN]also: TRANSPONER | Move a whole pattern up or down |
COPYPATTERN <FROM> <TO>also: COPIAPATRON, COPIAPATRÓN | Copy a music pattern |
SWING [0|1|2] [PATTERN] | Rhythm swing: 0 even, 1 a bit, 2 a lot |
WAV [PATTERN] | Download your song (or a pattern) as audio |
MUSICalso: MUSICA, MÚSICA | Music |
CRT [1-5|NO] | Screen filter: 1 classic · 2 arcade · 3 old tv · 4 phosphor · 5 lcd |
CLSalso: LIMPIAR | Clear the screen |
PALETTE [NUMBER]also: PALETA | See or change the cartridge palette |
COLOR [N #RRGGBB | RESET] | Change one palette color |
BANK [0-7]also: BANCO | Edit another bank of sprites and map |
MEMalso: MEMORIA | Memory map (peek/poke) |
INFO [FIELD TEXT]also: DATOS, DATA | Author, description, version… |
VERSIONalso: VERSIÓN | Console version and what is new |
CHANGELOG [VERSION]also: NOVEDADES, CAMBIOS, NEWS | What changed in each version |
STUDIOalso: ESTUDIO | Open the classic studio |
ARCADE | Go to the arcade |
MANUAL [TOPIC|N]also: GUIA, GUÍA, GUIDE | Manual: commands, keys, functions and lessons |
QUESTIONSalso: DUDAS, VIDEOS, SUGERENCIAS | Videos, manual, questions and suggestions |
TUTORIAL | Step-by-step lessons |
PUBLISH [NAME]also: PUBLICAR | Send your game to the community |
UNPUBLISH [NAME]also: DESPUBLICAR, OCULTAR | Remove it from the community |
SHARE [NAME]also: COMPARTIR, LINK | Link to play it directly |
PENDINGalso: PENDIENTES | Moderate: games to review |
TRY <N>also: PROBAR | Moderate: play a pending one |
APPROVE <N>also: APROBAR, RECHAZAR, REJECT | Moderate: decide (approve or reject) |
LOGIN <EMAIL>also: ENTRAR | Sign in to your account |
GOOGLE | Sign in with your google account |
SIGNUP <EMAIL>also: REGISTRO | Create an account |
LOGOUTalso: CERRAR | Sign out |
WHOAMIalso: QUIEN, QUIÉN | Which account you are using |
CLOUDalso: NUBE | Your cartridges in the cloud |
UPLOAD [NAME]also: SUBIR | Save to your account |
DOWNLOAD <NAME>also: BAJAR | Open from your account |
INSTALLalso: INSTALAR, APP | Install chivo-8 as an app (shortcut) |
DELETEACCOUNTalso: BORRARCUENTA, PRIVACIDAD, PRIVACY | Privacy and how to delete your account |
UPDATEalso: ACTUALIZAR | Get the new version of the app |
LANG [ES|EN]also: IDIOMA, LANGUAGE | Console language: spanish or english |
FONT [CLASSIC|ROUND]also: LETRA | Font style: classic or round |
KEYBOARD [CHIVO|PHONE]also: TECLADO | Keyboard: chivo-8 or your phone |
💻 Programming: functions
Games are written in Lua (recommended to start) or JavaScript. The Lua basics:
local vidas = 3 -- a variable
if vidas == 0 then ... end -- a condition
for i = 1, 10 do ... end -- repeat 10 times
local function saltar() ... end -- a function
local enemigos = {} -- a table (list)
enemigos[#enemigos + 1] = { x = 10, y = 20 }
for _, e in ipairs(enemigos) do rectfill(e.x, e.y, 8, 8, 8) end
print('POINTS: ' .. puntos, 2, 2, 7) -- .. joins textScreen and drawing
cls(color) | Clears the screen with a color (0 if none is given). |
pset(x, y, color) | Paints a pixel. |
pget(x, y) | Reads the color of a pixel. |
line(x1, y1, x2, y2, color) | A line between two points. |
rect(x, y, width, height, color) | Rectangle outline only. |
rectfill(x, y, width, height, color) | Filled rectangle. |
circ(x, y, radius, color) · circfill(...) | Circle outline or filled. |
elli(x, y, a, b, color) · ellib(...) | Filled or outline ellipse (a and b are the radii). |
tri(x1, y1, x2, y2, x3, y3, color) · trib(...) | Filled or outline triangle. |
print(text, x, y, color) | Writes text. Returns the width in pixels (handy for centering). |
camera(x, y) · camera() | Shifts everything that is drawn (screen shake, scrolling). With no numbers it goes back to 0, 0. |
clip(x, y, width, height) · clip() | Only draws inside that rectangle. |
pal(c1, c2) · pal() | Draws color c1 as c2 (recolor a sprite). pal() undoes it. |
palt(color, true/false) · palt() | Makes a color transparent (or not) when drawing. |
Sprites and map
spr(n, x, y, [width, height, flipX, flipY, scale, rotation]) | Draws sprite n. Width and height in sprites (2, 2 = 16x16); scale 2 = double size; rotation 1-3 = 90° each. |
sget(x, y) · sset(x, y, color) | Reads or paints a pixel of the sprite sheet (128x256). |
map(cellX, cellY, x, y, width, height) | Draws a piece of the map (in 8x8 cells). |
mget(cx, cy) · mset(cx, cy, n) | Reads or changes the sprite in a map cell (240x136 cells). |
fget(n, flag) · fset(n, flag, value) | Flags of each sprite (0-7), for example "solid" or "harmful". |
mfind(n) · mbuscar(n) | Finds every place on the map where you put sprite n (start, enemies, coins), removes it from the map and gives you the list with x, y in pixels. mfind(n, false) keeps them. |
flag 7 = animated tile | Consecutive sprites with flag 7 take turns by themselves on the map (5 per second), no code. spr() draws them still. |
banco(n) | Switches to sprite and map bank n (0-7) while playing. |
Controls
btn(b) · btnp(b) | btn: the button is held. btnp: it was just pressed. 0 left, 1 right, 2 up, 3 down, 4 Z, 5 X. Player 2: 8-13 (J L I K U O). |
key(name) · keyp(name) | Any key: 'a', 'space', 'enter', 'up'… |
mouse() | Mouse or touch: x, y and the buttons. |
Sound
sfx(n) | Plays effect n (you make them in Effects, F4). |
music(n) · music(-1) | Loops music pattern n; -1 stops it. |
track() | Plays the whole song (the patterns on the 4 channels). |
tono(frequency, duration, wave, volume) | A direct tone, no editor needed. Wave: 0 square, 1 triangle, 2 saw, 3 sine, 4 noise. |
Saving and memory
cartdata(name) | Opens a memory with 64 slots that is not erased when you close the page. |
dget(i) · dset(i, value) | Reads or saves slot i (high score, level…). |
peek(address) · poke(address, value) | Reads or changes the console memory: screen, sprites, map, flags and palette (MEM command). |
memcpy(dest, source, length) · memset(dest, value, length) | Copies or fills chunks of memory. |
Other
time() · t() | Seconds since the game started. |
stat(7) | Real frames per second. |
trace(text) | Writes to the browser console (to track down bugs). |
W · H | Width and height of the game screen (128x128, or 240x136 with SCREEN 240). |
📚 Step-by-step lessons
The same lessons are inside the console: LEARN N starts one, NEXT and BACK move along, PUT copies the step's code and RUN plays it.
Lesson 1 · Your first sprite
- Look at the editor. In Sprites (F2): top left is the sprite, big; on the right the palette; and at the bottom the sheet with all your sprites.
- Pick sprite #1. On the sheet at the bottom tap square #1 (the second one). Leave #0 empty: it is the air of the map.
- Paint with the pencil. Pick a color from the palette and paint with the pencil. Each big square is one pixel. Mistake? Ctrl+Z or the undo button.
- Try fill. Fill paints an area in one color, and pick color copies one you already used. Try flip and rotate to make variations.
- Outline and shine. Tip: first a dark outline, then the fill, and last a light pixel for shine. 3 colors are enough.
Lesson 2 · An animated character
- 2x and block #16. Tap 2X: now you edit 4 sprites together (16x16). On the sheet pick the block that starts at #16.
- Draw 2 frames. Draw your character standing. Then pick the block next to it (#18) and draw it again with the legs switched.
- Tap anim. Go back to #16 and tap ANIM: the canvas plays your frames as an animation. Tap it again for 3 or 4 frames.
- Spr(16, x, y, 2, 2). In code, a 16x16 sprite is drawn with spr(16, x, y, 2, 2): the last two numbers are width and height in sprites.
Lesson 3 · Build a level
- Floor on #2 + flag 0. In Sprites draw a floor tile on #2. With that sprite selected, turn on flag 0 (the first little square in the row of flags): it means solid.
- Paint the floor. Go to Map (F3). On the sheet at the bottom tap your tile #2 and paint by dragging your finger: make the floor at the bottom.
- Platforms. Add platforms. To stamp a big block, drag over the sheet (up to 4x4). Erase removes tiles.
- Move with the hand. The map is huge (240x136). Move around with the hand or the arrows; the magnifier gives a wide view. The dotted lines mark one screen (16x16).
Lesson 4 · A sound effect
- Effect 00, square. In Effects (F4) pick effect 00 with < and >. Tap the square wave: it sounds like a classic console.
- Two rising notes. The bars are the pitch: draw one halfway up on step 1 and a higher one on step 2. Two rising notes = ding!
- Test and volume. Tap TEST. Under each step there is volume (green), octave and command. Lower the volume of the last step so it fades out softly.
- Effect 01: jump. Make another one on 01 for the jump: notes that rise fast, triangle wave. For an explosion: noise and a falling volume.
Lesson 5 · A melody
- Pattern 00, triangle. In Music (F5) pick pattern 00. It is like a longer effect, made to repeat. Pick the triangle wave.
- Notes and play. Use a few different notes and repeat them: that is what makes it catchy. Tap play to hear it; 1X changes the speed.
- Pattern 01: bass. Make pattern 01 with a low line (the bass), square wave and few notes.
- Build the song. Tap SONG: on channel 1, slot 1, put 00; on channel 2, slot 1, put 01. They play together. Play plays the whole song.
Lesson 6 · Bring it to life with code
- _init _update _draw. Every game has 3 parts: _init() at the start, _update() for the logic (30 times per second) and _draw() to draw.
- Put, then run. This example moves your sprite #1 with the arrows over your level.
-- Your sprite #1 moves with the arrows over your level. local x, y = 20, 20 function _update() if btn(0) then x = x - 1 end -- left if btn(1) then x = x + 1 end -- right if btn(2) then y = y - 1 end -- up if btn(3) then y = y + 1 end -- down end function _draw() cls(1) -- dark blue background map(0, 0, 0, 0, 16, 16) -- your level spr(1, x, y) -- your sprite #1 end - Ctrl+r or run. Type RUN (or Ctrl+R in Code): your sprite moves with the arrows or with the Game Boy d-pad.
- Put: with collisions. So it does not go through walls, check flag 0 of the tile it is moving into. This example collides, plays sfx(0) and plays your music.
-- It no longer goes through walls: it checks flag 0 -- (solid) of the tile it moves into. It plays sfx(0) when it bumps. local x, y = 20, 20 local function solido(px, py) return fget(mget(px // 8, py // 8), 0) end local function libre(nx, ny) return not (solido(nx, ny) or solido(nx + 7, ny) or solido(nx, ny + 7) or solido(nx + 7, ny + 7)) end local function mover(dx, dy) if libre(x + dx, y + dy) then x, y = x + dx, y + dy else sfx(0) end end function _init() music(0) end function _update() if btn(0) then mover(-1, 0) end if btn(1) then mover(1, 0) end if btn(2) then mover(0, -1) end if btn(3) then mover(0, 1) end end function _draw() cls(1) map(0, 0, 0, 0, 16, 16) spr(1, x, y) print('MY GAME', 2, 2, 7) end - Sfx(0) and music(0). sfx(0) plays your effect 00; music(0) loops your pattern; track() plays the whole song. You have a game!
Lesson 7 · Save and share
- Save and a name. Type SAVE and a name, for example SAVE MYGAME. It stays on this device with everything: sprites, map, sound and code.
- Info author. Add your info: INFO AUTHOR YOUR NAME and INFO DESC WHAT IT IS ABOUT.
- Google and upload. Sign in with GOOGLE and type UPLOAD: your game follows you to any device.
- A gif to share. In Play (F6) tap GIF to record a short clip and share it. EXPORT downloads it as a file.
Lesson 8 · Points and text
- Variables. A variable stores a value that changes: local puntos = 0. With puntos = puntos + 10 you add to it.
- Put: coins. This example makes a coin collecting game with points.
-- Collect coins: each one gives 10 points. local x, y = 60, 60 -- your character local mx, my = 20, 20 -- the coin local puntos = 0 local function nuevaMoneda() mx = math.random(8, 112) my = math.random(16, 112) end function _update() if btn(0) then x = x - 2 end if btn(1) then x = x + 2 end if btn(2) then y = y - 2 end if btn(3) then y = y + 2 end -- touching it? (less than 8 apart in x and in y) if math.abs(x - mx) < 8 and math.abs(y - my) < 8 then puntos = puntos + 10 sfx(0) nuevaMoneda() end end function _draw() cls(1) circfill(mx + 3, my + 3, 3, 10) -- yellow coin rectfill(x, y, 8, 8, 11) -- green character print('POINTS: ' .. puntos, 2, 2, 7) end - Print. print('POINTS: ' .. puntos, 2, 2, 7) writes on the screen: text, x, y and color. The two dots .. join text with numbers.
- Math.random. math.random(8, 112) gives a random number between 8 and 112: that is how the coin shows up somewhere else. Try changing the numbers.
Lesson 9 · Enemies
- Tables. A table stores many things together: enemigos[1] = { x = 10, y = 20 }. With for _, e in ipairs(enemigos) you go through all of them.
- Put: enemies. Enemies that bounce off the edges. If they touch you, you lose a life and blink for a while.
-- Bouncing enemies. If they touch you, you lose a life. local x, y = 60, 100 local vidas, invencible = 3, 0 local enemigos = {} function _init() for i = 1, 4 do -- each enemy is a table with position and velocity enemigos[i] = { x = math.random(0, 120), y = math.random(0, 60), vx = math.random(1, 2), vy = math.random(1, 2) } end end local function choca(a, b) -- two 8x8 squares overlap return math.abs(a.x - b.x) < 8 and math.abs(a.y - b.y) < 8 end function _update() if vidas <= 0 then return end if btn(0) then x = x - 2 end if btn(1) then x = x + 2 end if btn(2) then y = y - 2 end if btn(3) then y = y + 2 end if invencible > 0 then invencible = invencible - 1 end for _, e in ipairs(enemigos) do e.x, e.y = e.x + e.vx, e.y + e.vy if e.x < 0 or e.x > 120 then e.vx = -e.vx end if e.y < 0 or e.y > 120 then e.vy = -e.vy end if invencible == 0 and choca(e, { x = x, y = y }) then vidas = vidas - 1 invencible = 60 -- 2 seconds without damage end end end function _draw() cls(0) for _, e in ipairs(enemigos) do rectfill(e.x, e.y, 8, 8, 8) end if invencible % 6 < 3 then rectfill(x, y, 8, 8, 12) end -- blinks print('LIVES: ' .. vidas, 2, 2, 7) if vidas <= 0 then print('GAME OVER', 38, 60, 8) end end - Collisions. Two 8x8 squares collide if they are less than 8 pixels apart in x and in y: math.abs(a.x - b.x) < 8 and math.abs(a.y - b.y) < 8.
- Challenge. Challenge: make one more enemy appear every 10 seconds (hint: a counter and table.insert).
Lesson 10 · Gravity and jumping
- Velocity. To jump you use a vertical velocity vy: every frame y = y + vy, and gravity adds a little to vy.
- Put: jump. A character that jumps between platforms with Z.
-- Gravity and jumping: Z jumps, arrows to move. local x, y, vy = 20, 20, 0 local enSuelo = false local plataformas = { { x = 0, y = 120, w = 128 }, -- the floor { x = 20, y = 92, w = 30 }, { x = 70, y = 70, w = 30 }, { x = 30, y = 46, w = 24 }, } function _update() if btn(0) then x = x - 2 end if btn(1) then x = x + 2 end if btnp(4) and enSuelo then vy = -5 end -- jump vy = math.min(vy + 0.3, 4) -- gravity pulls down y = y + vy enSuelo = false for _, p in ipairs(plataformas) do -- lands on a platform: stands on top of it if vy >= 0 and x + 7 >= p.x and x <= p.x + p.w and y + 8 >= p.y and y + 8 <= p.y + 6 then y, vy, enSuelo = p.y - 8, 0, true end end end function _draw() cls(12) for _, p in ipairs(plataformas) do rectfill(p.x, p.y, p.w, 4, 4) end rectfill(x, y, 8, 8, 8) print('Z: JUMP', 2, 2, 1) end - Btnp vs btn. btn(4) is true while you hold it; btnp(4) only at the moment you press it. For jumping you use btnp.
- Tune the jump. Change vy = -5 (more negative = higher jump) and 0.3 (bigger = falls faster) until it feels right.
Lesson 11 · Title, game and end
- States. A game switches screens with a state variable: 'titulo' (title), 'juego' (game) or 'fin' (end). _update and _draw do something different in each one.
- Put: screens. Title, 10 seconds of play and an end screen with your points.
-- A game has screens: title, game and end. local estado = 'titulo' local tiempo, puntos = 0, 0 function _update() if estado == 'titulo' then if btnp(4) then estado, tiempo, puntos = 'juego', 0, 0 end elseif estado == 'juego' then tiempo = tiempo + 1 if btnp(4) then puntos = puntos + 1 end -- press Z fast if tiempo >= 300 then estado = 'fin' end -- 10 seconds elseif estado == 'fin' then if btnp(5) then estado = 'titulo' end end end function _draw() cls(1) if estado == 'titulo' then print('MY GAME', 48, 50, 10) print('Z: START', 44, 70, 7) elseif estado == 'juego' then print('PRESS Z!', 42, 50, 7) print('POINTS: ' .. puntos, 42, 62, 11) rectfill(14, 100, 100 - tiempo // 3, 4, 8) -- time bar else print('END', 58, 50, 8) print('YOU GOT ' .. puntos, 46, 62, 7) print('X: AGAIN', 42, 80, 6) end end - Move it into your game. Copy the idea into your game: move your game code inside if estado == "juego".
Lesson 12 · Save the high score
- Cartdata. cartdata('mi_juego') opens a memory with 64 slots that is not erased when you close the page. Use a unique name for your game.
- Put: high score. Press Z as fast as you can: if you beat the high score, it is saved.
-- The high score is saved even if you close the page. cartdata('mi_juego') -- the name of your "memory" local record = dget(0) -- slot 0: the saved high score local puntos, tiempo = 0, 300 function _update() if tiempo > 0 then tiempo = tiempo - 1 if btnp(4) then puntos = puntos + 1 end if tiempo == 0 and puntos > record then record = puntos dset(0, record) -- save it end elseif btnp(5) then puntos, tiempo = 0, 300 end end function _draw() cls(0) print('PRESS Z FAST', 30, 40, 7) print('POINTS: ' .. puntos, 30, 56, 11) print('HIGH SCORE: ' .. math.floor(record), 30, 66, 10) if tiempo == 0 then print('X: AGAIN', 30, 86, 6) end end - Dget and dset. dget(0) reads slot 0 and dset(0, value) saves it. You can save the level, lives or coins in other slots.
Lesson 13 · Particles and effects
- Lots of sparks. A particle is a point with position, velocity and life. They are kept in a table and removed when their life runs out.
- Put: explosion. Z makes an explosion of 30 sparks and the screen shakes.
-- Particles: Z makes an explosion and the screen shakes. local chispas, temblor = {}, 0 local function explosion(x, y) for i = 1, 30 do local a, v = math.random() * 6.28, math.random() * 3 chispas[#chispas + 1] = { x = x, y = y, vx = math.cos(a) * v, vy = math.sin(a) * v, vida = math.random(15, 30) } end temblor = 8 end function _update() if btnp(4) then explosion(math.random(30, 98), math.random(30, 98)) end for i = #chispas, 1, -1 do -- back to front so we can remove items local c = chispas[i] c.x, c.y, c.vy = c.x + c.vx, c.y + c.vy, c.vy + 0.1 c.vida = c.vida - 1 if c.vida <= 0 then table.remove(chispas, i) end end if temblor > 0 then temblor = temblor - 1 end end function _draw() camera(math.random(-temblor, temblor) // 2, math.random(-temblor, temblor) // 2) cls(0) for _, c in ipairs(chispas) do pset(c.x, c.y, c.vida > 20 and 10 or (c.vida > 10 and 9 or 8)) -- yellow, orange, red end camera() print('Z: EXPLOSION', 2, 2, 7) end - Camera. camera(x, y) moves everything you draw; with random numbers the screen shakes. camera() puts it back in place.
- Use it. Use explosion(x, y) when an enemy dies or when you pick something up: effects make the game feel alive.
Lesson 14 · Tic-80 games
- Tic-80 classics. In Play (F6) open the LIBRARY: under TIC-80 Classics there are community games with an open license. Play one.
- Put: tic-80 style. Chivo-8 also understands TIC-80 code: everything in TIC(), a 240x136 screen and filled rect.
-- title: my TIC-80 style game -- script: lua -- This is how a TIC-80 game is written: everything happens in TIC(), -- the screen is 240x136 and the buttons are 0 up, -- 1 down, 2 left, 3 right, 4 = Z and 5 = X. x, y = 116, 64 function TIC() if btn(0) then y = y - 1 end if btn(1) then y = y + 1 end if btn(2) then x = x - 1 end if btn(3) then x = x + 1 end cls(13) rect(x, y, 8, 8, 2) -- in TIC-80 rect is filled print('HELLO FROM TIC-80', 70, 20, 0) end - Screen 128 or 240. Your game can use 128x128 (Chivo-8) or 240x136 (TIC-80): type SCREEN 240 or SCREEN 128. In the code, W and H tell the size.
- Import. IMPORT opens TIC-80 games (.lua, .js, .fnl or .tic). If you are going to publish them, check that the author allows it (their license).
Lesson 15 · Sound in your game
- Sounds. Type SOUNDS: it is a library of 20 ready-made effects (laser, extra life, door…). SOUNDS PUT copies them into your cartridge, from 5 to 24.
- Listen to them. SOUNDS 5 plays the laser, SOUNDS 7 the extra life… Listen and write down the numbers you want to use in your game.
- Song happy. Type SONG to see the 3 songs and SONG HAPPY to put it in. It lands in Music (F5): open it and see how it is made.
- Put: laser and music. Z plays the laser with sfx(5), X turns the music on and off with track() and music(-1), and the arrows play notes.
-- Sound in your game: Z = laser, X = music on/off, arrows = notes. -- First type SOUNDS PUT and SONG HAPPY on the command line. local musica = false local nota = '' local NOTAS = { [0] = { 'C', 262 }, [1] = { 'E', 330 }, [2] = { 'G', 392 }, [3] = { 'HIGH C', 523 } } function _update() if btnp(4) then sfx(5) end -- 5 = LASER from the library if btnp(5) then musica = not musica if musica then track() else music(-1) end end for b = 0, 3 do if btnp(b) then tono(NOTAS[b][2], 0.2, 1); nota = NOTAS[b][1] end -- 1 = triangle wave end end function _draw() cls(1) print('Z: LASER X: MUSIC', 4, 4, 7) print('ARROWS: NOTES', 4, 14, 7) print('MUSIC: ' .. (musica and 'ON' or 'OFF'), 4, 30, musica and 11 or 8) print(nota, 50, 60, 10) end - Tone. tono(262, 0.2, 1) plays a note right away: frequency (262 = C), duration in seconds and wave (0 square, 1 triangle, 2 saw, 3 sine, 4 noise).
- Make it yours. Open Effects (F4), pick 05 and change it: another wave, other notes. Your game will use the new sound without touching the code.
Lesson 16 · Your character
- New platform. Start with NEW PLATFORM: it is a game with a red square that jumps. We are going to swap that square for a character you draw.
- Draw on #1. In Sprites (F2) tap #1 on the sheet (the second little square) and draw your character with the pencil. Whatever you leave black (color 0) will be transparent.
- Put: with your sprite. This code is the same template, but it draws your sprite #1 with spr(1, x, y) instead of the red square.
-- Your character: the PLATFORM template with your sprite #1 instead of the red square. -- Draw #1 in Sprites (F2): black (color 0) is not drawn. -- ── CHANGE HERE ────────────────────────── local VELOCIDAD = 2 -- how fast you walk local SALTO = -5 -- more negative = higher jump local GRAVEDAD = 0.3 -- bigger = falls faster local COLOR_CIELO = 12 -- ───────────────────────────────────────── local x, y, vy, enSuelo = 10, 100, 0, false local mira = 1 -- 1 = right, -1 = left local puntos = 0 local plataformas = { { x = 0, y = 120, w = 128 }, { x = 20, y = 92, w = 30 }, { x = 70, y = 70, w = 30 }, { x = 30, y = 46, w = 24 }, } local monedas = {} function _init() for _, p in ipairs(plataformas) do monedas[#monedas + 1] = { x = p.x + p.w / 2, y = p.y - 8 } end end function _update() if btn(0) then x = x - VELOCIDAD; mira = -1 end if btn(1) then x = x + VELOCIDAD; mira = 1 end if btnp(4) and enSuelo then vy = SALTO; tono(440, 0.08) end vy = math.min(vy + GRAVEDAD, 4) y = y + vy enSuelo = false for _, p in ipairs(plataformas) do if vy >= 0 and x + 7 >= p.x and x <= p.x + p.w and y + 8 >= p.y and y + 8 <= p.y + 6 then y, vy, enSuelo = p.y - 8, 0, true end end for i = #monedas, 1, -1 do local m = monedas[i] if math.abs(x + 4 - m.x) < 6 and math.abs(y + 4 - m.y) < 6 then table.remove(monedas, i); puntos = puntos + 1; tono(880, 0.1) end end if y > 140 then x, y, vy = 10, 100, 0 end -- fell off: back to the start end function _draw() cls(COLOR_CIELO) for _, p in ipairs(plataformas) do rectfill(p.x, p.y, p.w, 4, 4) end for _, m in ipairs(monedas) do circfill(m.x, m.y, 2, 10) end palt(0, true) -- black (color 0) becomes transparent spr(1, x, y, 1, 1, mira < 0) -- your sprite #1; mira < 0 flips it palt() -- colors go back to normal print('COINS: ' .. puntos, 2, 2, 7) if #monedas == 0 then print('YOU WIN!', 46, 30, 10) end end - Palt and flip. palt(0, true) makes black transparent. In spr(1, x, y, 1, 1, mira < 0) the sixth value flips the sprite: that way it faces where it walks.
- Challenge: the coin. Draw a coin on #2 and change circfill(m.x, m.y, 2, 10) to spr(2, m.x - 4, m.y - 4). Your whole game with your drawings!
Lesson 17 · A bigger world
- Beyond the screen. The screen is 128 pixels wide, but your world can be longer. camera(cx, 0) shifts everything you draw: that way the screen follows the character.
- Put: long world. A world 4 screens wide with 14 platforms and coins. Walk right and the camera follows you.
-- A world bigger than the screen: the camera follows the character. local MUNDO = 512 -- world width in pixels (4 screens) local x, y, vy, enSuelo = 10, 100, 0, false local cx = 0 -- where the camera is local plataformas = { { x = 0, y = 120, w = MUNDO } } local monedas = {} function _init() for i = 1, 14 do local p = { x = 40 + i * 32, y = 100 - (i % 3) * 18, w = 24 } plataformas[#plataformas + 1] = p monedas[#monedas + 1] = { x = p.x + 12, y = p.y - 8 } end end function _update() if btn(0) then x = math.max(0, x - 2) end if btn(1) then x = math.min(MUNDO - 8, x + 2) end if btnp(4) and enSuelo then vy = -5 end vy = math.min(vy + 0.3, 4) y = y + vy enSuelo = false for _, p in ipairs(plataformas) do if vy >= 0 and x + 7 >= p.x and x <= p.x + p.w and y + 8 >= p.y and y + 8 <= p.y + 6 then y, vy, enSuelo = p.y - 8, 0, true end end for i = #monedas, 1, -1 do local m = monedas[i] if math.abs(x + 4 - m.x) < 6 and math.abs(y + 4 - m.y) < 6 then table.remove(monedas, i); tono(880, 0.08) end end -- the camera follows the character without leaving the world cx = math.max(0, math.min(MUNDO - 128, x - 60)) end function _draw() cls(12) camera(cx, 0) -- from here on everything is drawn shifted for _, p in ipairs(plataformas) do rectfill(p.x, p.y, p.w, 4, 4) end for _, m in ipairs(monedas) do circfill(m.x, m.y, 2, 10) end rectfill(x, y, 8, 8, 8) camera() -- what comes below stays fixed on the screen print('LEFT: ' .. #monedas, 2, 2, 7) if #monedas == 0 then print('YOU GOT THEM ALL!', 24, 30, 10) end end - The camera follows. cx = x - 60 keeps the character near the center; math.max and math.min keep the camera from leaving the world.
- What stays fixed. After camera() with no numbers, what you draw stays fixed on the screen: that way the score does not scroll away with the world.
- With your map. If you drew a level in Map (F3), add it with map(0, 0, 0, 0, 64, 16) after camera(cx, 0): the map moves too.
Lesson 18 · Title screen
- Each screen with its clock. Like in LEARN 11, the game changes screens with estado. Now each screen has its own clock t: it counts frames (30 per second) since it started.
- Put: title with a story. Falling stars, a title that slides down, a blinking Z TO START, a closing curtain and a story typed letter by letter.
-- Title screen: stars, a title that slides down, a blinking Z, -- a curtain that closes and a short story letter by letter. local estado = 'titulo' local t = 0 -- frames since this screen started (30 per second) local tituloY = -20 -- the title comes in from the top local estrellas = {} local intro = { -- your story: one message per Z 'A LONG TIME AGO...', 'A GOAT LOST HIS BELL.', 'TODAY HE SETS OUT TO FIND IT.', } local linea, cortina = 1, 0 function _init() for i = 1, 30 do estrellas[i] = { x = math.random(0, 127), y = math.random(0, 127), v = math.random(1, 3) / 2 } end end local function cambiar(nuevo) estado, t = nuevo, 0 end local function centrado(texto, y, c) local w = print(texto, 0, -10) -- measures without drawing (off screen) print(texto, (128 - w) // 2, y, c) end function _update() t = t + 1 for _, e in ipairs(estrellas) do e.y = e.y + e.v if e.y > 128 then e.y, e.x = 0, math.random(0, 127) end end if estado == 'titulo' then if tituloY < 36 then tituloY = tituloY + 2 end -- slides down to its place if tituloY >= 36 and btnp(4) then tono(660, 0.1); cambiar('cortina') end elseif estado == 'cortina' then cortina = t * 2 -- grows 2 pixels per frame if cortina >= 64 then cambiar('intro') end elseif estado == 'intro' then local texto = intro[linea] if t // 2 < #texto then if btnp(4) then t = #texto * 2 end -- Z: show it all at once elseif btnp(4) then linea, t = linea + 1, 0 tono(440, 0.05) if linea > #intro then cambiar('juego') end end elseif estado == 'juego' then if btnp(5) then cambiar('titulo'); tituloY, linea = -20, 1 end end end function _draw() cls(0) for _, e in ipairs(estrellas) do pset(e.x, e.y, e.v > 1 and 7 or 5) end if estado == 'titulo' or estado == 'cortina' then centrado('MY GREAT GAME', tituloY + 1, 2) -- shadow centrado('MY GREAT GAME', tituloY, 10) if tituloY >= 36 and (t // 15) % 2 == 0 then centrado('Z PARA EMPEZAR', 80, 7) end if estado == 'cortina' then -- two black curtains closing rectfill(0, 0, 128, cortina, 0) rectfill(0, 128 - cortina, 128, cortina, 0) end elseif estado == 'intro' then local texto = intro[linea] centrado(string.sub(texto, 1, t // 2), 60, 7) -- one letter every 2 frames if t // 2 >= #texto and (t // 10) % 2 == 0 then print('Z', 118, 118, 6) end else centrado('YOUR GAME STARTS HERE', 56, 11) centrado('X: BACK TO TITLE', 72, 6) end end -- CHALLENGES: up for it? -- 1. change MY GREAT GAME and the story to your own -- 2. add music to the title: track() at the start and music(-1) when playing -- 3. draw your character in the intro with spr(1, 60, 80) - Blinking. (t // 15) % 2 == 0 is true for half a second, then false for half a second: that is how text blinks. Change 15 to 5 and it blinks faster.
- Centering text. print(texto, 0, -10) measures the text without drawing it (off screen). With (128 - width) // 2 it ends up centered.
- Your story. Change the messages in the intro table to the story of your game. string.sub cuts by bytes, so in Spanish write them without accents.
Lesson 19 · Talking to characters
- Who says what. Each character is a table with nombre (name), position, color and dice: the list of what they say, one message per Z.
- Put: dialogue. Walk with the arrows. When you are close, a Z shows above the character: press it to talk.
-- Talk to the characters: walk up and press Z. -- Z also goes to the next message. local px, py = 20, 90 -- you local personajes = { { nombre = 'GRANDMA', x = 64, y = 90, color = 14, dice = { 'HI, LITTLE GOAT.', 'THEY SAY YOUR BELL IS UP THERE, ON THE HILL.', 'TAKE THIS CHEESE FOR THE ROAD.', } }, { nombre = 'DOG', x = 104, y = 60, color = 4, dice = { 'WOOF.', 'WOOF WOOF. (LOOKS LIKE HE IS HUNGRY)', } }, } local hablando = nil -- who is talking now (nil = nobody) local linea, letras, reloj = 1, 0, 0 local function cerca(p) return math.abs(px - p.x) < 14 and math.abs(py - p.y) < 14 end -- splits a long message into lines that fit in the box local function renglones(texto, max) local lista, actual = {}, '' for palabra in string.gmatch(texto, '%S+') do if actual ~= '' and #actual + 1 + #palabra > max then table.insert(lista, actual); actual = palabra elseif actual == '' then actual = palabra else actual = actual .. ' ' .. palabra end end table.insert(lista, actual) return lista end function _update() reloj = reloj + 1 if hablando then local texto = hablando.dice[linea] if letras < #texto then letras = letras + 1 if letras % 3 == 0 then tono(300 + math.random(0, 200), 0.02) end -- their voice: a beep if btnp(4) then letras = #texto end -- Z: show it all at once elseif btnp(4) then linea, letras = linea + 1, 0 if linea > #hablando.dice then hablando = nil end -- the conversation is over end return -- while they talk, you do not move end if btn(0) then px = px - 1 end if btn(1) then px = px + 1 end if btn(2) then py = py - 1 end if btn(3) then py = py + 1 end for _, p in ipairs(personajes) do if cerca(p) and btnp(4) then hablando, linea, letras = p, 1, 0 end end end function _draw() cls(12) rectfill(0, 100, 128, 28, 11) -- grass for _, p in ipairs(personajes) do rectfill(p.x, p.y, 8, 8, p.color) -- with a sprite: spr(2, p.x, p.y) if cerca(p) and not hablando then print('Z', p.x + 2, p.y - 8, 7) end end rectfill(px, py, 8, 8, 7) -- you; with a sprite: spr(1, px, py) if hablando then rectfill(2, 82, 124, 44, 7) -- the box: white border rectfill(3, 83, 122, 42, 0) -- and black background local w = print(hablando.nombre, 0, -10) rectfill(6, 76, w + 4, 9, hablando.color) -- the name tag print(hablando.nombre, 8, 78, 0) local quedan = letras for i, r in ipairs(renglones(hablando.dice[linea], 28)) do print(string.sub(r, 1, math.max(0, quedan)), 7, 90 + (i - 1) * 8, 7) quedan = quedan - #r - 1 end if letras >= #hablando.dice[linea] and (reloj // 10) % 2 == 0 then print('Z', 116, 118, 10) end end end -- CHALLENGES: up for it? -- 1. add a third character with their messages -- 2. after grandma, add queso = queso + 1 (cheese) and show it -- 3. swap the squares for your sprites (spr) and give them faces - Letter by letter. letras counts how many letters are showing and goes up 1 each frame; string.sub(texto, 1, letras) cuts the text. A beep every 3 letters is their voice.
- Lines. renglones() splits a long message by words so it fits in the box (28 letters). Like in lesson 18, Spanish messages go without accents.
- Challenge: get a gift. Challenge: when you finish talking to grandma, add queso = queso + 1 (cheese) and show it at the top. Hint: it goes where hablando = nil.
Lesson 20 · Inventory, keys and doors
- Backpack = table. The backpack is an empty table: mochila = {}. When you pick something up, table.insert(mochila, cosa) puts it in and #mochila tells how many things you carry.
- Put: keys and doors. Grab the red key to open the red door, and so on. X opens the backpack to see what you carry.
-- Inventory: collect keys and open the door of their color. -- X opens and closes the backpack. local px, py = 10, 60 local cosas = { -- what is on the floor: type, color and position { tipo = 'llave', color = 8, x = 40, y = 20 }, { tipo = 'llave', color = 12, x = 100, y = 100 }, { tipo = 'gema', color = 11, x = 110, y = 20 }, } local puertas = { -- each door opens with the key of its color { color = 8, x = 70, y = 0, w = 4, h = 64 }, { color = 12, x = 70, y = 64, w = 4, h = 64 }, } local mochila = {} -- what you carry local verMochila = false -- do I carry something of this type and color? gives its place in the backpack local function tengo(tipo, color) for i, c in ipairs(mochila) do if c.tipo == tipo and c.color == color then return i end end return nil end local function puertaEn(x, y) for i, p in ipairs(puertas) do if x + 6 > p.x and x < p.x + p.w and y + 6 > p.y and y < p.y + p.h then return i, p end end return nil end function _update() if btnp(5) then verMochila = not verMochila end if verMochila then return end -- with the backpack open the game waits local nx, ny = px, py if btn(0) then nx = nx - 1 end if btn(1) then nx = nx + 1 end if btn(2) then ny = ny - 1 end if btn(3) then ny = ny + 1 end local i, p = puertaEn(nx, ny) if p then local k = tengo('llave', p.color) if k then -- you have its key: it opens and the key is used up table.remove(mochila, k) table.remove(puertas, i) tono(880, 0.15) end else px = math.max(0, math.min(122, nx)) py = math.max(0, math.min(122, ny)) end for j = #cosas, 1, -1 do -- back to front so we can remove items local c = cosas[j] if math.abs(px - c.x) < 6 and math.abs(py - c.y) < 6 then table.insert(mochila, c) table.remove(cosas, j) tono(660, 0.08) end end end function _draw() cls(1) for _, p in ipairs(puertas) do rectfill(p.x, p.y, p.w, p.h, p.color) end for _, c in ipairs(cosas) do if c.tipo == 'llave' then rectfill(c.x, c.y, 2, 6, c.color) rectfill(c.x, c.y + 2, 6, 2, c.color) else circfill(c.x + 3, c.y + 3, 3, c.color) end end rectfill(px, py, 6, 6, 7) -- you print('X: BACKPACK (' .. #mochila .. ')', 2, 2, 6) if verMochila then rectfill(14, 30, 100, 60, 0) print('BACKPACK', 50, 34, 10) if #mochila == 0 then print('EMPTY', 54, 56, 5) end for k, c in ipairs(mochila) do rectfill(20 + (k - 1) * 14, 50, 10, 10, c.color) end end end -- CHALLENGES: up for it? -- 1. add a third key and its door -- 2. make the gem open a chest that gives coins -- 3. draw the key and the gem in Sprites and use spr - Searching the backpack. tengo(tipo, color) goes through the backpack and returns where the key is; if you do not have it, it returns nil (nothing). With if k then you know whether you have it.
- Using up the key. table.remove(mochila, k) removes the key when opening and table.remove(puertas, i) removes the door. For keys that are not used up, delete the first line.
- Challenge: the chest. Challenge: make a chest that only opens with the gem and gives 10 coins. Hint: it is one more item in the puertas table.
Lesson 21 · Enemies that chase you
- Where you are. To walk toward you, the enemy measures dx and dy. Divided by the total distance they give a direction of size 1: that way everyone walks at their speed, even diagonally.
- Put: they chase you. The dark red one always follows you. The guards only chase you if you enter their circle; they turn red when they see you.
-- Enemies that chase you: they walk toward you. -- Some always follow you; the guards only when they see you up close. local px, py = 60, 60 local enemigos = { { x = 10, y = 10, vel = 0.4, tipo = 'sigue' }, { x = 110, y = 110, vel = 0.7, tipo = 'vigila' }, { x = 110, y = 10, vel = 0.5, tipo = 'vigila' }, } local VISTA = 40 -- how far the guards can see local vidas, golpe = 3, 0 function _update() if vidas <= 0 then if btnp(4) then vidas, px, py = 3, 60, 60 end return end if btn(0) then px = px - 1 end if btn(1) then px = px + 1 end if btn(2) then py = py - 1 end if btn(3) then py = py + 1 end for _, e in ipairs(enemigos) do local dx, dy = px - e.x, py - e.y local dist = math.sqrt(dx * dx + dy * dy) -- distance (Pythagoras) e.persigue = e.tipo == 'sigue' or dist < VISTA if e.persigue and dist > 1 then e.x = e.x + dx / dist * e.vel -- dx / dist = the direction toward you e.y = e.y + dy / dist * e.vel end if golpe == 0 and dist < 6 then vidas, golpe = vidas - 1, 60 tono(150, 0.2) end end if golpe > 0 then golpe = golpe - 1 end end function _draw() cls(0) for _, e in ipairs(enemigos) do if e.tipo == 'vigila' then circ(e.x + 3, e.y + 3, VISTA, 1) end -- how far it sees rectfill(e.x, e.y, 6, 6, e.persigue and 8 or 2) end if golpe % 6 < 3 then rectfill(px, py, 6, 6, 11) end -- blinks if you got hit print('LIVES: ' .. vidas, 2, 2, 7) if vidas <= 0 then print('CAUGHT YOU · Z', 32, 60, 8) end end -- CHALLENGES: up for it? -- 1. make the guards go back to their spot when they lose you -- 2. add an enemy that runs away from you (subtract instead of add) -- 3. raise everyone's speed every 10 seconds - Pythagoras. math.sqrt(dx * dx + dy * dy) is the straight-line distance (the Pythagorean theorem). With it you decide whether it sees you (dist < VISTA) or touched you (dist < 6).
- Change their personality. Play with vel and VISTA: a slow enemy that sees far is scary in a different way than a fast, short-sighted one. That is how each enemy is designed.
- Challenge: the one that flees. Challenge: an enemy that runs away from you. Hint: instead of adding dx / dist, subtract it.
Lesson 22 · A shop with coins
- Products in a table. Each product is a table with nombre (name), precio (price) and color. To add one to the shop you just add a line to productos.
- Put: the shop. Collect coins, walk up to the stall and press Z. Up and down choose, Z buys, X leaves. The boots make you faster.
-- Shop: collect coins and buy from the seller. -- In the shop: up and down choose, Z buys, X leaves. local monedas = 0 local px, py = 20, 100 local tienda = false local elegido = 1 local productos = { { nombre = 'POTION', precio = 3, color = 8 }, { nombre = 'SWORD', precio = 8, color = 6 }, { nombre = 'BOOTS', precio = 5, color = 4 }, } local comprado = {} -- what you already bought: comprado['BOOTS'] = true local piso = {} -- coins on the floor function _init() for i = 1, 12 do piso[i] = { x = math.random(4, 120), y = math.random(36, 120) } end end local function cercaDelPuesto() return math.abs(px - 100) < 12 and math.abs(py - 20) < 14 end function _update() if tienda then if btnp(2) then elegido = (elegido - 2) % #productos + 1 end if btnp(3) then elegido = elegido % #productos + 1 end local p = productos[elegido] if btnp(4) then if comprado[p.nombre] then tono(200, 0.1) elseif monedas >= p.precio then monedas = monedas - p.precio comprado[p.nombre] = true tono(990, 0.15) else tono(120, 0.2) -- not enough money end end if btnp(5) then tienda = false end return end local v = comprado['BOOTS'] and 2 or 1 -- with boots you walk faster if btn(0) then px = px - v end if btn(1) then px = px + v end if btn(2) then py = py - v end if btn(3) then py = py + v end for i = #piso, 1, -1 do local m = piso[i] if math.abs(px + 3 - m.x) < 5 and math.abs(py + 3 - m.y) < 5 then table.remove(piso, i) monedas = monedas + 1 tono(880, 0.05) end end if cercaDelPuesto() and btnp(4) then tienda, elegido = true, 1 end end function _draw() cls(3) rectfill(96, 12, 16, 16, 9) -- the stall print('SHOP', 92, 4, 7) for _, m in ipairs(piso) do circfill(m.x, m.y, 2, 10) end rectfill(px, py, 6, 6, 7) print('$ ' .. monedas, 2, 2, 10) if tienda then rectfill(10, 30, 108, 70, 0) print('WHAT WILL IT BE?', 16, 34, 7) for i, p in ipairs(productos) do local y = 46 + (i - 1) * 12 if i == elegido then print('>', 14, y, 10) end rectfill(22, y, 6, 6, p.color) print(p.nombre, 32, y, comprado[p.nombre] and 5 or 7) print(comprado[p.nombre] and 'OWNED' or '$' .. p.precio, 92, y, 10) end print('Z BUY · X LEAVE', 26, 88, 6) elseif cercaDelPuesto() then print('Z', 102, 30, 7) end end -- CHALLENGES: up for it? -- 1. let the sword break rocks -- 2. let the potion be bought several times (count how many you have) -- 3. spawn new coins every 5 seconds - Choosing in a menu. elegido % #productos + 1 moves forward and wraps back to the first. (elegido - 2) % #productos + 1 does the same going up.
- Can you afford it?. if monedas >= p.precio decides whether you can buy it. comprado[p.nombre] = true remembers what you own: a table also works as a yes-or-no list.
- Challenge: potions. Challenge: let the potion be bought several times. Hint: instead of true, store a number and add 1.
Lesson 23 · Save your game
- More than a high score. In LEARN 12 you saved a high score. A saved game is several values: level, lives and coins, each in its own dget and dset slot.
- Put: saved game. Change the numbers with the arrows, Z saves, close the page and come back: everything is still there. X deletes the saved game.
-- Save your game: level, lives and coins stay even if you close the page. cartdata('mi_aventura') -- the name of your game's memory local nivel, vidas, monedas local aviso = 0 local function cargar() if dget(0) == 0 then -- slot 0 at zero: you never saved nivel, vidas, monedas = 1, 3, 0 else nivel, vidas, monedas = dget(1), dget(2), dget(3) end end local function guardar() dset(0, 1) -- mark: there is a saved game dset(1, nivel) dset(2, vidas) dset(3, monedas) aviso = 60 tono(880, 0.1) end function _init() cargar() end function _update() if btnp(2) then monedas = monedas + 1 end if btnp(1) then nivel = nivel + 1 end if btnp(3) and vidas > 0 then vidas = vidas - 1 end if btnp(4) then guardar() end if btnp(5) then -- delete the saved game dset(0, 0) cargar() tono(200, 0.2) end if aviso > 0 then aviso = aviso - 1 end end function _draw() cls(1) print('LEVEL ' .. nivel, 10, 20, 7) print('LIVES ' .. vidas, 10, 32, 8) print('COINS ' .. monedas, 10, 44, 10) print('UP: +1 COIN', 10, 66, 6) print('RIGHT: LEVEL UP', 10, 74, 6) print('DOWN: LOSE A LIFE', 10, 82, 6) print('Z: SAVE X: DELETE', 10, 94, 11) if aviso > 0 then print('GAME SAVED', 30, 110, 11) end end -- CHALLENGES: up for it? -- 1. also save the x and y of your character -- 2. save only when you reach a flag, like old games -- 3. have 3 save slots (slots 0-3, 10-13 and 20-23) - The mark. Slot 0 is a mark: 0 = never saved, 1 = there is a saved game. That is how the game knows whether to start fresh or load.
- Load and save. cargar() (load) and guardar() (save) are functions: you write them once and call them wherever needed (at the start, at a flag, when leaving).
- Challenge: three slots. Challenge: 3 save slots. Hint: slot 2 uses 10 to 13 and slot 3 uses 20 to 23.
Lesson 24 · A boss with phases
- Phases. A boss feels epic when it changes: fase() looks at its health and returns 1, 2 or 3. Everything else (speed, attacks, color) depends on that number.
- Put: the boss. Dodge the beams and shoot it with Z. At 20 and 10 health it changes color, moves faster and attacks with more beams.
-- A boss with phases: it changes its attack as it loses health. -- Arrows to move, Z shoots. local px, balas, rayos, jefe, fin, vidas local function reiniciar() px, balas, rayos, fin, vidas = 60, {}, {}, nil, 3 jefe = { x = 48, y = 12, vida = 30, vx = 0.6, t = 0 } end local function fase() if jefe.vida > 20 then return 1 -- phase 1: slow, one beam elseif jefe.vida > 10 then return 2 -- phase 2: three beams else return 3 end -- phase 3: furious end function _init() reiniciar() end function _update() if fin then if btnp(4) then reiniciar() end return end if btn(0) then px = math.max(0, px - 2) end if btn(1) then px = math.min(120, px + 2) end if btnp(4) then table.insert(balas, { x = px + 3, y = 110 }) tono(880, 0.03) end local f = fase() jefe.t = jefe.t + 1 jefe.x = jefe.x + jefe.vx * f -- each phase moves faster if jefe.x < 0 or jefe.x > 96 then jefe.vx = -jefe.vx end local cada = ({ 40, 30, 15 })[f] -- how many frames between attacks if jefe.t % cada == 0 then if f == 1 then table.insert(rayos, { x = jefe.x + 16, y = 30, vx = 0 }) else for _, vx in ipairs({ -0.6, 0, 0.6 }) do table.insert(rayos, { x = jefe.x + 16, y = 30, vx = vx }) end end end for i = #balas, 1, -1 do local b = balas[i] b.y = b.y - 4 if b.y > jefe.y and b.y < jefe.y + 16 and b.x > jefe.x and b.x < jefe.x + 32 then jefe.vida = jefe.vida - 1 table.remove(balas, i) tono(300, 0.03) if jefe.vida <= 0 then fin = 'ganaste' end elseif b.y < 0 then table.remove(balas, i) end end for i = #rayos, 1, -1 do local r = rayos[i] r.y = r.y + 1 + f * 0.5 r.x = r.x + r.vx if math.abs(r.x - (px + 4)) < 5 and r.y > 108 and r.y < 118 then vidas = vidas - 1 table.remove(rayos, i) tono(120, 0.2) if vidas <= 0 then fin = 'perdiste' end elseif r.y > 128 then table.remove(rayos, i) end end end function _draw() cls(0) local f = fase() local colores = { 11, 9, 8 } -- green, orange, red: that is how you see the phase rectfill(jefe.x, jefe.y, 32, 16, colores[f]) rectfill(jefe.x + 6, jefe.y + 4, 4, 4, 0) -- eyes rectfill(jefe.x + 22, jefe.y + 4, 4, 4, 0) rectfill(14, 4, 100, 3, 2) -- the health bar if jefe.vida > 0 then rectfill(14, 4, jefe.vida * 100 // 30, 3, colores[f]) end for _, b in ipairs(balas) do rectfill(b.x, b.y, 2, 4, 10) end for _, r in ipairs(rayos) do circfill(r.x, r.y, 2, colores[f]) end rectfill(px, 112, 8, 6, 12) print('LIVES ' .. vidas, 2, 120, 7) print('PHASE ' .. f, 96, 120, colores[f]) if fin == 'ganaste' then print('YOU WIN · Z', 40, 60, 11) end if fin == 'perdiste' then print('YOU LOSE · Z', 38, 60, 8) end end -- CHALLENGES: up for it? -- 1. make the boss shake in phase 3 (camera with random numbers) -- 2. add a phase 4 that shoots in a circle -- 3. give each phase different music - Tables as choices. ({ 40, 30, 15 })[f] picks the number for each phase in a single line. Likewise colores[f] picks the color.
- Health bar. jefe.vida * 100 // 30 turns the health (0 to 30) into the bar width (0 to 100). It is a simple proportion.
- Challenge: phase 4. Challenge: a phase 4 when it has 5 health left, shooting in 5 directions.
Lesson 25 · Pause menu and options
- Freezing the game. With pausa = true, _update skips the game part (that is the return): nothing moves, but _draw keeps drawing the menu on top.
- Put: pause. Press Z when the yellow square passes the gray zone. X pauses: you can turn off the music, change the difficulty or restart.
-- Pause menu: X pauses the game and opens the options. -- Up and down choose, Z changes the option. Meanwhile, the game freezes. local pausa = false local elegido = 1 local opciones = { { nombre = 'RESUME' }, { nombre = 'MUSIC', valor = true }, { nombre = 'DIFFICULTY', valor = 2, max = 3 }, { nombre = 'RESTART' }, } local NIVELES = { 'EASY', 'NORMAL', 'HARD' } local x, vx, puntos = 10, 1, 0 -- the text of each option with its value local function texto(o) if o.valor == nil then return o.nombre end if o.valor == true then return o.nombre .. ': ON' end if o.valor == false then return o.nombre .. ': OFF' end return o.nombre .. ': ' .. NIVELES[o.valor] end function _init() track() -- the cart's song end function _update() if not pausa then if btnp(5) then pausa, elegido = true, 1; return end x = x + vx * opciones[3].valor -- difficulty changes the speed if x < 0 or x > 120 then vx = -vx end if btnp(4) then -- Z right when the square passes the gray zone if math.abs(x - 60) < 8 then puntos = puntos + 1; tono(880, 0.05) else puntos = 0; tono(150, 0.1) end end return end if btnp(2) then elegido = (elegido - 2) % #opciones + 1 end if btnp(3) then elegido = elegido % #opciones + 1 end local o = opciones[elegido] if btnp(4) then tono(660, 0.05) if o.nombre == 'RESUME' then pausa = false elseif o.nombre == 'RESTART' then x, puntos, pausa = 10, 0, false elseif o.valor == true or o.valor == false then o.valor = not o.valor if o.valor then track() else music(-1) end else o.valor = o.valor % o.max + 1 -- 1, 2, 3 and back to 1 end end if btnp(5) then pausa = false end end function _draw() cls(1) rectfill(56, 60, 16, 8, 5) -- the zone rectfill(x, 62, 8, 4, 10) print('POINTS ' .. puntos, 2, 2, 7) print('X: PAUSE', 92, 2, 6) if pausa then rectfill(16, 24, 96, 72, 0) print('PAUSE', 54, 30, 10) for i, o in ipairs(opciones) do local marca = i == elegido and '> ' or ' ' print(marca .. texto(o), 22, 44 + (i - 1) * 10, i == elegido and 7 or 6) end end end -- CHALLENGES: up for it? -- 1. add a VOLUME option with 3 levels -- 2. save the options with dset so they are remembered -- 3. put a menu like this on the title screen (LEARN 18) - Options in a table. Each option has a name and, if it changes, a value: true or false (ON or OFF) or a number (EASY, NORMAL, HARD). texto(o) builds what you read.
- Changing a value. not o.valor flips ON and OFF. o.valor % o.max + 1 gives 1, 2, 3 and back to 1: it works for any option with several levels.
- Challenge: remember it. Challenge: save the music and difficulty with dset (LEARN 23) so the game remembers them.
Lesson 26 · Animation by state
- One state at a time. The character is always in one state: idle, walking or in the air. Each frame decides which one applies and each state is drawn differently.
- Put: states. Walk with the arrows and jump with Z: the legs breathe, cross or tuck in. The state shows at the top.
-- Animation by state: the character looks different when it is -- idle, walking or in the air. Arrows to move, Z jumps. local x, y, vy = 60, 100, 0 local mira = 1 -- 1 = right, -1 = left local estado = 'idle' local t = 0 -- the animation clock local function dibujar(x, y) local cuadro = (t // 6) % 2 -- 0, 1, 0, 1... changes every 6 frames rectfill(x, y, 8, 8, 9) -- body rectfill(x + (mira > 0 and 5 or 1), y + 2, 2, 2, 0) -- the eye looks where you go if estado == 'idle' then rectfill(x + 1, y + 8, 2, 3 + cuadro, 4) -- breathing legs rectfill(x + 5, y + 8, 2, 3 + cuadro, 4) elseif estado == 'walk' then rectfill(x + 1 + cuadro * 2, y + 8, 2, 4, 4) -- crossing legs rectfill(x + 5 - cuadro * 2, y + 8, 2, 4, 4) else rectfill(x, y + 8, 3, 2, 4) -- in the air: tucked legs rectfill(x + 5, y + 8, 3, 2, 4) end end function _update() t = t + 1 local mueve = false if btn(0) then x = x - 1; mira = -1; mueve = true end if btn(1) then x = x + 1; mira = 1; mueve = true end if btnp(4) and y >= 100 then vy = -4 end vy = vy + 0.25 y = math.min(100, y + vy) if y < 100 then estado = 'air' elseif mueve then estado = 'walk' else estado = 'idle' end end function _draw() cls(12) rectfill(0, 112, 128, 16, 3) dibujar(x, y) print('STATE: ' .. estado, 4, 4, 7) end -- CHALLENGES: up for it? -- 1. add a crouching state with the down arrow -- 2. swap the squares for your sprites: spr(16 + cuadro * 2, x, y, 2, 2) -- 3. make the legs go faster when you run - The animation clock. t goes up 1 every frame. (t // 6) % 2 gives 0 and 1 taking turns every 6 frames: that is the animation frame. With % 4 you would have 4 frames.
- With your sprites. Draw each pose in Sprites (for example 2X at #16 and #18) and replace the rectfill calls with spr(16 + cuadro * 2, x, y, 2, 2, mira < 0).
- Challenge: crouch. Challenge: a fourth state, crouching, with the down arrow. Hint: another branch in the state if and another way to draw it.
Lesson 27 · Several screens and doors
- Rooms in a table. Each room is a table with its name, its color and its doors. actual says which room you are in.
- Put: three rooms. House, forest and cave. Walk to the black squares: they are doors.
-- Several screens: each room is a table. When you touch a door -- you go to the room the door says. Arrows to walk. local cuartos = { { nombre = 'HOUSE', color = 4, puertas = { { x = 120, y = 56, va = 2, llega = { 8, 60 } } } }, { nombre = 'FOREST', color = 3, puertas = { { x = 0, y = 56, va = 1, llega = { 112, 60 } }, { x = 56, y = 0, va = 3, llega = { 60, 112 } } } }, { nombre = 'CAVE', color = 1, puertas = { { x = 56, y = 120, va = 2, llega = { 60, 10 } } } }, } local actual = 1 local px, py = 60, 60 local espera = 0 -- a little while without doors after arriving function _update() if btn(0) then px = px - 1 end if btn(1) then px = px + 1 end if btn(2) then py = py - 1 end if btn(3) then py = py + 1 end px = math.max(0, math.min(122, px)) py = math.max(0, math.min(122, py)) if espera > 0 then espera = espera - 1; return end for _, p in ipairs(cuartos[actual].puertas) do if math.abs(px - p.x) < 8 and math.abs(py - p.y) < 8 then actual = p.va -- the door says which room you go to px, py = p.llega[1], p.llega[2] -- and where you appear espera = 15 tono(520, 0.08) return end end end function _draw() local c = cuartos[actual] cls(c.color) for _, p in ipairs(c.puertas) do rectfill(p.x, p.y, 8, 8, 0) end rectfill(px, py, 6, 6, 7) print(c.nombre, 4, 4, 7) end -- CHALLENGES: up for it? -- 1. add a room 4 with its door -- 2. make the cave need a key (LEARN 20) -- 3. draw each room in the Map and use map(X * 16, Y * 16, 0, 0, 16, 16) - The door says where. Each door stores va (which room) and llega (where you appear). espera gives half a second without doors so you do not bounce back.
- With your map. Draw each room on a Map screen (they are numbered X,Y) and draw it with map(X * 16, Y * 16, 0, 0, 16, 16). NEW WORLD uses the same idea.
- Challenge: the locked cave. Challenge: make the cave door need a key (see LEARN 20).
Lesson 28 · Rain and snow
- Recycled particles. 80 drops that are never deleted: when one leaves at the bottom, it comes back at the top somewhere else. Endless rain with few particles.
- Put: weather. Rain, snow or clear: Z changes the weather.
-- Weather: rain and snow with particles. Z changes the weather. local climas = { 'RAIN', 'SNOW', 'CLEAR' } local clima = 1 local gotas = {} local function nueva() return { x = math.random(-20, 127), y = math.random(-128, 0), v = math.random(10, 20) / 10 } end function _init() for i = 1, 80 do gotas[i] = nueva() end end function _update() if btnp(4) then clima = clima % #climas + 1 end for _, g in ipairs(gotas) do if clima == 1 then -- rain: fast and slanted g.y = g.y + g.v * 3 g.x = g.x + 1 elseif clima == 2 then -- snow: slow and swaying g.y = g.y + g.v * 0.5 g.x = g.x + math.sin(g.y / 10) * 0.5 end if g.y > 128 then -- it left: start again at the top local n = nueva() g.x, g.y, g.v = n.x, -2, n.v end end end function _draw() cls(clima == 1 and 1 or (clima == 2 and 13 or 12)) rectfill(0, 110, 128, 18, clima == 2 and 7 or 3) -- the floor if clima == 1 then for _, g in ipairs(gotas) do line(g.x, g.y, g.x + 1, g.y + 3, 12) end elseif clima == 2 then for _, g in ipairs(gotas) do pset(g.x, g.y, 7) end end print('Z: ' .. climas[clima], 4, 4, 7) end -- CHALLENGES: up for it? -- 1. lightning: now and then cls(7) for one frame and a low tone -- 2. make the snow pile up on the floor -- 3. put the weather over the lesson 9 game - Math.sin to sway. math.sin gives a number that goes up and down between -1 and 1. Added to x, the snow sways side to side as it falls.
- On top of your game. Draw the weather at the end of _draw, after the level and the character, so it falls in front of everything.
- Challenge: lightning. Challenge: once in a while, a frame with cls(7) and a low tone. Hint: math.random(1, 200) == 1.
Lesson 29 · Moving platforms
- Each one knows how to move. Each platform stores its speed (dx, dy) and its range (min, max). When it reaches a limit, the speed flips sign.
- Put: platforms. One goes side to side and another goes up and down. Jump on with Z.
-- Moving platforms: one goes side to side and another goes up and down. -- If you stand on them, they carry you. Arrows to move and Z to jump. local px, py, vy, encima = 10, 104, 0, nil local plataformas = { { x = 30, y = 90, w = 24, dx = 0.5, dy = 0, min = 20, max = 70 }, { x = 84, y = 60, w = 20, dx = 0, dy = 0.5, min = 40, max = 100 }, } function _update() for _, p in ipairs(plataformas) do -- the platforms move first p.x, p.y = p.x + p.dx, p.y + p.dy local pos = p.dx ~= 0 and p.x or p.y if pos < p.min or pos > p.max then p.dx, p.dy = -p.dx, -p.dy end end if encima then px, py = px + encima.dx, py + encima.dy end -- the platform carries you if btn(0) then px = px - 1 end if btn(1) then px = px + 1 end if btnp(4) and (encima or py >= 104) then vy = -4 end vy = math.min(vy + 0.25, 4) py = py + vy encima = nil for _, p in ipairs(plataformas) do if vy >= 0 and px + 6 > p.x and px < p.x + p.w and py + 8 >= p.y and py + 8 <= p.y + 6 then py, vy, encima = p.y - 8, 0, p end end if py >= 104 then py, vy = 104, 0 end -- the floor end function _draw() cls(12) rectfill(0, 112, 128, 16, 3) for _, p in ipairs(plataformas) do rectfill(p.x, p.y, p.w, 4, 4) end rectfill(px, py, 6, 8, 8) if encima then print('ON TOP', 4, 4, 7) end end -- CHALLENGES: up for it? -- 1. a platform that falls 1 second after you step on it -- 2. one that moves diagonally (dx and dy at the same time) -- 3. put a coin above the one that rises - It carries you. encima stores which platform you are standing on. Each frame adds how much it moved to you: that is why you ride along.
- Order matters. First the platforms move, then you, and last the collisions are checked. In another order you would float or sink.
- Challenge: the falling one. Challenge: a platform that falls 1 second after you step on it. Hint: a counter that starts when encima is that platform.
Lesson 30 · Two players
- The same code for both. Each player is a table with position, color, points and b: which button it starts counting from (0 for player 1 and 8 for player 2).
- Put: coin race. Player 1 with the arrows, player 2 with J L I K. The first to 10 coins wins.
-- Two players: 1 with the arrows and Z, 2 with J L I K and U -- (or with two controllers). First to 10 coins wins. local jugadores = { { x = 20, y = 60, color = 8, b = 0, puntos = 0 }, -- buttons 0 to 7 { x = 100, y = 60, color = 12, b = 8, puntos = 0 }, -- buttons 8 to 15 } local moneda = { x = 60, y = 60 } local ganador = nil local function nuevaMoneda() moneda.x, moneda.y = math.random(8, 116), math.random(16, 116) end function _update() if ganador then if btnp(4) or btnp(12) then -- Z from either player for _, j in ipairs(jugadores) do j.puntos = 0 end ganador = nil end return end for i, j in ipairs(jugadores) do if btn(j.b + 0) then j.x = j.x - 1.5 end -- the same code for both: if btn(j.b + 1) then j.x = j.x + 1.5 end -- only the starting button changes if btn(j.b + 2) then j.y = j.y - 1.5 end if btn(j.b + 3) then j.y = j.y + 1.5 end if math.abs(j.x - moneda.x) < 7 and math.abs(j.y - moneda.y) < 7 then j.puntos = j.puntos + 1 tono(i == 1 and 660 or 880, 0.08) nuevaMoneda() if j.puntos >= 10 then ganador = i end end end end function _draw() cls(0) circfill(moneda.x + 3, moneda.y + 3, 3, 10) for i, j in ipairs(jugadores) do rectfill(j.x, j.y, 6, 6, j.color) print('J' .. i .. ': ' .. j.puntos, i == 1 and 4 or 92, 4, j.color) end if ganador then print('WINNER: PLAYER ' .. ganador, 26, 60, 7) end end -- CHALLENGES: up for it? -- 1. make them bump and push each other -- 2. let player 2 shoot with U (btnp(12)) -- 3. add a 30-second time limit - With two controllers. The first controller you connect is player 1 and the second is player 2. Test them in LEARN 31.
- On one keyboard. Without controllers it works too: player 2 uses J L I K to move and U and O as Z and X.
- Challenge: pushing. Challenge: make them push each other when they bump. Hint: if they are too close, move each one a little apart.
Lesson 31 · Bluetooth controller
- Pair your controller. Chivo-8 works with Bluetooth or USB controllers: Xbox, PlayStation, 8BitDo and most generic ones. Pair it in your phone or PC Bluetooth settings, open Chivo-8 and press a button on the controller.
- The controller command. Type CONTROLLER: it says which controllers it sees and which player each one is. The browser does not show them until you press a button.
- Put: controller test. It draws two controllers and lights up each button you press, with the number you use in btn(). It also works with the keyboard and the screen.
-- Test your controller: every button you press lights up. -- Player 1 = btn(0) to btn(7) · player 2 = btn(8) to btn(15). local nombres = { 'LEFT', 'RIGHT', 'UP', 'DOWN', 'Z', 'X', 'C', 'V' } local function control(j, y) local b = j * 8 -- player 2 starts at button 8 rectfill(8, y, 112, 44, 5) -- the controller body print('PLAYER ' .. (j + 1), 40, y + 2, 7) rectfill(16, y + 22, 8, 8, btn(b + 0) and 11 or 0) -- d-pad: left rectfill(32, y + 22, 8, 8, btn(b + 1) and 11 or 0) -- right rectfill(24, y + 14, 8, 8, btn(b + 2) and 11 or 0) -- up rectfill(24, y + 30, 8, 8, btn(b + 3) and 11 or 0) -- down circfill(96, y + 34, 4, btn(b + 4) and 8 or 0) -- Z: the bottom button (A or cross) circfill(106, y + 26, 4, btn(b + 5) and 12 or 0) -- X: the right one (B or circle) circfill(86, y + 26, 4, btn(b + 6) and 10 or 0) -- C: the left one (X or square) circfill(96, y + 18, 4, btn(b + 7) and 11 or 0) -- V: the top one (Y or triangle) local t = '' for i = 0, 7 do -- what is pressed and the number you read it with if btn(b + i) then t = t .. nombres[i + 1] .. '=' .. (b + i) .. ' ' end end print(t, 10, y + 46, 6) end function _draw() cls(1) control(0, 4) control(1, 64) end - Your game stays the same. btn(0) to btn(3) are the arrows and btn(4) to btn(7) are Z, X, C and V, whether they come from the keyboard, the screen or the controller. On the controller: bottom = Z, right = X, left = C and top = V.
- Say it in your game. If your game plays well with a controller, put it in its description: INFO DESC PLAYS WITH A CONTROLLER. That way whoever opens it on a PC or TV knows they can.
Lesson 32 · Music for each screen
- Where your music lives. Your music lives inside the cart, together with the code and the drawings: 64 sound effects, 20 patterns and one 4-channel song. SAVE, UPLOAD and EXPORT keep it with everything, and anyone who opens your game hears it the same.
- Song happy. Type SONG HAPPY: it fills patterns 10 to 13 and the song. If you like, DRUMS CUMBIA adds a beat.
- Put: music per screen. The title loops one pattern, the game plays the song, the boss plays a tenser pattern and the end stops the music and plays an effect.
-- Music for each screen: the title, the game and the boss sound different. -- First type SONG HAPPY on the command line. local estado = 'titulo' local t = 0 local textos = { -- what each screen says titulo = 'TITLE · Z STARTS', juego = 'GAME · THE BOSS IS COMING...', jefe = 'BOSS · Z BEATS IT', fin = 'END · Z AGAIN', } -- changes screen and starts ITS music only once local function cambiar(nuevo) estado, t = nuevo, 0 if nuevo == 'titulo' then music(10) -- a single pattern that loops elseif nuevo == 'juego' then track() -- the whole song, with its 4 channels elseif nuevo == 'jefe' then music(1) -- another pattern, tenser else music(-1) -- silence... sfx(3) -- ...and a victory effect end end function _init() cambiar('titulo') end function _update() t = t + 1 if estado == 'titulo' and btnp(4) then cambiar('juego') elseif estado == 'juego' and t > 240 then cambiar('jefe') -- after 8 seconds elseif estado == 'jefe' and btnp(4) then cambiar('fin') elseif estado == 'fin' and btnp(4) then cambiar('titulo') end if btnp(5) then sfx(0) end -- X: an effect plays on top of the music end function _draw() local fondo = { titulo = 1, juego = 3, jefe = 2, fin = 0 } cls(fondo[estado]) local w = print(textos[estado], 0, -10) print(textos[estado], (128 - w) // 2, 60, 7) print('X: AN EFFECT ON TOP', 26, 110, 6) end -- CHALLENGES: up for it? -- 1. compose a victory pattern at 7 and play it with music(7) at the end -- 2. make the boss music faster (in Music, 1X → 2X) -- 3. add DRUMS ROCK to the game song - Music, track and music(-1). music(10) loops one pattern (good for the title), track() plays the whole song, track(false) plays it once and music(-1) stops everything. sfx() plays on top without cutting the music.
- Only once. The most common mistake: putting music() inside _update. Since it runs 30 times per second, the song keeps restarting and you only hear a tiny bit. Start it only when the screen changes, like in cambiar().
- Challenge: victory. Challenge: compose a short victory pattern in Music at 7 and play it with music(7) at the end.
Lesson 33 · Compose your song
- The melody with rec. In Music (F5) pick pattern 05 and open the piano (tap the bottom line). Tap + until the red R shows: a metronome plays; play a melody and it gets written. Tap R to stop.
- The bass. In pattern 06 pick the triangle wave and add a few low notes, one per beat (every 4 steps), with the octave at -1.
- The drums. Type DRUMS ROCK (or CUMBIA, DEMBOW…): the kick goes to 08 and the snare to 09.
- Build the song. Tap SONG: in slots 1 to 4 put channel 1 = 05, channel 2 = 06, channel 3 = 08 and channel 4 = 09. Play plays the whole song.
- A second part. COPYPATTERN 5 7 copies the melody and TRANSPOSE +5 7 raises it: put it in slots 3 and 4 of channel 1 so the song changes. SWING 1 gives it a swing.
- In your game and outside. In your code, track() plays it. SAVE MYGAME keeps it with everything. WAV downloads it as an audio file, and the Play VIDEO now records the game with its music.
🌙 Lua course
The Chivo-8 language part by part: what each thing is and what it is for. In the console: LUA shows the list and LUA 1 starts.
LUA 1 · What is lua
- A language from brazil. Lua means moon in Portuguese. It was created in 1993 at a university in Rio de Janeiro (PUC-Rio), Brazil. It is small, fast and easy to put inside other programs.
- Where is it used?. PICO-8 and TIC-80 use it, Roblox (with Luau, a version of Lua), mods for many games like World of Warcraft, and programs like Neovim. Chivo-8 uses it because it reads almost like plain words.
- Put: hello, lua. Your first program: it draws two texts. Type RUN to see it.
-- Hello, Lua. Anything after two dashes is a comment: -- Lua does not read it, it is a note for you (or whoever reads your code). function _draw() cls(1) print('HELLO, LUA', 46, 56, 10) print('THIS IS A PROGRAM', 26, 68, 7) end - What it looks like. In Lua blocks end with end (no curly braces { }) and you do not need semicolons. Anything after -- is a comment: a note Lua does not read.
LUA 2 · Variables and types
- A box with a name. A variable stores a value: local vidas = 3. With local the box only exists in that part of the code, so it does not clash with others with the same name.
- Put: the types. Every value has a type: number, string (text), boolean (true or false), nil (nothing) and table. type() tells you which one.
-- Variables: a box with a name that stores a value. local vidas = 3 -- number local nombre = 'CHIVO' -- string (text) local vivo = true -- boolean (yes or no) local nada = nil -- nil: the box is empty local mochila = {} -- table function _draw() cls(0) print('vidas = ' .. vidas .. ' ' .. type(vidas), 4, 10, 7) print('nombre = ' .. nombre .. ' ' .. type(nombre), 4, 22, 7) print('vivo = ' .. tostring(vivo) .. ' ' .. type(vivo), 4, 34, 7) print('nada = ' .. tostring(nada) .. ' ' .. type(nada), 4, 46, 7) print('mochila: ' .. type(mochila), 4, 58, 7) print('type() tells the type', 4, 80, 6) end - Nil is nothing. nil means the box is empty. A variable you never created is nil: that is why many errors say a nil value.
- Lua guesses the type. In Lua you do not write the type: the same box can hold a number and later a text. It is handy, but if you make a mistake you only find out when it runs.
LUA 3 · Operators
- Put: calculate. Addition, subtraction, multiplication, division, integer division, remainder and power, with their results on screen.
-- Operators: Lua calculates and you see the result. local a, b = 7, 2 function _draw() cls(0) print('a = 7 b = 2', 4, 4, 10) print('a + b = ' .. a + b, 4, 16, 7) print('a - b = ' .. a - b, 4, 24, 7) print('a * b = ' .. a * b, 4, 32, 7) print('a / b = ' .. a / b, 4, 40, 7) -- always gives a decimal print('a // b = ' .. a // b, 4, 48, 7) -- integer division print('a % b = ' .. a % b, 4, 56, 7) -- the remainder print('a ^ b = ' .. a ^ b, 4, 64, 7) -- power print('a == b ' .. tostring(a == b), 4, 80, 11) print('a ~= b ' .. tostring(a ~= b), 4, 88, 11) -- ~= means different print('a > b and b > 0: ' .. tostring(a > b and b > 0), 4, 96, 11) print('#CHIVO = ' .. #'CHIVO', 4, 112, 12) -- # measures the text end - / and //. 7 / 2 gives 3.5 (always decimal). 7 // 2 gives 3 (the whole part). 7 % 2 gives 1 (what is left over): useful to know if a number is even or to make things wrap around.
- Comparing. == asks if they are equal and ~= if they are different (in almost every other language it is !=). A single = does not compare: it stores.
- And, or, not and ... and needs both to be true, or needs one, not flips it. The two dots .. join texts and # measures a text or a list.
LUA 4 · Deciding with if
- Put: if. Z adds points and the message changes depending on how many you have. X resets them.
-- Deciding: if asks something and does one thing or another. local puntos = 0 function _update() if btnp(4) then puntos = puntos + 1 end if btnp(5) then puntos = 0 end end function _draw() cls(1) print('POINTS: ' .. puntos, 40, 30, 7) if puntos == 0 then print('PRESS Z', 46, 60, 6) elseif puntos < 5 then print('GOING WELL', 48, 60, 11) else print('YOU ARE A STAR', 38, 60, 10) end if 0 then print('0 IS ALSO TRUE', 14, 100, 8) end print('X: RESET', 46, 116, 5) end - If, elseif, else. if asks; if it is not true, elseif asks something else; else is what happens when nothing was true. It all ends with a single end.
- 0 is true. A Lua quirk: only nil and false count as false. 0 and the empty text are true. In JavaScript and Python 0 is false.
- A trick with or. nombre = nombre or 'CHIVO' sets a default value: if nombre was nil, it becomes CHIVO.
LUA 5 · Loops
- Put: loops. Circles with for, a countdown, a while and a list of fruits.
-- Loops: for counts, while waits for something to change. function _draw() cls(0) for i = 1, 10 do -- i is 1, 2, 3... up to 10 circfill(i * 11, 16, 4, i) end for i = 10, 1, -1 do -- from 10 to 1 (-1 is the step) print(i, 2 + (10 - i) * 12, 30, 7) end local n = 1 while n < 100 do -- repeats while it is true n = n * 2 end print('WHILE: ' .. n, 4, 48, 11) -- the first double above 100 local frutas = { 'MANGO', 'PAPAYA', 'COCO' } for i, f in ipairs(frutas) do -- ipairs: each item of a list print(i .. ' ' .. f, 4, 60 + i * 8, 10) end end - For with numbers. for i = 1, 10 do repeats with i being 1, 2, 3 up to 10. A third number is the step: for i = 10, 1, -1 counts backwards.
- While and repeat. while repeats as long as something is true. repeat ... until repeats until it becomes true. break leaves the loop early. Careful: if it never changes, it repeats forever.
- Ipairs and pairs. for i, f in ipairs(lista) goes through a list in order. pairs goes through a record (name = value), but in no fixed order.
LUA 6 · Functions
- Put: functions. A function that draws squares, another that returns two results and another that takes a function.
-- Functions: a named piece of code you use many times. local function cuadro(x, y, color) -- receives data (parameters) rectfill(x, y, 12, 12, color) end local function sumarYRestar(a, b) return a + b, a - b -- in Lua it can return two things end local function aplicar(f, n) -- a function can receive another return f(n) end function _draw() cls(1) cuadro(10, 10, 8) cuadro(30, 10, 11) cuadro(50, 10, 12) local s, r = sumarYRestar(10, 3) print('SUM ' .. s .. ' DIFF ' .. r, 4, 40, 7) print('DOUBLE OF 21: ' .. aplicar(function(n) return n * 2 end, 21), 4, 56, 10) end - Parameters and return. What goes inside the parentheses is the data it receives. return gives back a result and ends the function.
- Two results. Lua lets you return several values: local s, r = sumarYRestar(10, 3). In many languages you would have to put them in a list.
- Functions as data. A function can be stored in a variable or passed to another function, like aplicar(f, n). _update and _draw are functions Chivo-8 calls 30 times per second.
LUA 7 · Tables
- Put: tables. A list, a record and a table inside another, and how to go through them.
-- Tables: the only structure in Lua. It works as a list and as a record. local lista = { 'SWORD', 'ESCUDO', 'POTION' } -- list: starts at 1 local chivo = { nombre = 'CHIVO', vidas = 3 } -- record: name = value local mundo = { jefe = { nombre = 'ROCO', vida = 30 } } -- tables inside tables function _init() table.insert(lista, 'LLAVE') -- adds at the end chivo.saltos = 0 -- a record can grow end function _draw() cls(0) print('lista[1] = ' .. lista[1], 4, 4, 7) print('#lista = ' .. #lista, 4, 12, 7) print('lista[0] = ' .. tostring(lista[0]), 4, 20, 8) -- does not exist: nil print('chivo.vidas = ' .. chivo.vidas, 4, 34, 11) print('jefe: ' .. mundo.jefe.nombre, 4, 42, 11) local y = 58 for k, v in pairs(chivo) do -- pairs goes through a record (no fixed order) print(k .. ' = ' .. tostring(v), 4, y, 6) y = y + 8 end end - The only structure. Other languages have lists, dictionaries, objects and classes. Lua only has tables, and it does all of that with them.
- They start at 1. In Lua the first item is lista[1]. In JavaScript, Python and C# it is [0]. It is the difference that confuses people most when switching languages.
- With a dot or brackets. chivo.vidas and chivo['vidas'] are the same. table.insert adds, table.remove removes and # counts the items in a list.
LUA 8 · Text
- Put: text. Measuring, cutting, reversing, repeating, formatting, searching and counting words.
-- Text: string has functions to cut, search and build it. local t = 'CHIVO IS GREAT' function _draw() cls(1) print(t, 4, 4, 10) print('#t = ' .. #t, 4, 16, 7) -- how many characters print('sub(1, 5) = ' .. string.sub(t, 1, 5), 4, 24, 7) -- a piece print('reverse = ' .. string.reverse('CHIVO'), 4, 32, 7) -- reversed print('rep = ' .. string.rep('JA', 3), 4, 40, 7) -- repeat print('format = ' .. string.format('%03d', 7), 4, 48, 7) -- 7 with zeros: 007 print('space at ' .. string.find(t, ' '), 4, 56, 7) -- where the first space is local palabras = 0 for p in string.gmatch(t, '%S+') do palabras = palabras + 1 end print('palabras = ' .. palabras, 4, 64, 7) print('#AÑO = ' .. #'AÑO', 4, 80, 8) -- Ñ takes 2 bytes: gives 4 end - String.sub. string.sub(t, 1, 5) gives characters 1 to 5. Negative numbers count from the end: string.sub(t, -3) is the last three.
- Format and gmatch. string.format('%03d', 7) gives 007: handy for scores. string.gmatch(t, '%S+') goes through each word; %S+ is a pattern: several characters that are not spaces.
- Bytes and accents. Lua counts bytes, not letters: accented letters take 2. That is why #AÑO gives 4 and in lessons 18 and 19 the Spanish messages have no accents.
LUA 9 · Common mistakes
- Put: buggy code. This code has 3 mistakes on purpose. Type RUN: Chivo-8 tells you which line has the first one.
-- This code has 3 mistakes on purpose. -- Type RUN, read what Chivo-8 says, fix it and run it again. local x = 10 function _update() if btn(1) then x = x + velocidad end -- mistake 2: velocidad does not exist if btn(0) then x = x - 1 -- mistake 1: missing end end function _draw() cls(1) rectfill(x, 60, 8, 8, 10) print('X: ' .. posicion, 4, 4, 7) -- mistake 3: it is called x, not posicion end - Mistake 1: missing end. The message says it expected end. Every if, for, while and function needs its end. Add end at the end of the btn(0) line.
- Mistakes 2 and 3: nil. attempt to perform arithmetic on a nil value: you added something that does not exist (velocidad). attempt to concatenate a nil value: you joined text with nil (posicion). Change them to 1 and x.
- Other classics. = instead of == inside an if, looking for lista[0], writing != instead of ~= and forgetting local (the variable becomes global and another part of the code changes it).
LUA 10 · Objects with tables
- What an object is. An object puts data (where it is, its color) together with what it can do (move, draw itself). A class is the mold to make many of them.
- Put: enemy class. Five enemies made from the same mold. Each one bounces on its own.
-- Objects: an Enemigo class made with tables and a metatable. local Enemigo = {} Enemigo.__index = Enemigo -- whatever the enemy lacks, it looks up in Enemigo function Enemigo.nuevo(x, y, color) local e = { x = x, y = y, color = color, vx = 1 } return setmetatable(e, Enemigo) -- now e can use the Enemigo functions end function Enemigo:mover() -- the colon passes the enemy as self self.x = self.x + self.vx if self.x < 0 or self.x > 120 then self.vx = -self.vx end end function Enemigo:dibujar() rectfill(self.x, self.y, 8, 8, self.color) end local lista = {} function _init() for i = 1, 5 do table.insert(lista, Enemigo.nuevo(i * 18, i * 20, 7 + i)) end end function _update() for _, e in ipairs(lista) do e:mover() end end function _draw() cls(0) for _, e in ipairs(lista) do e:dibujar() end print('5 ENEMIES, ONE CLASS', 22, 120, 7) end - Setmetatable and __index. setmetatable(e, Enemigo) tells e: whatever you do not have, look it up in Enemigo. That way they all share mover and dibujar without copying them.
- The colon. e:mover() is the same as e.mover(e). Inside the function, self is the enemy that called it.
- Like in other languages. In C#, JavaScript and Python this is written with the word class. Lua does not have it, but it does the same with tables.
📖 Lua guide: the language in depth
Lua in depth, to read calmly and come back to. The Lua course (in the console: LUA 1) is the short step-by-step version. Each chapter has a ▶ Try it program: copy it into CODE, press RUN and then change its numbers to see what happens.
1 · How a program is built
A Lua program is a list of statements read from top to bottom.
No semicolons or curly braces: blocks start with a word (function, if … then,
for … do, while … do) and finish with end.
- Comments: anything after
--is a note for people; Lua skips it. For several lines:--[[ … ]]. - Case matters:
lives,LivesandLIVESare three different names. - Names: letters, digits and
_, not starting with a digit. - Reserved words (can't be names):
and break do else elseif end false for function goto if in local nil not or repeat return then true until while. - Spaces and indentation change nothing for Lua, but help a lot when reading: each block two spaces further in.
The shape of a Chivo-8 game
Every game in the library follows the same order. Lua reads the file top to bottom, so a local function must be
written before the part that uses it:
-- 1. Settings: the numbers that decide how it feels (in CAPITALS)
local SPEED = 2
-- 2. Tools: small functions the whole game uses
local function centered(text, y, color)
print(text, 64 - #text * 2, y, color)
end
-- 3. State: what changes while you play
local x, y, score
-- 4. The three functions the console calls by itself
function _init() -- once, at the start
x, y, score = 60, 60, 0
end
function _update() -- 30 times a second: move, collide, count
if btn(0) then x = x - SPEED end
if btn(1) then x = x + SPEED end
end
function _draw() -- after each _update: draw
cls(1)
centered('SCORE ' .. score, 4, 7)
rectfill(x, y, 8, 8, 8)
endTo see a real one: OPEN SALTARIN (or the ✎ in the library) puts the whole game in your
editors. Look for those four parts in its code.
▶ Try it: paste it in CODE and press RUN.
-- Move the square with the arrows
local SPEED = 2
local x, y
function _init()
x, y = 60, 60
end
function _update()
if btn(0) then x = x - SPEED end
if btn(1) then x = x + SPEED end
if btn(2) then y = y - SPEED end
if btn(3) then y = y + SPEED end
end
function _draw()
cls(1)
print('MOVE WITH THE ARROWS', 24, 4, 7)
rectfill(x, y, 8, 8, 8)
end2 · Values and types
Every Lua value has one of these types. type(value) tells you which.
nil | "Nothing". A variable with no value is nil. It causes the most common error: using something that doesn't exist. |
boolean | true or false. |
number | Whole numbers (3) or decimals (0.5). Also hexadecimal: 0xff = 255. |
string | Text: 'hi' or "hi". |
table | A box that holds many values: lists, named records, whole levels. |
function | A named piece of code you can call. It's a value too! |
What counts as true?
In a condition, only nil and false are false. Everything else is true, even
0 and the empty string '' (other languages differ).
if 0 then print('0 is true in Lua', 2, 2, 7) end
if nil then print('this never shows', 2, 10, 8) end
Converting
tonumber('42') -- 42 (text → number; nil if it can't)
tostring(42) -- '42' (number → text)
'SCORE ' .. 10 -- 'SCORE 10' (.. converts the number by itself)
math.floor(3.7) -- 3 (drops the decimals)
7 // 2 -- 3 (integer division)
7 / 2 -- 3.5 (normal division always gives decimals)▶ Try it: paste it in CODE and press RUN.
-- Shows the type of each value
local values = { 42, 0.5, 'hello', true, {}, print }
function _draw()
cls(1)
print('LUA TYPES', 46, 4, 10)
for i, v in ipairs(values) do
print(tostring(v):sub(1, 12), 4, 10 + i * 10, 6)
print(type(v), 70, 10 + i * 10, 11)
end
print('and nil: ' .. type(nil), 4, 90, 8)
end3 · Variables: local and global
A variable is a name that holds a value. There are two kinds:
local: only exists inside the block where it was written (the function, theif, thefor…) and from there down. It's almost always the right choice: it doesn't clash with others of the same name and Lua reads it faster.- Global (no
local): exists in the whole program._init,_updateand_draware global because the console has to find them.
local lives = 3 -- file local: every function below sees it
function _update()
local dx = 0 -- local to _update: born and gone every frame
if btn(0) then dx = -1 end
for i = 1, 3 do
local double = i * 2 -- local to the for: doesn't exist outside
end
end
A very common mistake: forgetting local inside a function
If you write score = 0 without local and without declaring it before, Lua creates a new global. If you
mistype it (socre), it doesn't warn you either: it creates another variable and yours stays the same.
Several at once
local x, y = 10, 20 -- x = 10, y = 20
x, y = y, x -- swap in one line: now x = 20, y = 10
local a, b, c = 1 -- a = 1, b and c = nil
Constants
Lua has no real constants. By habit, values that shouldn't change are written in CAPITALS
(SPEED, GRAVITY) at the very top: that way anyone knows where to tune the game.
▶ Try it: paste it in CODE and press RUN.
-- local vs global: the outer counter keeps going, the inner one starts over
local times = 0
function _update()
times = times + 1
local frame = 0
frame = frame + 1
end
function _draw()
cls(1)
print('TIMES (FILE LOCAL): ' .. times, 4, 40, 11)
print('FUNCTION LOCAL: ALWAYS 1', 4, 56, 8)
end4 · Operators
+ - * / | Add, subtract, multiply, divide (7 / 2 = 3.5). |
// | Integer division: 7 // 2 = 3. |
% | Remainder: 7 % 2 = 1. Good for "every N frames": if t % 30 == 0 then. |
^ | Power: 2 ^ 3 = 8. |
== ~= | Equal and not equal (in Lua it's ~=, not !=). |
< > <= >= | Less, greater, less or equal, greater or equal. |
and or not | And, or, not. |
.. | Joins text: 'HI ' .. name. |
# | Length of a list or a string: #enemies. |
There's no ++ or +=: write score = score + 1.
and and or return values
a or b gives a if it's true; otherwise b. a and b gives b if a is true. Two tricks come from that:
speed = speed or 1 -- default value: if it was nil, now it's 1
local color = alive and 11 or 8 -- "if alive then 11 else 8" in one line
local text = musicOn and 'ON' or 'OFF' -- the library games do this
Careful: c and x or y fails if x is false or nil (you get y). Use a normal if for that.
Order
Like in math: first ^, then * / // %, then + -, then .., then comparisons, then
and and finally or. When in doubt, use parentheses: (a + b) * 2.
▶ Try it: paste it in CODE and press RUN.
-- % for things that repeat: blinking and cycling colors
local t = 0
function _update()
t = t + 1
end
function _draw()
cls(0)
if t % 30 < 15 then print('BLINKS EVERY SECOND', 26, 30, 7) end
for i = 0, 15 do
rectfill(i * 8, 60, 8, 8, (i + t // 4) % 16)
end
print('7 // 2 = ' .. 7 // 2 .. ' 7 % 2 = ' .. 7 % 2, 16, 90, 10)
print('2 TO THE 8TH = ' .. math.floor(2 ^ 8), 26, 100, 10) -- the font has no ^
end5 · Deciding and repeating
Deciding
if lives == 0 then
state = 'over'
elseif lives == 1 then
heartColor = 8 -- red: one left
else
heartColor = 11
end
Repeating a number of times: numeric for
for i = 1, 10 do ... end -- 1, 2, 3 … 10
for i = 0, 120, 8 do ... end -- in steps of 8: 0, 8, 16 … 120
for i = 10, 1, -1 do ... end -- backwards: 10, 9 … 1
The variable (i) is local to the for and shouldn't be changed inside.
Going through a list: generic for
for i, e in ipairs(enemies) do ... end -- in order: i = 1, 2, 3…
for key, value in pairs(record) do ... end -- every field (no fixed order)
While something is true
while x < 100 do x = x + 7 end -- checks BEFORE each round
repeat y = y - 1 until y <= 0 -- checks AFTER: runs at least once
Leaving early or skipping a round
for i = 1, #list do
if list[i] == wanted then found = i; break end -- break: leaves the loop
end
for _, e in ipairs(enemies) do
if not e.alive then goto continue end -- Lua has no "continue": goto does it
e.x = e.x + 1
::continue::
end
⚠ Don't put a while that waits for the player inside _update or _draw (like
while not btn(4) do end): the game freezes, because the console never gets to read the buttons. To wait, use a
state variable (chapter 14) or a coroutine (chapter 12).
▶ Try it: paste it in CODE and press RUN.
-- nested for: a grid of colors
function _draw()
cls(0)
for row = 0, 7 do
for col = 0, 7 do
local color = (row + col) % 2 == 0 and 12 or 1
rectfill(16 + col * 12, 16 + row * 12, 11, 11, color)
end
end
print('2 FORS, ONE INSIDE THE OTHER', 8, 116, 7)
end6 · Functions
A function is a named piece of code: you write it once and use it as many times as you like.
local function distance(x1, y1, x2, y2)
local dx, dy = x2 - x1, y2 - y1
return math.sqrt(dx * dx + dy * dy)
end
if distance(px, py, ex, ey) < 8 then lose() end
- Call it with fewer values and the missing ones arrive as
nil; with more, the extra ones are ignored. - Default values:
color = color or 7at the start of the function. returnends the function. Withoutreturn, it returnsnil.
Returning several values
local function center(r) return r.x + r.w / 2, r.y + r.h / 2 end
local cx, cy = center(player)
Functions are values
They go in variables and tables and get passed to other functions. For example, to sort a list with your own rule:
table.sort(scores, function(a, b) return a.p > b.p end) -- highest first
local actions = {
jump = function() vy = -4 end,
crouch = function() height = 4 end,
}
actions.jump()
Functions that remember (closures)
A function made inside another one can use the outer local variables, and keeps remembering them after the outer one has finished:
local function counter()
local n = 0
return function() n = n + 1; return n end
end
local nextOne = counter()
nextOne() -- 1
nextOne() -- 2
Any number of values: ...
local function sum(...)
local total = 0
for _, v in ipairs({ ... }) do total = total + v end
return total
end
sum(1, 2, 3) -- 6▶ Try it: paste it in CODE and press RUN.
-- One function draws a health bar; used 3 times
local function bar(x, y, value, max, color)
color = color or 11
rect(x, y, 52, 6, 7)
rectfill(x + 1, y + 1, math.floor(50 * value / max), 4, color)
end
local t = 0
function _update() t = t + 1 end
function _draw()
cls(1)
print('LIFE', 4, 20, 7); bar(40, 20, 7, 10)
print('MAGIC', 4, 40, 7); bar(40, 40, t % 100, 100, 12)
print('BOSS', 4, 60, 7); bar(40, 60, 3, 10, 8)
end7 · Tables I: lists
A table with numbers as keys is a list. In Lua counting starts at 1, not 0.
local fruits = { 'mango', 'papaya', 'guava' }
fruits[1] -- 'mango'
#fruits -- 3
fruits[#fruits + 1] = 'lime' -- add at the end
table.insert(fruits, 'plum') -- same thing
table.insert(fruits, 1, 'fig') -- add at the start (shifts the rest)
table.remove(fruits, 2) -- remove number 2 (shifts the rest)
table.remove(fruits) -- remove the last one
table.concat(fruits, ', ') -- 'fig, papaya, guava, lime'
table.sort(fruits) -- alphabetical order
Lists of game things
Enemies, bullets, sparks, coins: each one is a table inside a list.
local bullets = {}
-- shoot: a new table in the list
bullets[#bullets + 1] = { x = ship.x, y = ship.y, vy = -3 }
-- move them and remove the ones that leave the screen: ALWAYS back to front
for i = #bullets, 1, -1 do
local b = bullets[i]
b.y = b.y + b.vy
if b.y < 0 then table.remove(bullets, i) end
end
Why back to front? If you remove number 3 going forward, number 4 becomes number 3 and the loop skips it.
⚠ # only works well on lists without holes. If you do list[2] = nil in the middle, the length can't be trusted:
use table.remove to take things out.
▶ Try it: paste it in CODE and press RUN.
-- Z shoots; bullets are removed when they leave the screen
local bullets, x = {}, 60
function _update()
if btn(0) then x = x - 2 end
if btn(1) then x = x + 2 end
if btnp(4) then bullets[#bullets + 1] = { x = x + 3, y = 110 } end
for i = #bullets, 1, -1 do
local b = bullets[i]
b.y = b.y - 3
if b.y < 0 then table.remove(bullets, i) end
end
end
function _draw()
cls(0)
rectfill(x, 112, 8, 6, 12)
for _, b in ipairs(bullets) do rectfill(b.x, b.y, 2, 4, 10) end
print('Z SHOOTS · BULLETS: ' .. #bullets, 4, 4, 7)
end8 · Tables II: records and data
A table can also use names as keys: that's how you make a record of something.
local player = { x = 20, y = 40, lives = 3, name = 'GOAT' }
player.x -- 20 (same as player['x'])
player.speed = 2 -- add a new field
player.name = nil -- remove a field
local field = 'lives'
player[field] -- 3: with [ ] the name can come from a variable
Going through every field
for key, value in pairs(player) do
print(key .. ' = ' .. tostring(value), 2, y, 7)
end
pairs doesn't guarantee the order. If order matters, use a list with ipairs.
Tables inside tables: levels as data
The library games store their levels like this: the code that plays them is written once and each level is a table.
local LEVELS = {
{ name = 'THE YARD', enemies = 3, speed = 1 },
{ name = 'THE MARKET', enemies = 6, speed = 1.5 },
{ name = 'THE ROOF', enemies = 9, speed = 2 },
}
local l = LEVELS[2]
print(l.name, 2, 2, 7) -- THE MARKET
⚠ Copying a table doesn't duplicate it
local a = { lives = 3 }
local b = a -- b is ANOTHER NAME for the same table
b.lives = 0
print(a.lives) -- 0 as well
local function copy(t) -- one-level copy
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
For the same reason, { 1 } == { 1 } is false: they're two different tables with the same contents.
▶ Try it: paste it in CODE and press RUN.
-- Pick a level with UP/DOWN: everything comes from the LEVELS table
local LEVELS = {
{ name = 'THE YARD', color = 11, enemies = 3 },
{ name = 'THE MARKET', color = 9, enemies = 6 },
{ name = 'THE ROOF', color = 12, enemies = 9 },
}
local sel = 1
function _update()
if btnp(2) then sel = math.max(1, sel - 1) end
if btnp(3) then sel = math.min(#LEVELS, sel + 1) end
end
function _draw()
cls(1)
for i, l in ipairs(LEVELS) do
print((i == sel and '> ' or ' ') .. l.name, 20, 20 + i * 12, i == sel and l.color or 6)
end
local l = LEVELS[sel]
print('ENEMIES: ' .. l.enemies, 20, 90, 7)
for k = 1, l.enemies do rectfill(8 + k * 11, 102, 8, 8, 8) end
end9 · Text
Text (a string) goes between single or double quotes. For text with several lines: [[ … ]].
local a = 'HELLO'
local b = "SHE SAID: 'HI'" -- with doubles, singles fit inside
local c = 'FIRST\nSECOND' -- \n = new line
local d = [[
SEVERAL
LINES]]
Text functions
You can write string.upper(s) or, shorter, s:upper() (with a colon).
s:upper() · s:lower() | All upper or lower case. |
s:sub(2, 4) | A piece: letters 2 to 4. s:sub(-3) = the last 3. |
s:rep(3) | Repeats: ('-'):rep(5) = '-----'. |
s:find('x') | Where something appears (or nil). |
s:gsub('a', 'o') | Replaces all: ('banana'):gsub('a', 'o') = 'bonono'. |
s:byte(1) · string.char(65) | Letter ↔ number (65 = 'A'). |
string.format('%03d', 7) | Shaped numbers: '007'. %d integer, %.1f one decimal, %5d 5 places wide, %s text. |
Patterns: searching with wildcards
%d a digit, %a a letter, %s a space, . anything; + one or more, * zero or more.
local level = ('LEVEL 12'):match('%d+') -- '12'
for word in ('A B C'):gmatch('%S+') do ... end -- each word: A, B, C
local note, octave = ('c5'):match('^(%a)(%d)$') -- 'c', '5' (how cancion() reads notes)
⚠ Accented letters take 2
Lua counts bytes, not letters: #'AÑO' is 4, because Ñ takes 2. That's why the library games
center text with the width print() returns, not with #text:
local function width(s) return print(s, 0, -10) end -- print off screen: it only measures
local function centered(s, y, c) print(s, (128 - width(s)) // 2, y, c) end▶ Try it: paste it in CODE and press RUN.
-- Shaped text: clock, score with zeros and centering
local function width(s) return print(s, 0, -10) end
local function centered(s, y, c) print(s, (128 - width(s)) // 2, y, c) end
local t = 0
function _update() t = t + 1 end
function _draw()
cls(1)
local sec = t // 30
centered(string.format('TIME %02d:%02d', sec // 60, sec % 60), 30, 7)
centered(string.format('SCORE %06d', t * 7), 46, 10)
centered(('lullaby'):upper(), 62, 11)
centered('ÑANDÚ ' .. #'ÑANDÚ' .. ' BYTES', 78, 8)
centered(('-'):rep(20), 94, 6)
end10 · Numbers and randomness (math)
math.floor(x) · math.ceil(x) | Rounds down or up. To draw, use whole numbers: math.floor(x). |
math.abs(x) | Without sign: math.abs(-3) = 3. |
math.min(a, b) · math.max(a, b) | The smaller or the larger. Together they clamp: x = math.max(0, math.min(120, x)). |
math.random(n) | Random whole number from 1 to n. math.random(a, b) from a to b; math.random() a decimal from 0 to 1. |
math.sqrt(x) | Square root (for distances). |
math.sin(a) · math.cos(a) | Waves and circles. Angles are in radians: a full turn = 2 * math.pi. |
math.atan(dy, dx) | The angle to go from one point to another. |
math.pi · math.huge | π (3.1416…) and "infinity". |
Game recipes
-- pick something random from a list
local prize = PRIZES[math.random(#PRIZES)]
-- make the enemy go towards the player
local ang = math.atan(py - ey, px - ex)
ex = ex + math.cos(ang) * 1.5
ey = ey + math.sin(ang) * 1.5
-- float up and down (t = frames)
local floatY = 60 + math.sin(t / 10) * 4
-- gravity: speed changes position and gravity changes speed
vy = vy + 0.25
y = y + vy▶ Try it: paste it in CODE and press RUN.
-- Sparks: random position, speed and gravity
local sparks = {}
function _update()
for _ = 1, 3 do
local ang = math.random() * 2 * math.pi
sparks[#sparks + 1] = { x = 64, y = 50, vx = math.cos(ang) * 2, vy = math.sin(ang) * 2 - 1, life = 40 }
end
for i = #sparks, 1, -1 do
local s = sparks[i]
s.vy = s.vy + 0.1
s.x, s.y, s.life = s.x + s.vx, s.y + s.vy, s.life - 1
if s.life <= 0 then table.remove(sparks, i) end
end
end
function _draw()
cls(0)
for _, s in ipairs(sparks) do pset(math.floor(s.x), math.floor(s.y), s.life > 20 and 10 or 9) end
print('SPARKS: ' .. #sparks, 4, 4, 7)
end11 · Objects and metatables
Lua has no "classes" like other languages: tables and functions build the same thing.
A table with its own functions
local dog = { x = 10, barks = 0 }
function dog:bark() -- with : the function gets "self" (the table itself)
self.barks = self.barks + 1
end
dog:bark() -- same as dog.bark(dog)
A mold to make many: metatables
A metatable tells a table what to do when it's asked for something it doesn't have. With __index,
every enemy shares the mold's functions without copying them:
local Enemy = {}
Enemy.__index = Enemy -- whatever an enemy lacks, it looks up in Enemy
function Enemy.new(x, y)
return setmetatable({ x = x, y = y, speed = 1 }, Enemy)
end
function Enemy:move() self.x = self.x + self.speed end
function Enemy:draw() rectfill(self.x, self.y, 8, 8, 8) end
local e = Enemy.new(10, 20)
e:move(); e:draw()
Inheritance: a mold based on another
local Boss = setmetatable({}, { __index = Enemy }) -- whatever Boss lacks, in Enemy
Boss.__index = Boss
function Boss.new(x, y)
local b = Enemy.new(x, y)
b.life = 20
return setmetatable(b, Boss)
end
function Boss:draw() rectfill(self.x, self.y, 16, 16, 2) end -- draws differently; inherits move()
Other metamethods: __tostring (how it looks with tostring), __add (what + does between two tables), __eq (when two are equal).
▶ Try it: paste it in CODE and press RUN.
-- One mold (Bug) and another that inherits from it (Boss)
local Bug = {}
Bug.__index = Bug
function Bug.new(x, y, speed)
return setmetatable({ x = x, y = y, speed = speed }, Bug)
end
function Bug:move()
self.x = self.x + self.speed
if self.x < 0 or self.x > 120 then self.speed = -self.speed end
end
function Bug:draw() rectfill(self.x, self.y, 8, 8, 11) end
local Boss = setmetatable({}, { __index = Bug })
Boss.__index = Boss
function Boss.new(x, y) return setmetatable(Bug.new(x, y, 0.5), Boss) end
function Boss:draw() rectfill(self.x - 4, self.y - 4, 16, 16, 8) end
local all = {}
function _init()
for i = 1, 4 do all[#all + 1] = Bug.new(i * 20, i * 16, i * 0.5) end
all[#all + 1] = Boss.new(60, 100)
end
function _update() for _, b in ipairs(all) do b:move() end end
function _draw()
cls(1)
for _, b in ipairs(all) do b:draw() end
print('4 BUGS AND 1 BOSS, SAME move()', 4, 2, 7)
end12 · Coroutines: step-by-step things
A coroutine is a function that can pause halfway (coroutine.yield()) and continue
later from there (coroutine.resume()). It's for things that happen "step by step" over time —a cutscene, a dialogue, a
boss routine— without filling the game with "which step am I on" variables.
local function wait(frames)
for _ = 1, frames do coroutine.yield() end
end
local scene = coroutine.create(function()
text = 'HELLO, TRAVELER'
wait(60) -- 2 seconds (30 frames = 1 s)
text = 'THE TREASURE IS IN THE CENOTE'
wait(90)
text = ''
end)
function _update()
if coroutine.status(scene) ~= 'dead' then coroutine.resume(scene) end
end
Each _update gives the coroutine a push; it runs until the next yield and stops there until the next frame.
When it reaches the end, its status becomes 'dead'.
▶ Try it: paste it in CODE and press RUN.
-- A boss with a routine: moves, waits, shoots, starts again
local boss = { x = 10, y = 30 }
local bullets = {}
local function wait(n) for _ = 1, n do coroutine.yield() end end
local routine = coroutine.create(function()
while true do
for _ = 1, 50 do boss.x = boss.x + 2; coroutine.yield() end
wait(20)
for k = -2, 2 do bullets[#bullets + 1] = { x = boss.x + 6, y = boss.y + 12, vx = k * 0.6 } end
wait(20)
for _ = 1, 50 do boss.x = boss.x - 2; coroutine.yield() end
wait(20)
end
end)
function _update()
coroutine.resume(routine)
for i = #bullets, 1, -1 do
local b = bullets[i]
b.x, b.y = b.x + b.vx, b.y + 2
if b.y > 128 then table.remove(bullets, i) end
end
end
function _draw()
cls(1)
rectfill(boss.x, boss.y, 14, 12, 8)
for _, b in ipairs(bullets) do circfill(b.x, b.y, 2, 10) end
print('A ROUTINE WITH A COROUTINE', 12, 4, 7)
end13 · Errors and how to find them
When something breaks, under the game screen it shows what happened and on which line. Go to that line (in CODE, the bottom bar shows the line you're on) and check the names it uses.
attempt to index a nil value | You used thing.field or thing[1] and thing is nil: it doesn't exist, it's spelled differently or it had no value yet. |
attempt to perform arithmetic on a nil value | Math with something that is nil: almost always a variable with no starting value (give it one in _init). |
attempt to call a nil value | You called a function that doesn't exist: misspelled, or the local function is written below where you use it. |
attempt to concatenate a nil value | 'TEXT' .. thing with thing = nil. Use tostring(thing). |
'end' expected | An end is missing: count the open blocks (function, if, for, while). |
'=' expected or unexpected symbol | Something mistyped on that line: a != instead of ~=, a +=, a missing comma. |
See what's happening: print on screen
The most useful trick: draw the value you suspect on the screen. That way you see whether it changes the way you expect.
function _draw()
-- … your game …
print('VY=' .. tostring(vy) .. ' GROUND=' .. tostring(onGround), 2, 120, 8) -- remove it when done
end
Errors on purpose, and catching them
assert(level <= #LEVELS, 'there is no level ' .. level) -- if false, stops with that message
error('this should not happen') -- stops the game with your own message
local ok, err = pcall(function() -- pcall: try without crashing the game
loadLevel(99)
end)
if not ok then message = 'FAILED: ' .. tostring(err) end▶ Try it: paste it in CODE and press RUN.
-- pcall catches the error; the game goes on and shows what happened
local message = ''
local LEVELS = { 'YARD', 'MARKET' }
local function load(n)
assert(LEVELS[n], 'there is no level ' .. n)
return LEVELS[n]
end
function _init()
local ok, err = pcall(load, 5)
-- the message says where it happened ('[string]:6: …'); gsub removes that part
message = ok and 'OK' or tostring(err):gsub('^.-:%d+: ', '')
end
function _draw()
cls(1)
print('LEVEL 1: ' .. load(1), 4, 20, 11)
print('LEVEL 5:', 4, 40, 7)
print(message, 4, 50, 8)
end14 · Organizing a game
A game grows fast. These habits —the same ones the library games use— keep it readable.
1. States: title, playing, over
One variable says which screen you're on; _update and _draw do different things depending on it.
local state = 'title'
function _update()
if state == 'title' then
if btnp(4) then start(); state = 'playing' end
elseif state == 'playing' then
moveEverything()
if lives == 0 then state = 'over' end
elseif state == 'over' then
if btnp(4) then state = 'title' end
end
end
2. Data apart from code
Levels, enemies, texts and music in tables at the top (chapter 8). To make a new level you add a table, not code.
3. Each thing knows how to move and draw itself
Lists of entities with their own move and draw (chapters 7 and 11): _update and _draw stay short.
4. Short functions with names that say what they do
collide(a, b), loseLife(), nextLevel(). If a function doesn't fit on the screen, split it.
5. Read the library games
With OPEN you open any Chivo-8 game in your editors. A good reading order: ① the comment at the top
("Techniques this cartridge shows") · ② the settings in CAPITALS · ③ _init · ④ _update, looking for the state
· ⑤ _draw. Change a number, press RUN and see what happened: it's faster than just reading.
▶ Try it: paste it in CODE and press RUN.
-- A tiny game with states: catch the squares, miss 3 and you lose
local state, x, falling, score, misses = 'title'
local function start()
x, score, misses = 60, 0, 0
falling = { x = math.random(0, 120), y = 0 }
end
function _update()
if state == 'title' then
if btnp(4) then start(); state = 'playing' end
elseif state == 'playing' then
if btn(0) then x = x - 3 end
if btn(1) then x = x + 3 end
falling.y = falling.y + 1 + score / 5
if falling.y > 110 then
if math.abs(falling.x - x) < 10 then score = score + 1 else misses = misses + 1 end
falling = { x = math.random(0, 120), y = 0 }
end
if misses == 3 then state = 'over' end
elseif btnp(4) then
state = 'title'
end
end
function _draw()
cls(1)
if state == 'title' then
print('CATCH', 54, 50, 10); print('Z TO START', 44, 64, 7)
elseif state == 'playing' then
rectfill(falling.x, falling.y, 8, 8, 9)
rectfill(x - 4, 116, 16, 4, 12)
print('SCORE ' .. score .. ' MISSES ' .. misses, 2, 2, 7)
else
print('OVER: ' .. score .. ' POINTS', 34, 56, 8); print('Z: AGAIN', 48, 70, 7)
end
end15 · Sound and music in your game
The effects and music you make in the editors aren't "exported" to the code: they stay inside the cart, in numbered slots. Your code just says "play slot 5".
1. Where each sound lives
- Effects (F4): 64 slots, 00 to 63 →
sfx(n) - Patterns (F5): 20 slots, 00 to 19 →
music(n)loops one - Song (F5 → SONG): 4 channels × 8 slots, each holding a pattern →
track()
- Inside: while you edit, the editor copies your notes into two engine lists:
SFX_BANK(effects) andMUSIC_BANK(patterns).sfx(5)looks upSFX_BANK[5]and plays its notes one after another.track()walks the song: on each channel it plays the pattern in slot 1, then slot 2… - Factory sounds (new cart):
sfx(0)coin ·sfx(1)jump ·sfx(2)hit ·sfx(3)power-up ·sfx(4)explosion. The song plays patterns 00 and 01.SOUNDS PUTbrings 20 more effects (5 to 24) andSONG HAPPYfills patterns 10 to 13. - Change it without touching the code: if you redo effect 01 in F4, your game uses the new one the next time it calls
sfx(1). - Saved with everything:
SAVE,UPLOADandEXPORTkeep the 64 effects, 20 patterns and the song together with the code and drawings. Anyone who opens your game hears it the same.
2. Effects: at the moment something happens
if btnp(4) then -- on press
vy = -4
sfx(1) -- jump
end
if collide(goat, coin) then
score = score + 1
sfx(0) -- coin
end
With btn (button held) instead of btnp, the effect restarts 30 times per second and sounds like a buzz.
An effect plays on top of the music without cutting it.
3. Music: only once, when the screen changes
music(0) -- loops pattern 00
track() -- whole song
track(false) -- only once
music(-1) -- stops all
The most common mistake is putting music() or track() inside _update: since it runs 30 times per second,
the song keeps restarting and you only hear a tiny bit. Put it in a function that runs once, when the screen changes:
local function change(new)
state = new
if new == 'title' then music(0)
elseif new == 'playing' then track()
elseif new == 'over' then music(-1); sfx(4)
end
end
4. Names instead of numbers
A record (chapter 8) with the name of each effect makes the code easier to read, and if you move an effect to another slot you change a single line:
local SND = { coin = 0, jump = 1, hit = 2, power = 3, boom = 4 }
sfx(SND.jump)
5. tono(): a direct sound, no editor
tono(frequency, duration, wave, volume) plays right away. Frequency is in hertz (440 = A), duration in seconds,
wave is 0 square · 1 triangle · 2 saw · 3 sine · 4 noise, and volume from 0 to 1.
It's for sounds that change with the game, something a fixed effect can't do:
-- each coin in a row sounds a bit higher
combo = combo + 1
tono(300 + combo * 40, 0.08, 1, 0.4)
Note math: one octave up = frequency × 2; one semitone = × 1.0595. That's why the library games compute
440 * 2 ^ ((midi - 69) / 12) to turn "c5" into hertz.
6. Editor or code?
- Editor (sfx, music, track): you hear it while you make it, with custom waves, effects (arpeggio, vibrato, slide), 4 channels and DRUMS. The usual choice for your game.
- Code (tono and songs as text): the library games write their music as text (
cancion('c5 e5 . g5', …)) and play it withtono()every frame, so one game can carry several songs without using the editor. Open them withOPENto see how.
7. If it doesn't play
- The browser won't play anything until you touch the screen or press a key: the first touch turns audio on.
- The slot is empty:
sfx(30)does nothing if effect 30 has no notes. - It's called every frame (point 3) or with
btninstead ofbtnp(point 2). - A song channel is muted or at volume 0 in the Music editor.
▶ Try it: paste it in CODE and press RUN.
-- Sound in a game: title with a pattern, game with the song,
-- effects for jumping and catching, and a tone that rises with the combo.
-- Uses the factory sounds and music (or your own from F4 and F5).
local SND = { coin = 0, jump = 1, hit = 2, boom = 4 }
local state, x, y, vy, combo, score, lives, drop, music_on
local function change(new)
state = new
if new == 'title' then music(0)
elseif new == 'playing' then
x, y, vy, combo, score, lives = 60, 108, 0, 0, 0, 3
drop = { x = math.random(8, 112), y = 0 }
music_on = true
track()
else music(-1); sfx(SND.boom)
end
end
function _init() change('title') end
function _update()
if state ~= 'playing' then
if btnp(4) then change('playing') end
return
end
if btn(0) then x = x - 2 end
if btn(1) then x = x + 2 end
if btnp(4) and y >= 108 then vy = -4; sfx(SND.jump) end
if btnp(5) then -- X turns the music on and off
music_on = not music_on
if music_on then track() else music(-1) end
end
vy = vy + 0.3; y = math.min(108, y + vy)
drop.y = drop.y + 1.2
if math.abs(drop.x - x) < 8 and math.abs(drop.y - y) < 8 then
score = score + 1; combo = combo + 1
sfx(SND.coin)
tono(300 + combo * 40, 0.08, 1, 0.4)
drop = { x = math.random(8, 112), y = 0 }
elseif drop.y > 124 then
lives = lives - 1; combo = 0
sfx(SND.hit)
drop = { x = math.random(8, 112), y = 0 }
if lives == 0 then change('over') end
end
end
function _draw()
cls(1)
if state == 'title' then
print('SOUND', 54, 44, 10)
print('Z: START', 48, 60, 7)
elseif state == 'playing' then
circfill(drop.x, drop.y, 3, 10)
rectfill(x - 4, y, 8, 8, 12)
rectfill(0, 116, 128, 12, 3)
print('SCORE ' .. score .. ' LIVES ' .. lives, 2, 2, 7)
print('COMBO ' .. combo .. ' X: MUSIC', 2, 10, 6)
else
print('OVER: ' .. score .. ' POINTS', 34, 50, 8)
print('Z: AGAIN', 48, 64, 7)
end
end16 · Cheat sheet: all of Lua on one page
-- comment --[[ several lines ]]
local x = 10 -- local variable (always use local)
local a, b = 1, 2 -- several at once
nil true false 3 0.5 'text' {} function() end
+ - * / // % ^ -- // integer division · % remainder
== ~= < > <= >= -- ~= is "not equal"
and or not -- only nil and false are false
'A' .. 'B' #list -- join text · length
x = x or 0 -- default value
c = alive and 11 or 8 -- choose in one line
if a then … elseif b then … else … end
for i = 1, 10 do … end for i = 10, 1, -1 do … end
for i, v in ipairs(list) do … end
for k, v in pairs(tbl) do … end
while cond do … end repeat … until cond
break goto continue … ::continue::
local function f(a, b) return a + b, a - b end
local sum, diff = f(5, 3)
local t = { 1, 2, 3 } t[1] #t -- lists start at 1
table.insert(t, v) table.remove(t, i) table.sort(t) table.concat(t, ',')
local p = { x = 1, y = 2 } p.x p['y'] -- named records
s:upper() s:lower() s:sub(1, 3) s:rep(2) s:find('a') s:gsub('a', 'o')
string.format('%03d %.1f %s', 7, 1.25, 'hi')
s:match('%d+') for w in s:gmatch('%S+') do … end
math.floor math.ceil math.abs math.min math.max math.sqrt
math.random(n) math.random(a, b) math.sin math.cos math.atan(dy, dx) math.pi
setmetatable(obj, Mold) Mold.__index = Mold obj:method()
coroutine.create(f) coroutine.resume(co) coroutine.yield()
pcall(f) error('msg') assert(cond, 'msg') type(x) tostring(x) tonumber(s)
Differences from other languages: lists start at 1 · ~= instead of != · no ++ or += ·
blocks end with end instead of braces · 0 and '' are true · variables are global unless you write local.
Chivo-8 uses Lua 5.3 (with // and goto); it doesn't include io, require or utf8.
🔤 Lua and other languages
The same game in JavaScript, Python, C#, GDScript and Fennel, with their pros and cons. In the console: LANGUAGES.
LANGUAGES 1 · Lua and javascript
- Put: in javascript. The same moving square, but in JavaScript. Chivo-8 switches to JavaScript by itself; type RUN and move it.
// The same moving square, now in JavaScript. // Chivo-8 understands both: the functions have the same names. let x = 60, y = 60; function _update() { if (btn(0)) x -= 1; // x -= 1 is x = x - 1 if (btn(1)) x += 1; if (btn(2)) y -= 1; if (btn(3)) y += 1; } function _draw() { cls(1); rectfill(x, y, 8, 8, 10); print("HELLO FROM JAVASCRIPT", 22, 4, 7); } - What changes. In JavaScript blocks go between braces { }, lines end with ;, local is written let, different is !== and lists start at 0.
- Pros. JavaScript runs in every browser: it is the language of the web. With it you build pages, apps and games that open from a link. It is one of the most used in the world.
- Cons. It has odd rules from its history: == and === are not the same, there are undefined and null, and 0 counts as false. Lua is smaller and has fewer surprises.
LANGUAGES 2 · Python
- Put: python and lua. At the top, in comments, the square in Python with Pygame. Below, the same in Lua so you can run it and compare.
-- PYTHON with Pygame: the same moving square. -- -- x, y = 60, 60 -- while True: # el ciclo del juego lo escribes tú -- teclas = pygame.key.get_pressed() -- if teclas[pygame.K_LEFT]: -- x -= 1 # los bloques van con sangría -- pantalla.fill((29, 43, 83)) -- pygame.draw.rect(pantalla, (255, 236, 39), (x, y, 8, 8)) -- pygame.display.flip() -- -- And down here, the same in Lua so you can run it: local x, y = 60, 60 function _update() if btn(0) then x = x - 1 end if btn(1) then x = x + 1 end if btn(2) then y = y - 1 end if btn(3) then y = y + 1 end end function _draw() cls(1) rectfill(x, y, 8, 8, 10) print('PYTHON: INDENT LUA: END', 14, 4, 7) end - Indentation rules. Python uses no end and no braces: the spaces at the start of the line say what is inside the if. Comments use # and lists start at 0.
- Pros. It is the most used for learning and in schools, and the favorite for artificial intelligence, data and automating tasks. It has libraries for almost everything.
- Cons. For games it is slower and does not run easily in the browser or on phones. One space too many or too few breaks the program. For games there is Pyxel, a fantasy console in Python.
LANGUAGES 3 · C# and gdscript
- Put: unity and godot. In comments: the square in C# (Unity) and in GDScript (Godot). Below, in Lua so you can run it.
-- C# in Unity: the same moving square. -- -- public class Cuadro : MonoBehaviour { -- public float velocidad = 60f; // cada variable dice su tipo -- void Update() { -- float h = Input.GetAxis("Horizontal"); -- transform.position += new Vector3(h, 0, 0) * velocidad * Time.deltaTime; -- } -- } -- -- GDSCRIPT in Godot: -- -- extends Sprite2D -- var velocidad = 60 -- func _process(delta): -- if Input.is_action_pressed("ui_left"): -- position.x -= velocidad * delta -- -- And down here, the same in Lua so you can run it: local x = 60 function _update() if btn(0) then x = x - 1 end if btn(1) then x = x + 1 end end function _draw() cls(1) rectfill(x, 60, 8, 8, 10) print('C#, GDSCRIPT AND LUA', 28, 4, 7) end - Types. In C# every variable states its type: float velocidad, int vidas, string nombre. The program checks everything before running and catches mistakes early; Lua does not.
- C# in unity. Unity makes professional 3D and mobile games, and many studios ask for C#. Downside: you write more and the engine is heavy to start with.
- Gdscript in godot. GDScript looks like Python (indentation, func) and lives in Godot, a free and open engine, great for indie 2D games. Outside Godot it is not used.
- What about delta?. Unity and Godot multiply by delta (the time of each frame) because the speed changes with the computer. Chivo-8 always runs at 30 frames per second, so you do not need it here.
LANGUAGES 4 · Fennel
- Put: in fennel. The square in Fennel. It is a TIC-80 cart: the screen is 240x136 and everything happens in TIC. Type RUN.
;; script: fennel ;; The same moving square, in Fennel: a Lisp that turns into Lua. ;; It is a TIC-80 cart: a 240x136 screen and everything happens in TIC. (var x 116) (var y 64) (fn _G.TIC [] (when (btn 2) (set x (- x 1))) ; (- x 1) es x - 1 (when (btn 3) (set x (+ x 1))) (when (btn 0) (set y (- y 1))) (when (btn 1) (set y (+ y 1))) (cls 1) (rect x y 8 8 4) (print "HELLO FROM FENNEL" 80 6 12)) - Parentheses first. Fennel is a Lisp: everything goes inside parentheses and the function comes first. (+ x 1) is x + 1 and (set x 5) is x = 5.
- It turns into lua. Before running, Fennel is translated into Lua. That is why it works wherever Lua works, like TIC-80 and Chivo-8.
- Pros and cons. Pro: very short code and macros (code that writes code). Con: so many parentheses are hard at first and few people use it.
LANGUAGES 5 · Scratch
- Put: blocks and lua. At the top, in comments, how the square looks in Scratch. Below, the same in Lua to run it.
-- SCRATCH: programs made of blocks you snap together with the mouse. -- The same moving square looks like this: -- -- al hacer clic en la bandera verde -- por siempre -- si tecla flecha derecha presionada entonces -- cambiar x por 1 -- si tecla flecha izquierda presionada entonces -- cambiar x por -1 -- -- And down here, the same in Lua so you can run it: local x = 60 function _update() if btn(1) then x = x + 1 end if btn(0) then x = x - 1 end end function _draw() cls(1) rectfill(x, 60, 8, 8, 10) print('SCRATCH: BLOCKS LUA: TEXT', 8, 4, 7) end - Blocks instead of text. Scratch was made by MIT so kids can program by dragging colored blocks, without typing. It is free at scratch.mit.edu.
- Pros. There are no typing mistakes: blocks only fit if they make sense. It is ideal for starting at age 8 and has a huge community.
- Cons. Big programs get hard to read and it is not used professionally. That is why the next step is a text language, like Lua.
LANGUAGES 6 · C
- Put: c and lua. In comments, the square in C with the raylib library. Below, in Lua to run it.
-- C: the language used to make consoles, systems and engines. -- The square in C (with the raylib library) looks like this: -- -- int x = 60; // int: número entero -- while (!WindowShouldClose()) { -- if (IsKeyDown(KEY_RIGHT)) x = x + 1; -- BeginDrawing(); -- ClearBackground(DARKBLUE); -- DrawRectangle(x, 60, 8, 8, YELLOW); -- EndDrawing(); -- } -- -- And down here, the same in Lua so you can run it: local x = 60 function _update() if btn(1) then x = x + 1 end if btn(0) then x = x - 1 end end function _draw() cls(1) rectfill(x, 60, 8, 8, 10) print('C: FAST LUA: SIMPLE', 16, 4, 7) end - The grandparent. C is from 1972. Operating systems, game engines and consoles are made with C. Lua is written in C, and so is TIC-80.
- Pros. It is one of the fastest and runs on almost any device, even a watch. You control every byte of memory.
- Cons. You manage the memory: one mistake can crash the whole program. You need much more code for the same thing as in Lua.
LANGUAGES 7 · Which one should i learn?
- Depending on your goal. Small games, Roblox and mods: Lua. Web pages and apps: JavaScript. School, AI and automation: Python. Game studios: C#. Indie games in Godot: GDScript.
- What you know carries over. Variables, if, loops, functions and lists exist in all of them. Switching languages means learning new words, not learning to think again.
- Challenge: your game in js. Challenge: write the lesson 6 game (moving around your level) in JavaScript. In Code, the menu has CODE IN JAVASCRIPT to switch.
🌐 Saving, sharing and community
On this device
- What you make is saved in the browser by itself.
SAVEplus a name names it (for exampleSAVE MYGAME);LOAD MYGAMEopens it andDIRlists yours. INFO AUTHOR YOUR NAMEandINFO DESC WHAT IT IS ABOUTadd your info to the game.EXPORTdownloads the cartridge (.json) andIMPORTopens it.EXPORT HTMLturns your game into a single file that opens without internet or can be uploaded to itch.io.
In the cloud (with an account)
- Sign in with
GOOGLEor withLOGIN YOU@EMAIL(SIGNUPcreates the account).UPLOADsaves your game to the cloud andCLOUDlists yours: they follow you to any device.
Community
PUBLISHsends your game for review (you need an account).- Once approved, it shows up in the Play LIBRARY for everyone, even without an account.
SHAREgives you a link to play it directly (it is copied for you).UNPUBLISHremoves it. If you change a game that was already approved, it goes back to review.
A game imported from someone else can only be published if its license allows it (MIT, GPL, CC…) or with its author's permission. Anyone can report a game in the library; with 3 reports it is hidden while it is reviewed.
🆘 Common errors
When something breaks, under the game screen it shows what happened, on which line, and a hint. These are the most common:
THE FUNCTION sprr DOES NOT EXIST · DID YOU MEAN spr? | The name is misspelled. Use the one it suggests or look it up in Functions. |
MISSING AN end FOR THE function ON LINE 3 | Every function, if, for and while closes with end. Check there is one for each. |
EXTRA end | There is one end too many: delete it, or check that an if or function is not missing above. |
MISSING then · MISSING do | It is written if something then ... end and for i = 1, 10 do ... end. |
vidas HAS NO VALUE (NIL) | You are using a variable that never got a number. Give it a value above or in _init(). |
e IS EMPTY (NIL) | You want to use e.x but e does not exist (for example, an enemy you already removed). |
YOU ARE JOINING TEXT (..) WITH SOMETHING EMPTY | In print('POINTS: ' .. puntos) the variable has no value. Give it one first. |
MISSING CLOSING QUOTES · MISSING A CLOSING PARENTHESIS | Every " or ' and every ( needs its pair. |
A FUNCTION CALLS ITSELF FOREVER | A function calls itself and never stops. Check it has an if to stop. |
🕹️ TIC-80 games
Chivo-8 runs TIC-80 games written in
Lua, JavaScript or Fennel: it translates their functions (TIC(),
spr with a transparent color, filled rect, btn with its numbers, pmem,
peek/poke…) into Chivo-8 ones.
- TIC-80 classics: in Play (F6) → Library. They are games with an open license, credited to their authors (
carts/CREDITOS-TIC80.txt). - IMPORT opens a TIC-80 game (
.lua,.js,.fnlor.tic). Its sprites, map and colors move into your cartridge. - Screen: TIC-80 games use 240x136. For your game choose
SCREEN 128orSCREEN 240(it is saved as-- pantalla: 240x136at the top of the code). - Differences: in TIC-80 everything happens in
TIC()(60 times per second) and the buttons are 0 up, 1 down, 2 left, 3 right. TIC-80 sound is replaced with similar tones. - Publishing: an imported game can only be published if its license allows it (MIT, GPL, CC…) or with the author's permission.
🆕 Versions
In the console: VERSION and CHANGELOG.
v0.9.5 · 2026-11-06 · beta
21 games (11 new) you can open and change, piano, controllers and a Lua guide
- Sprites: cut, copy and paste (also between carts), 3×3 tile view, line, rectangle and circle, shift the drawing with arrows, replace a color in the whole sprite and onion skin for animating
- Map: select, flip, cut, copy and paste as a stamp; random brush, automatic borders and numbered screens
- Animated tiles: consecutive sprites with flag 7 take turns by themselves on the map (water, lava, fire). If your game already used flag 7 for something else, check it
- mfind(n) / mbuscar(n): finds the markers on the map (start, enemies, coins), removes them and gives you their position
- NEW WORLD / NUEVO MUNDO: a 3-screen platformer with sprites, map and flags ready
- What the game changes with mset, sset or fset no longer stays in your cart: when you exit and on every RUN it goes back to how it was
- Sound effects and Music: major arpeggio (A), minor arpeggio (a) and drop (C) as step commands
- New lessons: LEARN 18 title screen with a story and LEARN 19 talking to characters
- Code on the phone: bottom bar to select, cut, copy and paste
- LEARN accepts just the number · KEYBOARD PHONE or CHIVO · FONT CLASSIC or ROUND · QUESTIONS opens the help page
- In Play, a small hint that you can also play in landscape
- Sound effects and Music: a 16-key piano to try each command (tap the bottom line or the P key)
- New lessons: LEARN 20 to 25 (inventory with keys and doors, enemies that chase you, a shop, saving your game, a boss with phases and a pause menu)
- LUA: a 9-part course on the language, what each thing is and what it is for (variables, if, loops, functions, tables, text and common mistakes)
- LANGUAGES: the same game in JavaScript, Python, C#, GDScript and Fennel, with their pros and cons
- Sound effects and Music: wave view (TON column or O key): live while it plays, and the shape of the chosen wave when silent
- Bluetooth or USB controllers: CONTROLLER command (which controller it sees and which player), player notice when connecting and LEARN 31 to test it
- New lessons: LEARN 26 to 30 (animation by state, several screens with doors, rain and snow, moving platforms and two players)
- LUA 10: objects with tables and metatables · LANGUAGES 5 and 6: Scratch and C
- Music: R records as you play in real time, with a metronome (on the phone, the piano + button turns into REC)
- DRUMS: 6 ready beats (rock, disco, cumbia, dembow, march and ballad) with kick and snare in the free channels
- Music: transpose (Shift + arrows or TRANSPOSE), copy and paste patterns (Ctrl+C/V or COPYPATTERN) and SWING
- The Play VIDEO now records the game's sound
- WAV: download your song (or a pattern) as an audio file, with the volume adjusted
- New lessons: LEARN 32 music for each screen (where it is saved, music, track, the mistake of putting it in _update) and LEARN 33 compose your song (melody with REC, bass, drums, transpose and WAV)
- Chivo Saltarín v2: 6 levels (cenote with holes, town with crates, night fair), map with stars, combo, ENDLESS mode and the top 5 with initials
- Kuku v2: 6 levels (market, jungle with linked cenotes, closed ruins), hot chili, combo, map with stars, ENDLESS and the top 5 with initials
- Games v2: Nave Moneda, Star Shower, Tamales Express, Pixel and the coins, Rompemuros and Glitch Maze go to 6 levels, with a level map, stars per level, a summary after each one and the top 5 with initials
- Don Chepe v2: 18 warehouses (6 per difficulty) with stars for solving them in the minimum number of moves
- Chivotchi v2: 4 mini-games to choose from (new: Jump and Memory), a high score for each and 8 medals
- New games in the library: Piñata Tower (designed by César), Tortillería (5-square falling blocks), Mouse in the Market and Cross the Street, Chito, all with levels, stars and the top 5
- IMPORT on phones: you can now pick TIC-80 games (.lua, .tic, .fnl) that used to show up grayed out; if the file is not valid, it tells you before touching your cartridge
- IMPORT also opens Chivo-8 code (.lua or .js with _update and _draw): it replaces only the code; sprites, map and sounds stay
- 7 more new games: Plague in the Cornfield, Land the Balloon, Defend the Town, Cenote Treasure (minesweeper), Lotería (match three), 2048 (based on Gabriele Cirulli’s, MIT) and Cohetones (against the computer or 2 players)
- Game title screens: text no longer spills out of its box or gets covered
- TIC-80 classics: 4 more in the library (Vogeljagd 2, Dyker, Chunky Tanks for 4 players and Stacked Tic-Tac-Toe), with credit and MIT license
- TIC-80 games: textri and ttri (textured triangles) now work, mouse() also returns scroll and string.format accepts «% d». Nibiruman is playable again (it crashed on start)
- OPEN (or the ✎ button in the Library): a Chivo-8 game goes whole into your editors, with its drawings in SPRITES; change a sprite or a number and press RUN. A note at the top of the code says where everything is
- Manual: "Lua guide", 15 chapters to learn the language in depth (structure, types, tables, text, objects, coroutines, errors, organizing a game and a cheat sheet), each with a program to copy and try
v0.9.3 · 2026-10-22 · stable
More lively sound
- Effects: GOLPE, LARGO, SUBE, BAJA or OLA envelope (bottom row of the editor)
- Square wave with 50, 25 or 12 % pulse (the NES and Game Boy timbre); tono() accepts 'p25' and 'p12' (waves 5 and 6)
- AZAR: a new effect of the chosen type (coin, jump, laser, explosion, hit, power, click or random); R key
- The SOUNDS library uses envelopes and pulses (bell, alarm, shot…)
- The classic Studio now saves effect speed
- Spanish and English: the whole console, the lessons, the templates and the manual (LANG EN / IDIOMA ES; opens in English if your browser is not in Spanish)
- Commands work with their name in both languages (LEARN = APRENDE, PUT = PONER, NEW PLATFORM = NUEVO SALTO…)
- Install it as an app from Chrome (INSTALL): it opens in its own window, and offline with the last thing you saw
- New icon: the pixel goat inside the console, drawn in Chivo-8 itself (also on the browser tab)
v0.9.2 · 2026-10-20 · stable
Your character and bigger worlds
- Lesson 16: your character (spr, palt and flipping the sprite)
- Lesson 17: a world bigger than the screen (camera)
- Each template has 3 challenges at the end of the code
- Visit and usage analytics (production only)
- The new Arcade also opens saved cartridges (?cart=) and files (?archivo=)
- Faster TIC-80 games (Wolf-80 about 2x) and a fix for the Nibiruman error (math.random with a big range)
v0.9.1 · 2026-10-20 · stable
Keyboard styles
- On-screen keyboard with 4 styles: Classic, Pink, Lavender and Neon (STYLE key, remembered in the browser)
- Text: the 240x136 screen is inspired by TIC-80
- BETA notice with a link to the regular version; the beta does not show up in search engines
- 3 more keyboard styles: Red, Yellow and Green (Game Boy shades)
- Errors explained on the game screen: what happened, on which line, and a hint (did you mean spr?)
- Game templates: NEW PLATFORM, SHIP, CATCH, MAZE or RACE
- Sound library: SOUNDS (20 ready-made effects, 5 to 24) and SONG (happy, adventure and mystery)
- Lesson 15: sound in your game (LEARN 15)
- The ⌨ button also hides the keyboard (⌨ ▼), in Chivo-8 and in TIC-80
- A more complete manual: templates, editors, the 16 colors, sound and music, saving and community, common errors
- PUBLISH sets your Google account name as author if the game has none
- Console power-on sound and cartridge sound when a game starts (also in the Arcade)
- «TAP THE SCREEN OR ENTER» screen before power-on, so the startup sound is always heard
- Arcade: «PRESS START» screen before playing, so the startup sound and music play from the beginning
- The Arcade is now the same Game Boy as Play, just for playing and with PRESS START; play links (SHARE) also wait for START
- 8 shell colors for the Play and Arcade Game Boy: tap CHIVO-8 or type SHELL
v0.9.0 · 2026-10-20 · stable
TIC-80 games and more tools
- TIC-80 classics in the library: 16 games with an open license, credited to their authors
- Runs TIC-80 games in Lua, JavaScript and Fennel (IMPORT accepts .lua, .js, .fnl and .tic)
- Optional 240x136 screen inspired by TIC-80: SCREEN 128 or SCREEN 240 command
- Player 2 on the keyboard (J L I K + U O), also in TIC-80 games
- Chivotchi renewed: pixel goat, minigames, food or candy, 3 adult forms and an album
- CRT filter with 5 styles to pick your favorite: CRT 1 to CRT 5
- Palette editable color by color (COLOR N #RRGGBB) and sprite and map banks (BANK N)
- Deeper sound: 4 drawable waves (ED) and speed per effect
- peek, poke, memcpy and memset with a memory map (MEM)
- Drawing: elli, ellib, tri, trib and spr with scale and rotation
- Map: whole-world view (WORLD or Tab)
- Code: find (Ctrl+F), go to line (Ctrl+G) and list of functions (Ctrl+O)
- EXPORT PNG and IMPORT PNG of the sprite sheet; EXPORT HTML: your game in a single file
- Physical controllers (gamepad) and mouse; video and GIF without skips
- Fix: pal() and palt() with no arguments now reset the colors
- Numbered versions: VERSION shows what is new, CHANGELOG the history, and a notice when a new version opens
- Full manual (MANUAL command): commands, keys, functions with examples and lessons
- 7 new lessons (LEARN 8 to 14): points, enemies, jumping, screens, high score, particles and TIC-80
- Fix: COLOR N #RRGGBB works now
v0.8.0 · 2026-10-19 · stable
The console is the main page
- The Console becomes the main page; the Studio stays as the classic Studio
- Community: PUBLISH sends your game for review and approved ones show up in the library
- SHARE gives a link that opens the game directly in Play
- Lessons inside the console: LEARN, NEXT, BACK and PUT
- Library in Play with the Chivo-8 games, the saved ones and the community ones
- PHOTO, GIF and VIDEO of the game; palettes (PALETTE) and cartridge info (INFO)
- Sign in with Google (GOOGLE) and save to the cloud
- Beta at /labs/chivo-8-beta/ to try things before publishing