Spielerando

Sprite stack

Builds a figure from layers drawn as seen from above and piles them up, so that it looks like the figure seen from a slanted camera. Turn the layers and the same drawings show the figure from any side, in pictures that all have one size and all match.

A grassy floor seen from above. Flat slices drop onto a shadow one after another, boots first, then legs, a cream jacket, a light blue veil with two dark eyes and a honey coloured hat, until they make the beekeeper. Then she turns once all the way round, and each time she has turned an eighth, a small copy of her facing that way appears in a grid of eight boxes beside her. At the end the pile sinks away, slice by slice.
The figure is only flat drawings seen from above, piled one pixel higher each. Turn the drawings and the pile turns, so all eight directions on the right come from the same few drawings and match without being drawn again. Watch her stand still on her shadow while she turns.

When you need it

For games seen from above in which a character, a vehicle or a prop must face 8 or 16 directions. Directions drawn one by one have to be made to match by hand, and here every direction comes from the same layers. It suits chunky shapes best. Fine details seen from the side, such as a face in profile, are not what it draws.

Say this to your AI

Use the sprite stack recipe from Spielerando with the pixel art from text recipe. Write my figure as layers from the feet up, each as rows of letters, run the stack check and show me its report, then show me the figure from 8 directions in one row.

The button copies this text together with the tested code below, so your AI has everything.

Settings

The code

Tested TypeScript with no outside parts. Copy it into your game, or hand it to your AI together with the text above.

/* Sprite stack: a figure drawn as layers, like slices of it seen from above, from the feet up. The
   code turns every layer and piles them, each a pixel higher than the one below, and the pile looks
   like the figure seen from a slanted camera. Turn the layers by another angle and the figure
   faces another way, so one set of drawings gives every direction, and they all match.

   Usage:
     const layers = thicken([boots, legs, body, head, hat], [2, 3, 5, 3, 2]);   // 15 layers
     const report = checkStack(layers);                 // says what is wrong with the layers
     const picture = renderStack(layers, 45);           // the figure turned 45 degrees clockwise
     const frames = turnaround(layers);                 // 8 pictures, one for each direction
     // frames[0] is as drawn, frames[2] a quarter turn clockwise, frames[4] seen from behind
     const stand = groundPoint(layers);                 // where the figure stands, in every picture

   A layer is { width, height, data } with four numbers a pixel (red, green, blue, opacity), the
   shape a canvas uses. All layers have one size, and the first is the lowest. What is at the
   bottom of a layer's drawing is the side of the figure that faces the viewer at angle 0.
   `thicken` repeats layers, so that legs drawn once can be three layers high.

   What you see of a layer is mostly its front edge, one pixel high, because the layer above
   covers the rest. So a face is not drawn on one layer: it is the front pixels of the head's
   layers, one row from each.

   Every picture has the same size whatever the angle, and the figure turns around the middle of
   its layers. A layer with an odd width and height has one pixel exactly in the middle, and that
   pixel does not move at all, so the figure does not wobble while it turns. `groundPoint` says
   where that middle is in the pictures. Put the figure into your game by that point. Its lowest
   pixel is not the same row in every direction, because feet that are wider than deep come
   closer to the viewer when the figure turns sideways.

   Slanted angles are read from each layer drawn nine times as big with its stairs smoothed, which
   keeps round shapes round. Quarter turns are exact.

   SPDX-License-Identifier: MIT
   Copyright (c) 2026 Spielerando, https://spielerando.com */

export const DEFAULTS = {
  /** How many directions a turnaround has: 8 gives one every 45 degrees. */
  directions: 8,
  /** How many pixels each layer is drawn above the one below. Less makes the figure flatter, as if seen from higher up. */
  lift: 1,
  /** The colour of a one-pixel line around the finished figure, or "none". */
  outline: "none",
};

export type StackSettings = Partial<typeof DEFAULTS>;

/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
  width: number;
  height: number;
  data: Uint8ClampedArray;
}

export interface StackProblem {
  kind: "no-layers" | "layer-size" | "empty-layer" | "not-square" | "even-size";
  /** The layer it is about, counting from 1 at the bottom. */
  layer?: number;
  message: string;
}

