Make 2D games in Snail with lib/game (a window, keyboard, mouse and gamepad, shapes, text, images, sound) and lib/math (Vec2, Color, Rng, Timer, springs, collision, noise), with 3D in the same window through game/scene3d and the rest of lib/engine. Use when a Snail project mounts game, math or engine, or a Snail game is asked for. Read the snail skill first for the language.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Snail Game?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/codeadopter-snail-game)
---
name: snail-game
description: Make 2D games in Snail with lib/game (a window, keyboard, mouse and gamepad, shapes, text, images, sound) and lib/math (Vec2, Color, Rng, Timer, springs, collision, noise), with 3D in the same window through game/scene3d and the rest of lib/engine. Use when a Snail project mounts game, math or engine, or a Snail game is asked for. Read the snail skill first for the language.
---
# Games in Snail
`lib/game` is a window you draw into each frame. It runs on SDL, which comes with `snailc`, on
Windows and Linux, with nothing else to install. The language itself is in `snailc guide`; to
change a game while it runs, see `snailc guide hot`.
```
snailc init --game mygame # snail.toml with libs = ["game"], and a main.snail that runs
cd mygame
snailc run # opens the window
snailc run --hot # the same, taking each saved change while it runs
```
While a `snailc run --hot` session is open, test every change in its window, in the project's own
files: save, run `snailc hot wait`, then look with `snailc hot shot` and play with
`snailc hot send "hold Right 30"`, as `snailc guide hot` tells. Do not copy the game to test it,
and do not start a second `snailc run` beside the window.
A game can play itself offscreen: `SDL_SetHint(SDL_HINT_VIDEO_DRIVER, "offscreen")` first, then
`win.take_message("hold Right 60")` plays input and `win.take_message("shot frame.png")` saves the
frame being drawn once it is drawn.
Without a window, such as on a machine with no screen or to check that a game still starts, run a
fixed number of frames: `SNAIL_GAME_FRAMES=600 snailc run` (PowerShell:
`$env:SNAIL_GAME_FRAMES=600; snailc run`). It exits 0 when nothing failed. The line
`Installed Vulkan doesn't implement the VK_EXT_headless_surface extension` is SDL's and harmless.
No input arrives in this mode and `win.dt` is real time.
## A whole game
Move with W A S D, the arrows or a gamepad; click to shoot toward the mouse; R restarts.
```snail
use game
struct Shot
pos: Vec2
vel: Vec2
life: f32 = 1.5
struct Enemy
pos: Vec2
hp: int = 2
fn main()
var win = window("Shooter", 1280, 720)
win.background = rgb(20, 24, 32)
var rng = Rng.seeded(1)
var player = win.center
var shots: [..]Shot
var enemies: [..]Enemy
var spawn = Timer.every(0.8)
var score = 0
var over = false
while win.frame()
if over
win.text_centered(340.0, "game over: {score}. R restarts")
if win.pressed(R)
enemies.clear()
shots.clear()
score = 0
over = false
continue
player += win.move * 320.0 * win.dt
if win.clicked(MouseLeft)
let aim = (win.mouse_world - player).normalized
shots.push(Shot(player, aim * 700.0))
if spawn.tick(win.dt)
enemies.push(Enemy(player + rng.direction() * 650.0))
for ref s in shots
s.pos += s.vel * win.dt
s.life -= win.dt
for ref e in enemies
e.pos = e.pos.move_toward(player, 90.0 * win.dt)
for ref s in shots
if s.life > 0.0 and s.pos.distance(e.pos) < 20.0
s.life = 0.0
e.hp -= 1
if e.pos.distance(player) < 26.0: over = true
let before = enemies.len
enemies.retain(|e| e.hp > 0)
score += before - enemies.len
shots.retain(|s| s.life > 0.0)
for e in enemies
win.circle(e.pos, 16.0, e.hp > 1 ? rgb(220, 70, 70) : rgb(255, 150, 120))
for s in shots
win.circle(s.pos, 4.0, rgb(255, 240, 160))
win.square(player, 28.0, rgb(250, 200, 60))
win.text(16.0, 16.0, "score {score} enemies {enemies.len}")
```
The shape of every lib/game program: state in `var`s of `main`, then `while win.frame()`, which
shows the last frame, clears the window, reads input and returns false once the window closes
(Escape or the close button). Each pass updates, then draws. Load images and sounds before the
loop, never inside it.
## Traps
- **Everything is `f32`.** Write `300.0`, not `300`, where an `f32` is wanted; convert with
`i as f32`. A float constant next to an `f32` stays `f32`.
- **`use game` loads all of lib/math into the one namespace.** Its names are taken: types `Vec2`,
`Vec3`, `Color`, `Rect`, `Timer`, `Rng`, `Image`, `SoundFile`, `Window`, `Input`, `Ray`, `Plane`,
`Quat`, `Mat4`, and functions `rgb`, `rgba`, `lerp`, `remap`, `sign`, `fract`, `saturate`,
`smoothstep`, `radians`, `degrees`, `move_toward`, `damp`, `spring`, `noise2`, `hash2`,
`window`. Name your own types and functions differently (`Hitbox`, `Cooldown`). Enum members
are not taken: your own `South` may sit beside the gamepad's `South`.
- **Vectors are built with their type's name.** `Vec2(1.0, 2.0)`; there is no `vec2()`.
`Vec2.splat(0.0)` and `Vec2.from_angle(a)` are the static helpers.
- **y points down**, (0, 0) is the top-left corner, angles are radians.
- **Time with `win.dt` or a `Timer`, never with frame counts.** The loop runs at the display's
refresh rate, which may be 60 or 180 frames a second.
- **Shapes are in the world, text is on the screen.** `win.camera` and `win.zoom` move shapes and
sprites, not `win.text`. Use `win.mouse_world` to aim at world positions, `win.mouse` for the
screen, and `win.text_at(pos, ...)` for text that follows a thing.
- **Removing while looping.** Mark items, then `list.retain(|x| x.alive)`; or walk backward with
an index and `swap_remove(i)`. Do not remove inside a `for` over the same list.
- **Interpolated text is fine in calls**: `win.text(16.0, 16.0, "hp {hp}")` each frame costs no
allocation.
- **Asset paths** are relative to the folder the game runs in (the project folder under
`snailc run`). A missing file stops the game with its name.
## The window and input
| Call | Gives |
|---|---|
| `window(title, w, h)` | The window, `w` by `h` drawing units, scaled when resized |
| `win.frame()` | The loop: false once the window closes, Escape is pressed or `win.quit()` was called |
| `win.dt`, `win.time`, `win.frames`, `win.fps` | Seconds since the last frame (at most 0.1), since the start; frames shown; frames a second |
| `win.width`, `win.height`, `win.size`, `win.center` | The drawing area |
| `win.background` | The color each frame starts with |
| `win.camera`, `win.zoom`, `win.look_at(p)` | The world point at the top-left, the scale, centering on `p` |
| `win.to_screen(p)`, `win.to_world(p)` | Between world and screen positions |
| `win.move` | Steering from W A S D, the arrows, the d-pad and the left stick, length at most 1 |
| `win.down(Space)`, `win.pressed(R)`, `win.released(Enter)` | A key held, just pressed, just released |
| `win.clicked(MouseLeft)`, `win.mouse_held(MouseRight)` | Mouse buttons (`MouseLeft`, `MouseMiddle`, `MouseRight`) |
| `win.mouse`, `win.mouse_world`, `win.input.wheel` | The mouse on the screen and in the world, wheel turns |
| `win.input.pad_held(South)`, `win.input.pad_pressed(Start)`, `win.input.pad_axis(RightX)`, `win.input.stick` | The first gamepad |
| `win.quit_on_escape`, `win.fullscreen_on_f11`, `win.toggle_fullscreen()` | Window behavior |
Keys: `A`..`Z`, `Num0`..`Num9`, `Space`, `Enter`, `Escape`, `Tab`, `Backspace`, `Left`, `Right`,
`Up`, `Down`, `LeftShift`, `LeftCtrl`, `F1`..`F12`.
## Drawing and sound
| Call | Draws |
|---|---|
| `win.square(center, size, c)`, `win.box(center, Vec2 size, c)` | Filled squares and rectangles, centered |
| `win.rect(x, y, w, h, c)`, `win.rect_outline(x, y, w, h, c)` | Rectangles from their top-left corner; an outline is one pixel wide |
| `win.circle(center, r, c)`, `win.circle_outline(center, r, c)` | Circles |
| `win.line(a, b, c)`, `win.thick_line(a, b, width, c)` | Lines |
| `win.triangle(a, b, c, color)`, `win.polygon([p1, p2, p3], color)` | A triangle, a convex polygon |
| `win.text(x, y, s)`, `win.text(x, y, s, c, size)` | Screen text, an 8x8 font times `size`, an `f32` (default 2.0) |
| `win.text_centered(y, s)`, `win.text_width(s)`, `win.text_at(pos, s)` | Centered text, its width, text in the world |
| `win.screen_rect(x, y, w, h, c)`, `win.screen_box(center, size, c)` | Rectangles on the screen: bars, panels |
| `let img = win.image("hero.png")`, `win.sprite(img, pos, scale, angle, flip, tint)` | PNG or BMP sprites |
| `img.cell(n, 16.0, 16.0)`, `img.part(x, y, w, h)` | Frame `n` of a sprite sheet, any part of an image |
| `let hit = win.sound("hit.wav")`, `win.play(hit)`, `win.play(hit, 0.5)` | WAV sounds, up to 16 at once |
| `win.sound_effect(Coin, 3)` | A sound effect made from numbers, no file: `Coin`, `Laser`, `Explosion`, `PowerUp`, `Hurt`, `Jump`, `Blip`; the seed varies it; `sound_recipe(kind, seed)` to change its `pitch`, `slide`, `decay`... then `win.sound_of(recipe)` |
Colors: `rgb(r, g, b)` and `rgba(r, g, b, a)` from 0 to 255, `Color.hex(0x336699)`,
`Color.rgb(1.0, 0.5, 0.0)` from 0 to 1, `c.with_alpha(0.5)`, `a.lerp(b, t)`.
## lib/math, loaded by `use game`
| Name | Use |
|---|---|
| `Vec2` | `+ - * /` with vectors or `f32`, `length`, `normalized`, `distance(o)`, `dot(o)`, `angle`, `rotated(a)`, `perp`, `lerp(o, t)`, `move_toward(target, step)`, `limited(max)`, `reflect(n)` |
| `Rng` | `Rng.seeded(1)` or a zeroed `var rng: Rng`; `float()` (0 to 1), `range(a, b)` (an `f32`), `int_range(lo, hi)` (an `int`, `hi` included), `below(n)` (a `u32` from 0 to n - 1), `chance(p)`, `direction()`, `in_circle(r)` |
| `Timer` | `Timer.every(0.5)`, then `if t.tick(win.dt)` once per interval; `t.interval = 0.3` changes it; `t.restart()` |
| Motion | `damp(x, target, halflife, dt)`, `damp2` for `Vec2`, `damp3` for `Vec3`; `spring(ref x, ref v, target, halflife, dt)`, `spring2`, `spring3`; `ease_out`, `ease_in_out`, `ease_out_back`, `ease_out_bounce` |
| Scalars | `lerp(a, b, t)`, `remap`, `saturate`, `smoothstep`, `sign`, `fract`, `wrap_angle`, `angle_diff`, `Pi`, `Tau` |
| Collision | `Rect.centered(c, size)`, `r.contains(p)` or `p in r`, `r.overlaps(o)`; `circles_overlap(a, ra, b, rb)`, `circle_overlaps_rect(c, r, rect)`, `circle_push(a, ra, b, rb)` |
| `SpatialGrid` | Many things near each other: `grid.clear()`, `grid.add(i, pos)` each frame, then `grid.query(pos, radius, &found)` or `grid.nearest(pos, radius)` |
| Noise | `noise2(x, y)`, `fbm2(x, y, octaves)` from 0 to 1 |
## Bigger games
Split a game into files with `use` lines (`use enemies` reads `enemies.snail` beside
`main.snail`) and a struct per thing, with methods: `fn update(dt: f32)` and `fn draw(win:
*Window)`. Pass the window as `&win`. Keep the frame loop in `main`, which also suits hot mode.
## 3D in the same window
`use game/scene3d` adds 3D to a lib/game window (Windows only for now): `win.scene3d()` gives a
scene that lib/engine's renderer draws in light and shadow. `scene.show()` puts its picture among
the 2D drawing at that point, so 2D drawn after it (a score, a health bar) is on top, and 2D drawn
before it is covered.
```snail
use game
use game/scene3d
fn main()
var win = window("A turning box", 1280, 720)
let scene = win.scene3d()
let box = scene.box(Vec3(1.0, 1.0, 1.0))
scene.camera.position = Vec3(0.0, 1.5, 4.0)
scene.camera.look_at(Vec3(0.0, 0.0, 0.0))
while win.frame()
scene.draw(box, Mat4.rotation(Quat.axis_angle(Vec3.up(), win.time)), rgb(230, 160, 60))
scene.show()
win.text(16.0, 16.0, "fps {win.fps:.0}")
```
| Call | Gives |
|---|---|
| `scene.box(Vec3 size)`, `scene.sphere(r)`, `scene.plane(w, d)`, `scene.cylinder(r, h)` | A mesh number to draw; `scene.mesh(&m)` for a `Mesh` built with engine/mesh |
| `scene.draw(mesh, Mat4 model, color)` | The mesh this frame, placed by `Mat4.trs(position, Quat, Vec3 scale)`, or `Mat4.translation(p)`, `Mat4.rotation(q)` and `Mat4.scaling(v)` multiplied; lit, casting and taking the sun's shadow; see-through when the color's alpha is below 1 (`rgba`) |
| `scene.sky(rgb(110, 170, 240))` | The background, shown exactly as that sRGB color (`renderer.sky` itself is linear light and comes out paler) |
| `scene.model("car.glb")` | A model number: a glTF file (`.gltf` or `.glb`, as Blender, Poly Haven and Sketchfab export them) with its meshes, PNG or JPEG textures and materials |
| `scene.draw_model(model, Mat4 place)` | The model this frame, each part placed by the file's own node tree, then by `place` |
| `scene.model_of(model)` | The `Model`: `bounds()` (an `Aabb`) to size or place it, `nodes` to move its parts, `animate(m.animation("Walk"), seconds)` to play an animation, skins and morph targets included |
| `scene.sculpted(solid)`, `scene.draw_sculpted(&model, Mat4 place)` | With `use game/sculpted`: a model made with lib/sculpt, meshed at levels of detail, drawn at the coarsest that looks the same on screen; `draw_sculpted_all(&model, places)` draws many copies |
| `scene.live_sculpted(model_fn, name: "rock")`, `scene.draw_live(&live, place)` | A sculpted model made again, meshes and collider, whenever the code changes under `--hot`; keep it in a `var`; `live.collider()` |
| `solid.collider()` | Collisions from a sculpted model's field: `place(m)`, then `distance(p)`, `normal(p)`, `ray(o, dir, reach)`, `push_out(center, radius)`; questions only read |
| `ColliderSet`: `set.add(&collider, place)` | Many props sharing colliders, asked as one: `distance`, `nearest`, `touches`, `push_out`, `ray` |
| `scene.draw_look(mesh, place, color, look)` | A plain mesh in a sculpt look: `glossy()`, `metal()`, `glow(2.0)`, patterns |
| `scene.sun(Aabb over, toward)` | A sun from `toward` with its shadow over the box `over`; a game following a player calls it each frame with a box around the player |
| `scene.camera` | `position`, `look_at(target)`, `fov_y`, `rotation` (a `Quat`) |
| `scene.renderer` | lib/engine's renderer: materials, fog (docs/engine.md); `bloom_levels = 5` makes light above `bloom_threshold` (1) glow, as a `glow(2.0)` look |
The first `scene3d()` moves the window's drawing onto a Direct3D 12 device, about a quarter second,
taking loaded images along; a 2D game that never asks for 3D keeps SDL's faster-starting renderer.
The whole of `lib/engine` (UI canvas, mixer, fixed-step clock, recording and replay) runs on the
same `Window` through its `App`: docs/engine.md in the Snail repository.