---
title: "Games"
description: "Terminal apps, written in TypeScript and compiled to native executables with scriptc."
canonical_url: "https://tui-sdk.dev/docs/guides/games"
---
# Games

A game in the terminal is a grid of characters that changes many times a second. tui has the parts most games need: sprites for the things that move, a tilemap for the world, a camera that follows the player, collision against the map and between things, and a loop that runs the game at a fixed rate. They draw into the same frame as everything else, so a game can have a header, a table of scores, or a dialog over it.

[`ember.ts`](https://github.com/vercel-labs/tui/blob/main/examples/ember.ts) is a small shooter built from these parts: fly a ship through a cave, light every ember, and shoot the drones before they lunge. It plays by itself until you hold a key, and again after 12 seconds without one.

The HTML page runs [`examples/ember.ts`](https://github.com/vercel-labs/tui/blob/main/examples/ember.ts) here, in a terminal in the page.

```sh
node examples/ember.ts
```

## Sprites

A sprite is a picture of characters, with one string for each row. Each character draws as itself, or as its palette says, with another character and a style. A space is transparent, so whatever is under it shows through. A character that isn't one cell wide, such as an emoji, is left out.

```ts
import { createSprite, drawSprite, runApp } from "tui"

const ship = createSprite([" ^ ", "<r>"], {
  r: { char: "█", fg: "#ff5f5f" },
  "^": { fg: "#ffd75f" },
})

runApp({
  view: (frame) => {
    drawSprite(frame, ship, frame.rect.columns / 2 - 1, frame.rect.rows / 2)
  },
})
```

`drawSprite` puts the sprite's top left at a cell, rounded from the numbers you give it, so a thing can move in fractions of a cell. It draws only inside the rect you pass as its last argument, which is the whole frame by default. Pass the part of the screen your game is in to keep sprites out of the header.

### Pixel art

A cell holds two pixels, one above the other, when it draws `▀` in the upper pixel's color on a background of the lower's. `▄` or `▀` without a background draws one pixel and leaves the other empty.

```ts
import { createSprite, drawSprite, runApp } from "tui"

// Three pixels across and three down, in two rows of cells.
const ember = createSprite(["aca", " b "], {
  a: { char: "▄", fg: "#f5a623" },
  c: { char: "▀", fg: "#f5a623", bg: "#fff3c4" },
  b: { char: "▀", fg: "#f5a623" },
})

runApp({
  view: (frame) => {
    drawSprite(frame, ember, 2, 1)
  },
})
```

`ember.ts` draws its ship, drones, embers, and particles this way. Its `pixels` function takes a picture as rows of pixels and makes two sprites from it, the second one pixel lower. Drawing the second sprite puts a thing half a cell down, so it moves a pixel at a time in both directions.

## Tilemaps and the camera

A tilemap is the world, with one string for each row and one character for each tile. The tiles you name say how each character draws and which ones are `solid`. A character you don't name draws as itself and isn't solid. Everything outside the map counts as solid, so nothing walks off its edge.

```ts
import { createCamera, createTilemap, drawTilemap, runApp } from "tui"

const map = createTilemap(
  [
    "##################",
    "#....#...........#",
    "#....#....*......#",
    "#.........####...#",
    "##################",
  ],
  {
    "#": { char: "█", fg: "#454545", solid: true },
    ".": { char: " " },
    "*": { char: "▄", fg: "#f5a623" },
  },
)
const camera = createCamera()

runApp({
  view: (frame) => {
    camera.follow(10, 2, frame.rect.columns, frame.rect.rows, map)
    drawTilemap(frame, map, frame.rect, camera)
  },
})
```

The map's own characters can mark where things start. `map.find("@")` lists each cell that holds an `@`, from top to bottom. `map.get(x, y)` reads a tile and `map.set(x, y, ".")` changes one, so a gem the player picks up turns back into floor. `ember.ts` marks its embers and drones this way, and changes the rock tiles near an ember when the ship lights it.

A map can be bigger than the screen. `camera.follow` centers a point, usually the player, in a view of the size you give it, and keeps that view inside the map. `drawTilemap` draws what the camera sees. Draw the map first, then each sprite at `rect.x + x - camera.x` and `rect.y + y - camera.y`.

## Collision

A body is a box measured in cells: a `Rect` whose numbers can be fractions of a cell. `moveBody` moves a body across and then down, and stops it flush against any solid tile it runs into. It returns the sides it hit as `Hit`'s bits, and 0 when it hit nothing, so `hit & Hit.bottom` means the body is standing on something. It moves at most half a cell at a time, so a fast body can't pass through a thin wall.

```ts
import { createTilemap, Hit, moveBody, overlaps, touches } from "tui"

const map = createTilemap(["#######", "#..*..#", "#######"], {
  "#": { solid: true },
  ".": { char: " " },
})
const player = { x: 1, y: 1, columns: 1, rows: 1 }
const drone = { x: 5, y: 1, columns: 1, rows: 1 }

const hit = moveBody(map, player, 10, 0)
if (hit & Hit.right) {
  // Flush against the wall: player.x is 5.
}
if (touches(map, player, "*") || overlaps(player, drone)) {
  // On a gem, or caught.
}
```

`touches` says whether a box is on any tile of a given character, such as a gem or a spike. `overlaps` says whether two boxes share any area, such as the player and an enemy. Boxes that only touch at an edge don't overlap.

Give each body a `Rect` of its own, and keep its speed and other state beside it, as in `{ box, vy }`, rather than in the same object. `moveBody` changes the box you pass it, and under scriptc a bigger object passed as a `Rect` is a copy.

## A fixed step

Frames don't come at an even rate. If a game moves things by each frame's `delta`, it plays differently on a slow machine, and a jump can go through a floor after a stall. `createFixedStep` runs your game's `tick` at a fixed rate instead, 60 times a second by default. Call `update(frame)` in the view each frame. It runs as many ticks as the time since the last frame holds, and returns how far along it is to the next tick, from 0 to 1. Draw each thing at `lerp(from, to, alpha)`, between where it was at the last tick and where it is now, and motion looks smooth at any frame rate.

```ts
import { createFixedStep, createSprite, drawSprite, lerp, runApp } from "tui"

const ball = createSprite(["●"])
const state = { x: 0, from: 0, speed: 20 }

// 60 times a second, whatever the frame rate.
function tick(seconds: number) {
  state.from = state.x
  state.x += state.speed * seconds
  if (state.x > 40 || state.x < 0) {
    state.speed = -state.speed
  }
}

const fixed = createFixedStep(tick)

runApp({
  view: (frame) => {
    const alpha = fixed.update(frame)
    drawSprite(frame, ball, lerp(state.from, state.x, alpha), 1)
  },
})
```

`update` asks for the next frame, so an app without `fps` keeps drawing while the game runs. After a stall, it catches up at most 250 ms (set `most` to change that), so the game slows down for a moment instead of running hundreds of ticks at once. When a game pauses, stop calling `update`, and call `reset()` before it starts again so the paused time isn't caught up.

`ember.ts` also sets `fps: 60`, so its frames come from a timer at that rate instead of one requested after each frame.

Read the keys in the view, before `update`, with [`heldKeys`](/docs/guides/motion#animation-and-games) and `frame.held`, and keep what's held where `tick` can read it.

## Testing a game

A test app moves its clock only when you tell it to, so a game plays out the same way in every test run. `advance(ms)` runs the ticks that time holds and draws the frame. Move the clock a frame at a time, because a single `advance` catches up at most 250 ms, the same as after a stall.

```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { createFixedStep, createSprite, createTestApp, drawSprite, type Frame } from "tui"

const ball = createSprite(["●"])
const state = { x: 0 }
const fixed = createFixedStep((seconds) => {
  state.x += 10 * seconds
})

function view(frame: Frame) {
  fixed.update(frame)
  drawSprite(frame, ball, state.x, 0)
}

test("the ball moves 10 cells a second", () => {
  const app = createTestApp({ columns: 40, rows: 1, view })
  // A second, a frame at a time: one advance catches up at most 250 ms.
  for (let frame = 0; frame < 20; frame++) {
    app.advance(50)
  }
  assert.equal(app.find("●")?.x, 10)
})
```

`app.press("right")` holds a key the way a terminal without key releases does: `frame.held("right")` stays true for half a second after the press.