export interface StackReport {
  /** True when the layers can be piled. A note about wobble does not make it false. */
  ok: boolean;
  problems: StackProblem[];
  text: string;
}

const blank = (width: number, height: number): Pixels => ({ width, height, data: new Uint8ClampedArray(width * height * 4) });

function copyPixel(from: Pixels, fx: number, fy: number, to: Pixels, tx: number, ty: number): void {
  const a = (fy * from.width + fx) * 4;
  const b = (ty * to.width + tx) * 4;
  to.data[b] = from.data[a];
  to.data[b + 1] = from.data[a + 1];
  to.data[b + 2] = from.data[a + 2];
  to.data[b + 3] = from.data[a + 3];
}

/** Each layer repeated: `thicken([legs, body], [3, 5])` is three layers of legs under five of body. */
export function thicken(layers: Pixels[], counts: number[]): Pixels[] {
  if (layers.length !== counts.length) throw new Error(`There are ${layers.length} layers and ${counts.length} counts: give one count for each layer.`);
  const out: Pixels[] = [];
  layers.forEach((layer, i) => {
    if (!Number.isInteger(counts[i]) || counts[i] < 0) throw new Error(`Layer ${i + 1} is to be repeated ${counts[i]} times: a count is a whole number, 0 or more.`);
    for (let n = 0; n < counts[i]; n++) out.push(layer);
  });
  return out;
}

/** Says what is wrong with the layers before anything is drawn. */
export function checkStack(layers: Pixels[]): StackReport {
  const problems: StackProblem[] = [];
  if (layers.length === 0) problems.push({ kind: "no-layers", message: "There are no layers to pile." });
  layers.forEach((layer, i) => {
    if (layer.width !== layers[0].width || layer.height !== layers[0].height) {
      problems.push({ kind: "layer-size", layer: i + 1, message: `Layer ${i + 1} is ${layer.width} by ${layer.height} pixels, layer 1 is ${layers[0].width} by ${layers[0].height}. Layers of different sizes do not sit on top of each other.` });
    }
    let drawn = false;
    for (let p = 3; p < layer.data.length; p += 4) if (layer.data[p] !== 0) drawn = true;
    if (!drawn) problems.push({ kind: "empty-layer", layer: i + 1, message: `Layer ${i + 1} has nothing drawn on it: the figure has a gap there, one pixel high.` });
  });
  const stopping = problems.length;
  if (layers.length > 0 && layers[0].width !== layers[0].height) {
    problems.push({ kind: "not-square", message: `The layers are ${layers[0].width} by ${layers[0].height} pixels. It works, but square layers are easier to think about when the figure turns.` });
  } else if (layers.length > 0 && layers[0].width % 2 === 0) {
    problems.push({ kind: "even-size", message: `The layers are ${layers[0].width} pixels wide, an even number, so no pixel is exactly in the middle and the figure shifts by up to a pixel as it turns. An odd size such as ${layers[0].width + 1} turns around one pixel that stays put.` });
  }
  const blocking = problems.slice(0, stopping).filter((p) => p.kind !== "empty-layer");
  const head = layers.length === 0 ? "No layers." : `${layers.length} ${layers.length === 1 ? "layer" : "layers"} of ${layers[0].width} by ${layers[0].height} pixels.`;
  const summary = problems.length === 0 ? "No problems." : `Found ${problems.length} ${problems.length === 1 ? "thing" : "things"} to look at.`;
  return { ok: blocking.length === 0, problems, text: [`${head} ${summary}`, ...problems.map((p) => `${p.kind}: ${p.message}`)].join("\n") };
}

/** The side of the square a layer of this size is turned on: room for every angle. */
export function roomFor(width: number, height: number): number {
  let side = 2 * Math.ceil(Math.hypot(width, height) / 2 + 1);
  if ((side - width) % 2 !== 0) side++;
  return side;
}

function quarterTurn(square: Pixels, turns: number): Pixels {
  const n = ((turns % 4) + 4) % 4;
  const side = square.width;
  const out = blank(side, side);
  for (let y = 0; y < side; y++) {
    for (let x = 0; x < side; x++) {
      if (n === 0) copyPixel(square, x, y, out, x, y);
      else if (n === 1) copyPixel(square, x, y, out, side - 1 - y, x);
      else if (n === 2) copyPixel(square, x, y, out, side - 1 - x, side - 1 - y);
      else copyPixel(square, x, y, out, y, side - 1 - x);
    }
  }
  return out;
}

/** The picture three times as big, with its stairs smoothed and every pixel's own colour kept in the middle of its block. */
function triple(pixels: Pixels): Pixels {
  const { width, height } = pixels;
  const out = blank(width * 3, height * 3);
  const key = (x: number, y: number) => {
    if (x < 0 || y < 0 || x >= width || y >= height) return 0;
    const i = (y * width + x) * 4;
    return pixels.data[i + 3] === 0 ? 0 : pixels.data[i] * 16777216 + pixels.data[i + 1] * 65536 + pixels.data[i + 2] * 256 + pixels.data[i + 3];
  };
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const a = key(x - 1, y - 1);
      const b = key(x, y - 1);
      const c = key(x + 1, y - 1);
      const d = key(x - 1, y);
      const e = key(x, y);
      const f = key(x + 1, y);
      const g = key(x - 1, y + 1);
      const h = key(x, y + 1);
      const i = key(x + 1, y + 1);
      const from: [number, number][] = Array.from({ length: 9 }, () => [0, 0]);
      if (b !== h && d !== f) {
        if (d === b) from[0] = [-1, 0];
        if ((d === b && e !== c) || (b === f && e !== a)) from[1] = [0, -1];
        if (b === f) from[2] = [1, 0];
        if ((d === b && e !== g) || (d === h && e !== a)) from[3] = [-1, 0];
        if ((b === f && e !== i) || (h === f && e !== c)) from[5] = [1, 0];
        if (d === h) from[6] = [-1, 0];
        if ((d === h && e !== i) || (h === f && e !== g)) from[7] = [0, 1];
        if (h === f) from[8] = [1, 0];
      }
      for (let n = 0; n < 9; n++) {
        const sx = x + from[n][0];
        const sy = y + from[n][1];
        if (sx < 0 || sy < 0 || sx >= width || sy >= height) continue;
        copyPixel(pixels, sx, sy, out, x * 3 + (n % 3), y * 3 + Math.floor(n / 3));
      }
    }
  }
  return out;
}

/** One layer turned clockwise, on its square with room. */
function turnLayer(layer: Pixels, degrees: number): Pixels {
  const side = roomFor(layer.width, layer.height);
  const left = (side - layer.width) / 2;
  const top = Math.floor((side - layer.height) / 2);
  const placed = blank(side, side);
  for (let y = 0; y < layer.height; y++) for (let x = 0; x < layer.width; x++) copyPixel(layer, x, y, placed, left + x, top + y);
  const turns = Math.sign(degrees) * Math.floor(Math.abs(degrees) / 90 + 0.5);
  const rest = degrees - turns * 90;
  const square = quarterTurn(placed, turns);
  if (rest === 0) return square;
  const big = triple(triple(square));
  const middle = (side - 1) / 2;
  const angle = (rest * Math.PI) / 180;
  const cos = Math.cos(angle);
  const sin = Math.sin(angle);
  const out = blank(side, side);
  for (let y = 0; y < side; y++) {
    for (let x = 0; x < side; x++) {
      const fx = Math.floor((middle + (x - middle) * cos + (y - middle) * sin + 0.5) * 9);
      const fy = Math.floor((middle - (x - middle) * sin + (y - middle) * cos + 0.5) * 9);
      if (fx >= 0 && fy >= 0 && fx < big.width && fy < big.height) copyPixel(big, fx, fy, out, x, y);
    }
  }
  return out;
}

function parseHex(color: string): [number, number, number, number] {
  const m = /^#([0-9a-f]{6})$/i.exec(color.trim());
  if (!m) throw new Error(`The outline colour "${color}" is not a colour written like #1f2142, and not "none".`);
  return [parseInt(m[1].slice(0, 2), 16), parseInt(m[1].slice(2, 4), 16), parseInt(m[1].slice(4, 6), 16), 255];
}

/** The size of every picture the stack gives, whatever the angle. */
export function pictureSize(layers: Pixels[], settings: StackSettings = {}): { width: number; height: number } {
  const { lift = DEFAULTS.lift } = settings;
  if (layers.length === 0) throw new Error("There are no layers to pile.");
  const side = roomFor(layers[0].width, layers[0].height);
  // one clear pixel all around, which is also where an outline goes
  return { width: side + 2, height: side + Math.round((layers.length - 1) * lift) + 2 };
}

/** Where the middle of the lowest layer is in every picture: the point the figure stands on and turns around.
    Place the figure in your game by this point, not by its lowest pixel, which changes with the direction. */
export function groundPoint(layers: Pixels[], settings: StackSettings = {}): { x: number; y: number } {
  const { width, height } = pictureSize(layers, settings);
  const side = width - 2;
  return { x: 1 + (side - 1) / 2, y: height - 1 - side + (side - 1) / 2 };
}

/** The figure turned clockwise by any angle: every layer turned, then piled from the lowest up. */
export function renderStack(layers: Pixels[], degrees: number, settings: StackSettings = {}): Pixels {
  const { lift = DEFAULTS.lift, outline = DEFAULTS.outline } = settings;
  if (!Number.isFinite(degrees)) throw new Error(`An angle has to be a number of degrees, not ${degrees}.`);
  if (!(lift > 0)) throw new Error(`Each layer has to be lifted by more than 0 pixels, not ${lift}.`);
  const report = checkStack(layers);
  if (!report.ok) throw new Error(report.text);
  const { width, height } = pictureSize(layers, settings);
  const side = width - 2;
  const out = blank(width, height);
  layers.forEach((layer, i) => {
    const turned = turnLayer(layer, degrees);
    const top = height - 1 - side - Math.round(i * lift);
    for (let y = 0; y < side; y++) {
      for (let x = 0; x < side; x++) {
        if (turned.data[(y * side + x) * 4 + 3] !== 0) copyPixel(turned, x, y, out, x + 1, top + y);
      }
    }
  });
  if (outline === "none") return out;
  const line = parseHex(outline);
  const drawn = (x: number, y: number) => x >= 0 && y >= 0 && x < width && y < height && out.data[(y * width + x) * 4 + 3] !== 0;
  const edge: number[] = [];
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      if (!drawn(x, y) && (drawn(x + 1, y) || drawn(x - 1, y) || drawn(x, y + 1) || drawn(x, y - 1))) edge.push((y * width + x) * 4);
    }
  }
  for (const at of edge) out.data.set(line, at);
  return out;
}

/** The figure from every direction, clockwise, all pictures one size. */
export function turnaround(layers: Pixels[], settings: StackSettings = {}): Pixels[] {
  const { directions = DEFAULTS.directions } = settings;
  if (!Number.isInteger(directions) || directions < 1) throw new Error(`A turnaround has a whole number of directions, at least 1, not ${directions}.`);
  return Array.from({ length: directions }, (_, i) => renderStack(layers, (i * 360) / directions, settings));
}
The tests this code passes
import assert from "node:assert/strict";
import test from "node:test";
import { DEFAULTS, type Pixels, checkStack, groundPoint, pictureSize, renderStack, roomFor, thicken, turnaround } from "./code.ts";

const COLORS: Record<string, number[]> = { r: [0xc2, 0x41, 0x2d, 255], b: [0x2f, 0x62, 0xf0, 255], y: [0xf2, 0xc1, 0x4e, 255], k: [0x1f, 0x21, 0x42, 255] };

/** A layer from rows of letters; a dot is see-through. */
function draw(rows: string[]): Pixels {
  const width = rows[0].length;
  const data = new Uint8ClampedArray(width * rows.length * 4);
  rows.forEach((row, y) => [...row].forEach((letter, x) => letter !== "." && data.set(COLORS[letter], (y * width + x) * 4)));
  return { width, height: rows.length, data };
}

const at = (p: Pixels, x: number, y: number) => {
  const i = (y * p.width + x) * 4;
  return p.data[i + 3] === 0 ? "." : Object.keys(COLORS).find((key) => COLORS[key].join() === [...p.data.slice(i, i + 4)].join()) ?? "?";
};
/** The picture as rows of letters, to compare against by eye. */
const show = (p: Pixels) => Array.from({ length: p.height }, (_, y) => Array.from({ length: p.width }, (_, x) => at(p, x, y)).join(""));
const places = (p: Pixels, letter: string) => show(p).flatMap((row, y) => [...row].flatMap((l, x) => (l === letter ? [[x, y]] : [])));

const RED = draw(["rrr", "rrr", "rrr"]);
const BLUE = draw(["bbb", "bbb", "bbb"]);
/** A body with a yellow mark on the side that faces the viewer. */
const BODY = draw([".....", ".bbb.", ".bbb.", ".bbb.", "..y.."]);

test("layers are piled from the lowest up, each a pixel higher, and the upper covers the lower", () => {
  // a 3 by 3 layer turns on a square of 9, and the picture has one clear pixel all around
  assert.equal(roomFor(3, 3), 9);
  assert.deepEqual(pictureSize([RED, BLUE]), { width: 11, height: 12 });
  assert.deepEqual(show(renderStack([RED, BLUE], 0)), [
    "...........",
    "...........",
    "...........",
    "...........",
    "....bbb....",
    "....bbb....",
    "....bbb....",
    "....rrr....",
    "...........",
    "...........",
    "...........",
    "...........",
  ]);
  // lifted two pixels a layer, two rows of the lower layer show
  assert.deepEqual(pictureSize([RED, BLUE], { lift: 2 }), { width: 11, height: 13 });
  assert.deepEqual(show(renderStack([RED, BLUE], 0, { lift: 2 })).slice(4, 10), ["....bbb....", "....bbb....", "....bbb....", "....rrr....", "....rrr....", "..........."]);
  // lifted half a pixel, every second layer sits on the same row as the one below
  assert.deepEqual(pictureSize([RED, BLUE, RED, BLUE], { lift: 0.5 }), { width: 11, height: 13 });
});

test("the side drawn at the bottom faces the viewer, and turning clockwise shows the others in turn", () => {
  const layers = [BODY, BODY];
  const middle = (pictureSize(layers).width - 1) / 2;
  const marks = (degrees: number) => places(renderStack(layers, degrees), "y");
  // at 0 the mark is below the body; only the lower layer's mark shows, and the upper one above it
  assert.ok(marks(0).every(([x]) => x === middle));
  assert.equal(marks(0).length, 2);
  // a quarter turn clockwise brings it to the left, half a turn hides it behind the body
  assert.ok(marks(90).every(([x]) => x < middle));
  assert.ok(marks(270).every(([x]) => x > middle));
  const blueRows = (degrees: number) => places(renderStack(layers, degrees), "b").map(([, y]) => y);
  // from the front the lower mark is the lowest thing drawn
  assert.ok(Math.max(...marks(0).map(([, y]) => y)) > Math.max(...blueRows(0)));
  // from behind the lower layer's mark is covered by the upper body, and the upper one sits on top of everything
  assert.equal(marks(180).length, 1);
  assert.ok(marks(180)[0][1] < Math.min(...blueRows(180)));
});

test("every direction gives a picture of the same size, and a full turn comes back to the start", () => {
  const layers = thicken([BODY, RED_ON_5(), BODY], [2, 3, 1]);
  const size = pictureSize(layers);
  for (let degrees = 0; degrees <= 360; degrees += 5) {
    const picture = renderStack(layers, degrees);
    assert.deepEqual({ width: picture.width, height: picture.height }, size, `${degrees} degrees`);
  }
  assert.deepEqual(renderStack(layers, 360), renderStack(layers, 0));
  assert.deepEqual(renderStack(layers, -90), renderStack(layers, 270));
  assert.equal(DEFAULTS.directions, 8);
  const frames = turnaround(layers);
  assert.equal(frames.length, 8);
  frames.forEach((frame, i) => assert.deepEqual(frame, renderStack(layers, i * 45), `direction ${i + 1}`));
  assert.equal(turnaround(layers, { directions: 16 }).length, 16);
  assert.deepEqual(turnaround(layers, { directions: 4 }), [frames[0], frames[2], frames[4], frames[6]]);
});

function RED_ON_5(): Pixels {
  return draw([".....", ".rrr.", ".rrr.", ".rrr.", "....."]);
}

test("a layer with an odd size turns around one pixel that never moves", () => {
  const dot = draw([".....", ".....", "..k..", ".....", "....."]);
  const still = renderStack([dot, dot, dot], 0);
  assert.deepEqual(places(still, "k").map(([x]) => x), [6, 6, 6], "three layers, one above the other");
  for (let degrees = 1; degrees < 360; degrees++) assert.deepEqual(renderStack([dot, dot, dot], degrees), still, `${degrees} degrees`);
  // groundPoint names that pixel: the lowest layer's dot is there, and the ones above it straight above
  assert.deepEqual(groundPoint([dot, dot, dot]), { x: 6, y: 8 });
  assert.deepEqual(places(still, "k"), [[6, 6], [6, 7], [6, 8]]);
  assert.deepEqual(groundPoint([dot, dot, dot], { lift: 2 }), { x: 6, y: 10 });
  // with an even size no pixel is in the middle: a pixel next to it moves on a quarter turn
  const even = draw(["....", ".k..", "....", "...."]);
  assert.notDeepEqual(renderStack([even], 90), renderStack([even], 0));
  assert.match(checkStack([even]).text, /an even number, so no pixel is exactly in the middle/);
  assert.equal(checkStack([even]).ok, true, "it is a note, the stack still works");
});

test("quarter turns are exact, and no angle makes up a colour", () => {
  const layers = [BODY, RED_ON_5(), BODY];
  const quarter = (p: Pixels) => draw(Array.from({ length: p.width }, (_, y) => Array.from({ length: p.height }, (_, x) => at(p, y, p.height - 1 - x)).join("")));
  assert.deepEqual(show(quarter(BODY)), [".....", ".bbb.", "ybbb.", ".bbb.", "....."]);
  assert.deepEqual(renderStack(layers, 90), renderStack(layers.map(quarter), 0));
  assert.deepEqual(renderStack(layers, 180), renderStack(layers.map(quarter).map(quarter), 0));
  for (let degrees = 0; degrees < 360; degrees += 3) assert.ok(!show(renderStack(layers, degrees)).join("").includes("?"), `${degrees} degrees`);
});

test("a filled square layer keeps close to its size at every angle", () => {
  const square: Pixels = { width: 11, height: 11, data: new Uint8ClampedArray(11 * 11 * 4).fill(255) };
  for (let degrees = 0; degrees < 360; degrees++) {
    const picture = renderStack([square], degrees);
    let drawn = 0;
    for (let i = 3; i < picture.data.length; i += 4) if (picture.data[i] !== 0) drawn++;
    assert.ok(drawn >= 113 && drawn <= 125, `${degrees} degrees: ${drawn} pixels of 121`);
  }
});

test("the outline is one pixel of its colour around the figure, and changes nothing inside", () => {
  const plain = renderStack([RED, BLUE], 0);
  const lined = renderStack([RED, BLUE], 0, { outline: "#1f2142" });
  assert.deepEqual(show(lined).slice(3, 9), ["....kkk....", "...kbbbk...", "...kbbbk...", "...kbbbk...", "...krrrk...", "....kkk...."]);
  for (let y = 0; y < plain.height; y++) for (let x = 0; x < plain.width; x++) if (at(plain, x, y) !== ".") assert.equal(at(lined, x, y), at(plain, x, y));
  // one pixel alone gets its four neighbours
  assert.equal(places(renderStack([draw(["r"])], 0, { outline: "#1f2142" }), "k").length, 4);
  // there is room for it at every angle: no outline pixel is missing at the picture's edge
  const layers = thicken([draw(["rrrrr", "rrrrr", "rrrrr", "rrrrr", "rrrrr"])], [6]);
  for (let degrees = 0; degrees < 360; degrees += 5) {
    const picture = renderStack(layers, degrees);
    for (let x = 0; x < picture.width; x++) assert.equal(at(picture, x, 0) + at(picture, x, picture.height - 1), "..", `${degrees} degrees`);
    for (let y = 0; y < picture.height; y++) assert.equal(at(picture, 0, y) + at(picture, picture.width - 1, y), "..", `${degrees} degrees`);
  }
  assert.throws(() => renderStack([RED], 0, { outline: "dark" }), /not a colour written like #1f2142/);
});

test("thicken repeats each layer as often as its count says", () => {
  assert.deepEqual(thicken([RED, BLUE], [2, 3]), [RED, RED, BLUE, BLUE, BLUE]);
  assert.deepEqual(thicken([RED, BLUE], [0, 1]), [BLUE]);
  assert.throws(() => thicken([RED, BLUE], [2]), /2 layers and 1 counts/);
  assert.throws(() => thicken([RED], [1.5]), /whole number/);
});

test("planted: layers of different sizes, an empty layer and no layers are reported", () => {
  const good = checkStack([RED, BLUE]);
  assert.deepEqual([good.ok, good.text], [true, "2 layers of 3 by 3 pixels. No problems."]);
  const sizes = checkStack([RED, draw(["bbbb", "bbbb", "bbbb"]), BLUE]);
  assert.equal(sizes.ok, false);
  assert.deepEqual(sizes.problems.map((p) => [p.kind, p.layer]), [["layer-size", 2]]);
  assert.match(sizes.text, /Layer 2 is 4 by 3 pixels, layer 1 is 3 by 3/);
  assert.throws(() => renderStack([RED, draw(["bbbb", "bbbb", "bbbb"])], 0), /Layer 2 is 4 by 3 pixels/);
  const gap = checkStack([RED, draw(["...", "...", "..."]), BLUE]);
  assert.deepEqual(gap.problems.map((p) => [p.kind, p.layer]), [["empty-layer", 2]]);
  assert.equal(gap.ok, true, "a gap can be drawn, it is only reported");
  const none = checkStack([]);
  assert.deepEqual([none.ok, none.problems.map((p) => p.kind)], [false, ["no-layers"]]);
  assert.throws(() => renderStack([], 0), /no layers/);
  assert.match(checkStack([draw(["rrr", "rrr"])]).text, /not-square: The layers are 3 by 2 pixels/);
});

test("what is not an angle, a lift or a count of directions is refused", () => {
  assert.throws(() => renderStack([RED], Number.NaN), /number of degrees/);
  assert.throws(() => renderStack([RED], 0, { lift: 0 }), /more than 0 pixels/);
  assert.throws(() => renderStack([RED], 0, { lift: -1 }), /more than 0 pixels/);
  for (const directions of [0, 2.5]) assert.throws(() => turnaround([RED], { directions }), /whole number of directions/);
});

Common questions

how do i make a character face 8 directions

Draw it once as layers seen from above, from the feet up, and let code turn and pile the layers for each direction. Every direction then shows the same figure, because it is the same drawing.

what is sprite stacking

A way to fake a solid object with flat pictures. The object is cut into thin slices, each slice is a small picture seen from above, and the slices are drawn one above the other, each a pixel higher.

why does my stacked sprite wobble when it turns

It is turning around a point that is not a pixel. Give the layers an odd width and height, so that one pixel is exactly in the middle, and place the figure in the game by that point.

Was this page helpful?

One click, no account. It shows us which pages help.

Next step

Code recipe

Pixel art from text

Turns a sprite written as rows of letters into real pixels: one letter is one pixel, and a short list says which letter is which colour. Before it draws anything it reports a row that is too short, a letter with no colour and a frame of another size, each with its row and column.