Spielerando

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.

A pixel art desk. On the left a white sheet holds ten rows of digits and dots, in the middle a small list puts each digit beside a colour box and the dot beside a checkerboard. A light moves along the rows letter by letter, the matching entry in the list lights up, and on the right a big square of exactly that colour appears on a checkerboard, until a honey jar with a wooden lid stands there.
One letter is one pixel. Watch the light: each letter on the sheet is looked up in the list and becomes one square of that colour, in the same row and column. A dot stays see-through, so the checkerboard shows through at the corners of the jar.
The same desk. The sheet holds the jar's rows again, but one row is a letter short and another has a digit the list does not know. A light runs down the rows; at the gap at the end of the short row and around the unknown digit red boxes appear, and a red lamp shows the number 2 while the checkerboard stays empty. Then both places are filled in, their boxes turn green, the lamp turns green and the jar is drawn.
The check reads every row before it draws anything. A row that is too short and a digit with no colour are each named by row and column, so you or your AI fix exactly that one letter. Until then nothing is drawn, so a broken picture never reaches your game.

When you need it

For small sprites, icons and tiles up to about 32 by 32 pixels that your AI should draw itself, and for changing one pixel later without redoing the picture. An AI writes and reads text well, so it can count the rows, compare two frames and fix a single letter. It does not replace a painter: big, detailed pictures are still better made in an image tool or by hand.

Say this to your AI

Use the pixel art from text recipe from Spielerando. Write my sprite as rows of letters with a palette of at most 8 colours, run the check and show me its report word for word, then show me the picture scaled up 8 times so that I can judge it.

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.

/* Pixel art from text: a sprite written as rows of letters, one letter for one pixel, and a list
   that says which letter is which colour. An AI writes text well and can read it back, so it can
   count the rows, compare two frames and fix one pixel, which it cannot do with a picture it only
   described to an image tool.

   Usage:
     const palette = { k: "#1f2142", y: "#f2c14e", w: "#ffffff" };
     const result = readSprites(`
       ..kkkk..
       .kyyyyk.
       kywyywyk
       kyyyyyyk
       .kyyyyk.
       ..kkkk..
     `, palette);
     if (!result.ok) console.log(result.text);     // every problem, with its row and column
     const sprite = result.frames[0];              // { width, height, data }, four numbers a pixel

     // in a browser, on a canvas (the shape is the one a canvas uses):
     context.putImageData(new ImageData(scaleUp(sprite, 8).data, sprite.width * 8), 0, 0);
     // or as a picture that stays sharp at any size:
     const svg = spriteToSvg(sprite, 8);          // or svgShapes(sprite), to put into an SVG of your own

   A dot is a see-through pixel. An empty line starts the next frame of an animation, and every
   frame must have the size of the first. Spaces in front of and behind the rows are ignored, so the
   text can sit indented in your code; a space is never a pixel.

   What it reports, instead of drawing a broken picture: a row that is longer or shorter than the
   others, a letter the palette does not know, a colour it cannot read, a frame of another size,
   more colours than `maxColors`, a side longer than `maxSize`.

   `scaleUp` only takes whole numbers. Scaled by 2.5, some pixels come out two wide and some
   three, and the picture stops looking like pixel art.

   To go the other way, from a picture you have to text an AI can read: `paletteFrom` gives each
   colour a letter, `spriteToText` writes the rows.

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

export const DEFAULTS = {
  /** The letter for a see-through pixel. */
  transparent: ".",
  /** The most colours one sprite may use. Fewer colours hold a style together. */
  maxColors: 16,
  /** The longest side of a sprite, in pixels. */
  maxSize: 64,
};

export type SpriteSettings = 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;
}

/** One letter for one colour, written "#rgb", "#rrggbb" or, with opacity, "#rrggbbaa". */
export type Palette = Record<string, string>;

export type ProblemKind = "empty" | "ragged-row" | "unknown-letter" | "bad-color" | "bad-letter" | "frame-size" | "too-many-colors" | "too-big";

export interface Problem {
  kind: ProblemKind;
  /** Frames, rows and columns count from 1, as a person would. */
  frame?: number;
  row?: number;
  column?: number;
  message: string;
}

export interface SpriteResult {
  ok: boolean;
  /** One picture per frame. A frame with a problem is still here, with the bad pixels see-through. */
  frames: Pixels[];
  problems: Problem[];
  /** The result in words, to show as it is. */
  text: string;
}

/** A colour as four numbers from 0 to 255, or null if it is not written as a hex colour. */
export function parseColor(color: string): [number, number, number, number] | null {
  const m = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(color.trim());
  if (!m) return null;
  const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
  const part = (i: number) => parseInt(hex.slice(i, i + 2), 16);
  return [part(0), part(2), part(4), hex.length === 8 ? part(6) : 255];
}

const twoDigits = (n: number) => n.toString(16).padStart(2, "0");

/** The colour of one pixel as "#rrggbb", or "#rrggbbaa" when it is partly see-through. */
export function colorAt(pixels: Pixels, x: number, y: number): string {
  const i = (y * pixels.width + x) * 4;
  const d = pixels.data;
  return "#" + twoDigits(d[i]) + twoDigits(d[i + 1]) + twoDigits(d[i + 2]) + (d[i + 3] === 255 ? "" : twoDigits(d[i + 3]));
}

/** The text as frames of rows: no empty lines around it, no indent, no spaces at the line ends. */
function framesOf(text: string): string[][] {
  const lines = text.replace(/\r/g, "").split("\n").map((line) => line.trim());
  const frames: string[][] = [];
  let frame: string[] = [];
  for (const line of lines) {
    if (line === "") {
      if (frame.length > 0) frames.push(frame);
      frame = [];
    } else frame.push(line);
  }
  if (frame.length > 0) frames.push(frame);
  return frames;
}

/** The length most rows have, so that the one row that differs is the one named. */
function usualLength(rows: string[][]): number {
  const counts = new Map<number, number>();
  for (const row of rows) counts.set(row.length, (counts.get(row.length) ?? 0) + 1);
  let best = 0;
  for (const [length, count] of counts) if (count > (counts.get(best) ?? 0)) best = length;
  return best;
}

/** Reads one sprite, or the frames of an animation, and says what is wrong with the text. */
export function readSprites(text: string, palette: Palette, settings: SpriteSettings = {}): SpriteResult {
  const { transparent = DEFAULTS.transparent, maxColors = DEFAULTS.maxColors, maxSize = DEFAULTS.maxSize } = settings;
  const problems: Problem[] = [];
  const colors = new Map<string, [number, number, number, number]>();
  for (const [letter, color] of Object.entries(palette)) {
    if ([...letter].length !== 1 || letter.trim() === "" || letter === transparent) {
      problems.push({ kind: "bad-letter", message: `The palette names "${letter}": each colour needs exactly one letter, not a space and not the "${transparent}" of a see-through pixel.` });
      continue;
    }
    const parsed = parseColor(color);
    if (parsed) colors.set(letter, parsed);
    else problems.push({ kind: "bad-color", message: `The palette gives "${letter}" the colour "${color}", which is not a colour written like #1f2142.` });
  }

  const frames: Pixels[] = [];
  const texts = framesOf(text);
  if (texts.length === 0) problems.push({ kind: "empty", message: "There are no rows to read." });
  texts.forEach((lines, f) => {
    const rows = lines.map((line) => [...line]);
    const width = usualLength(rows);
    const height = rows.length;
    const data = new Uint8ClampedArray(width * height * 4);
    const used = new Set<string>();
    const unknown = new Set<string>();
    rows.forEach((row, y) => {
      if (row.length !== width) {
        problems.push({ kind: "ragged-row", frame: f + 1, row: y + 1, message: `Frame ${f + 1}, row ${y + 1} has ${row.length} letters, the other rows have ${width}: "${row.join("")}".` });
      }
      for (let x = 0; x < width && x < row.length; x++) {
        const letter = row[x];
        if (letter === transparent) continue;
        const color = colors.get(letter);
        if (!color) {
          // a letter the palette lists with a colour that cannot be read is reported once, above
          if (!(letter in palette) && !unknown.has(letter)) {
            unknown.add(letter);
            problems.push({ kind: "unknown-letter", frame: f + 1, row: y + 1, column: x + 1, message: `Frame ${f + 1}, row ${y + 1}, column ${x + 1}: the letter "${letter}" is not in the palette.` });
          }
          continue;
        }
        used.add(letter);
        data.set(color, (y * width + x) * 4);
      }
    });
    if (used.size > maxColors) {
      problems.push({ kind: "too-many-colors", frame: f + 1, message: `Frame ${f + 1} uses ${used.size} colours, and the limit is ${maxColors}.` });
    }
    if (width > maxSize || height > maxSize) {
      problems.push({ kind: "too-big", frame: f + 1, message: `Frame ${f + 1} is ${width} by ${height} pixels, and the longest side allowed is ${maxSize}.` });
    }
    if (f > 0 && (width !== frames[0].width || height !== frames[0].height)) {
      problems.push({ kind: "frame-size", frame: f + 1, message: `Frame ${f + 1} is ${width} by ${height} pixels, frame 1 is ${frames[0].width} by ${frames[0].height}.` });
    }
    frames.push({ width, height, data });
  });

  const size = frames.length > 0 ? `${frames.length === 1 ? "1 sprite" : `${frames.length} frames`} of ${frames[0].width} by ${frames[0].height} pixels` : "Nothing";
  const summary = problems.length === 0 ? `${size}. No problems.` : `${size}. Found ${problems.length} ${problems.length === 1 ? "problem" : "problems"}.`;
  return { ok: problems.length === 0, frames, problems, text: [summary, ...problems.map((p) => `${p.kind}: ${p.message}`)].join("\n") };
}

/** One sprite from text. It stops with every problem in the message, so a broken picture never reaches the game. */
export function readSprite(text: string, palette: Palette, settings: SpriteSettings = {}): Pixels {
  const result = readSprites(text, palette, settings);
  if (!result.ok) throw new Error(result.text);
  if (result.frames.length !== 1) throw new Error(`Expected one sprite and found ${result.frames.length} frames. Use readSprites for an animation.`);
  return result.frames[0];
}

const LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

/** A palette for a picture you already have: its colours, the most used first, each with a letter. */
export function paletteFrom(pixels: Pixels, settings: SpriteSettings = {}): Palette {
  const { transparent = DEFAULTS.transparent } = settings;
  const counts = new Map<string, number>();
  for (let y = 0; y < pixels.height; y++) {
    for (let x = 0; x < pixels.width; x++) {
      if (pixels.data[(y * pixels.width + x) * 4 + 3] === 0) continue;
      const color = colorAt(pixels, x, y);
      counts.set(color, (counts.get(color) ?? 0) + 1);
    }
  }
  const letters = [...LETTERS].filter((letter) => letter !== transparent);
  if (counts.size > letters.length) throw new Error(`The picture has ${counts.size} colours, more than the ${letters.length} letters there are. Pixel art uses a few colours; this picture is not pixel art yet.`);
  const sorted = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));
  return Object.fromEntries(sorted.map(([color], i) => [letters[i], color]));
}

/** The rows of letters for a picture. It stops at a pixel whose colour is not in the palette. */
export function spriteToText(pixels: Pixels, palette: Palette, settings: SpriteSettings = {}): string {
  const { transparent = DEFAULTS.transparent } = settings;
  const letterOf = new Map<string, string>();
  for (const [letter, color] of Object.entries(palette)) {
    const parsed = parseColor(color);
    if (parsed) letterOf.set(parsed.join(","), letter);
  }
  const rows: string[] = [];
  for (let y = 0; y < pixels.height; y++) {
    let row = "";
    for (let x = 0; x < pixels.width; x++) {
      const i = (y * pixels.width + x) * 4;
      const d = pixels.data;
      if (d[i + 3] === 0) {
        row += transparent;
        continue;
      }
      const letter = letterOf.get(`${d[i]},${d[i + 1]},${d[i + 2]},${d[i + 3]}`);
      if (letter === undefined) throw new Error(`Row ${y + 1}, column ${x + 1} has the colour ${colorAt(pixels, x, y)}, which is not in the palette.`);
      row += letter;
    }
    rows.push(row);
  }
  return rows.join("\n");
}

/** The picture with every pixel `factor` pixels wide and high. Only whole numbers keep the pixels square. */
export function scaleUp(pixels: Pixels, factor: number): Pixels {
  if (!Number.isInteger(factor) || factor < 1) throw new Error(`Scale pixel art by a whole number such as 2, 3 or 4, not by ${factor}.`);
  const width = pixels.width * factor;
  const height = pixels.height * factor;
  const data = new Uint8ClampedArray(width * height * 4);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const from = (Math.floor(y / factor) * pixels.width + Math.floor(x / factor)) * 4;
      const to = (y * width + x) * 4;
      data[to] = pixels.data[from];
      data[to + 1] = pixels.data[from + 1];
      data[to + 2] = pixels.data[from + 2];
      data[to + 3] = pixels.data[from + 3];
    }
  }
  return { width, height, data };
}

/** The picture's pixels as SVG shapes, one for each colour, to put inside an SVG of your own. */
export function svgShapes(pixels: Pixels): string {
  const runs = new Map<string, string[]>();
  for (let y = 0; y < pixels.height; y++) {
    let x = 0;
    while (x < pixels.width) {
      if (pixels.data[(y * pixels.width + x) * 4 + 3] === 0) {
        x++;
        continue;
      }
      const color = colorAt(pixels, x, y);
      let end = x + 1;
      while (end < pixels.width && pixels.data[(y * pixels.width + end) * 4 + 3] !== 0 && colorAt(pixels, end, y) === color) end++;
      // a run of one colour in a row is one box: start, across, one down, back
      if (!runs.has(color)) runs.set(color, []);
      runs.get(color)!.push(`M${x} ${y}h${end - x}v1h-${end - x}z`);
      x = end;
    }
  }
  return [...runs]
    .map(([color, boxes]) => {
      const opacity = color.length === 9 ? ` fill-opacity="${(parseInt(color.slice(7), 16) / 255).toFixed(3)}"` : "";
      return `<path fill="${color.slice(0, 7)}"${opacity} d="${boxes.join("")}"/>`;
    })
    .join("");
}

/** The picture as an SVG file. It stays sharp at any size, and `pixelSize` says how big one pixel is shown. */
export function spriteToSvg(pixels: Pixels, pixelSize = 1): string {
  const width = pixels.width * pixelSize;
  const height = pixels.height * pixelSize;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${pixels.width} ${pixels.height}" shape-rendering="crispEdges">${svgShapes(pixels)}</svg>`;
}
The tests this code passes
import assert from "node:assert/strict";
import test from "node:test";
import { DEFAULTS, type Pixels, colorAt, paletteFrom, parseColor, readSprite, readSprites, scaleUp, spriteToSvg, spriteToText, svgShapes } from "./code.ts";

const PALETTE = { k: "#1f2142", y: "#f2c14e", w: "#ffffff" };
const BEE = `
  ..kkkk..
  .kyyyyk.
  kywyywyk
  kyyyyyyk
  .kyyyyk.
  ..kkkk..
`;

const pixelAt = (p: Pixels, x: number, y: number) => [...p.data.slice((y * p.width + x) * 4, (y * p.width + x) * 4 + 4)];
const countOf = (p: Pixels, color: string) => {
  let n = 0;
  for (let y = 0; y < p.height; y++) for (let x = 0; x < p.width; x++) if (p.data[(y * p.width + x) * 4 + 3] !== 0 && colorAt(p, x, y) === color) n++;
  return n;
};

test("each letter becomes one pixel of its colour, and a dot stays see-through", () => {
  const result = readSprites(BEE, PALETTE);
  assert.equal(result.ok, true, result.text);
  assert.equal(result.text, "1 sprite of 8 by 6 pixels. No problems.");
  const [sprite] = result.frames;
  assert.equal(sprite.width, 8);
  assert.equal(sprite.height, 6);
  assert.equal(sprite.data.length, 8 * 6 * 4);
  assert.deepEqual(pixelAt(sprite, 0, 0), [0, 0, 0, 0]);
  assert.deepEqual(pixelAt(sprite, 2, 0), [0x1f, 0x21, 0x42, 255]);
  assert.deepEqual(pixelAt(sprite, 2, 2), [255, 255, 255, 255]);
  assert.deepEqual(pixelAt(sprite, 3, 3), [0xf2, 0xc1, 0x4e, 255]);
  assert.equal(countOf(sprite, "#ffffff"), 2);
  assert.equal(countOf(sprite, "#1f2142"), 16);
  assert.equal(countOf(sprite, "#f2c14e"), 18);
});

test("indent, empty lines around the picture and Windows line ends do not change it", () => {
  const plain = "..kkkk..\n.kyyyyk.\nkywyywyk\nkyyyyyyk\n.kyyyyk.\n..kkkk..";
  const windows = plain.replace(/\n/g, "\r\n");
  const a = readSprite(BEE, PALETTE);
  for (const text of [plain, windows, `\n\n\t${plain.replace(/\n/g, "\n\t")}  \n\n`]) assert.deepEqual(readSprite(text, PALETTE), a);
});

test("a row that is too short or too long is named, with its number and its letters", () => {
  const short = readSprites(BEE.replace("kywyywyk", "kywyywy"), PALETTE);
  assert.equal(short.ok, false);
  assert.deepEqual(short.problems.map((p) => [p.kind, p.frame, p.row]), [["ragged-row", 1, 3]]);
  assert.match(short.text, /row 3 has 7 letters, the other rows have 8: "kywyywy"/);
  const long = readSprites(BEE.replace(".kyyyyk.\n  ..kkkk..", ".kyyyyk..\n  ..kkkk.."), PALETTE);
  assert.deepEqual(long.problems.map((p) => [p.kind, p.row]), [["ragged-row", 5]]);
  // the picture is still there, as wide as most rows are
  assert.equal(short.frames[0].width, 8);
  assert.equal(long.frames[0].width, 8);
});

test("a letter the palette does not know is named once, where it first stands", () => {
  const result = readSprites(BEE.replace("kywyywyk", "kyxyyxyk"), PALETTE);
  assert.deepEqual(result.problems.map((p) => [p.kind, p.frame, p.row, p.column]), [["unknown-letter", 1, 3, 3]]);
  assert.match(result.text, /row 3, column 3: the letter "x" is not in the palette/);
  // its pixels stay see-through instead of getting a made-up colour
  assert.deepEqual(pixelAt(result.frames[0], 2, 2), [0, 0, 0, 0]);
  // a space inside a row is a letter the palette does not know, never a pixel
  assert.deepEqual(readSprites("kk\nk k", PALETTE).problems.map((p) => p.kind), ["ragged-row", "unknown-letter"]);
});

test("a palette that cannot be read is reported", () => {
  const colour = readSprites("kq", { k: "#1f2142", q: "dark blue" });
  assert.deepEqual(colour.problems.map((p) => p.kind), ["bad-color"]);
  assert.match(colour.text, /gives "q" the colour "dark blue"/);
  for (const letter of ["kk", " ", "."]) {
    assert.deepEqual(readSprites("k", { k: "#000", [letter]: "#fff" }).problems.map((p) => p.kind), ["bad-letter"], `"${letter}"`);
  }
});

test("colours can be written short, long or with opacity", () => {
  assert.deepEqual(parseColor("#fa0"), [255, 170, 0, 255]);
  assert.deepEqual(parseColor("#FFAA00"), [255, 170, 0, 255]);
  assert.deepEqual(parseColor("#ffaa0080"), [255, 170, 0, 128]);
  for (const bad of ["ffaa00", "#ffaa0", "red", "rgb(1,2,3)", ""]) assert.equal(parseColor(bad), null, bad);
  const glass = readSprite("g", { g: "#ffaa0080" });
  assert.deepEqual(pixelAt(glass, 0, 0), [255, 170, 0, 128]);
  assert.equal(colorAt(glass, 0, 0), "#ffaa0080");
});

test("an empty line starts the next frame, and a frame of another size is reported", () => {
  const two = readSprites("kk\nyy\n\nyy\nkk", PALETTE);
  assert.equal(two.ok, true);
  assert.equal(two.text, "2 frames of 2 by 2 pixels. No problems.");
  assert.equal(two.frames.length, 2);
  assert.equal(colorAt(two.frames[0], 0, 0), "#1f2142");
  assert.equal(colorAt(two.frames[1], 0, 0), "#f2c14e");
  const uneven = readSprites("kk\nyy\n\nyyy\nkkk\n\n\nkk\nyy\nww", PALETTE);
  assert.deepEqual(uneven.problems.map((p) => [p.kind, p.frame]), [["frame-size", 2], ["frame-size", 3]]);
  assert.match(uneven.text, /Frame 2 is 3 by 2 pixels, frame 1 is 2 by 2/);
});

test("too many colours and too big a picture are reported against the limits", () => {
  assert.equal(DEFAULTS.maxColors, 16);
  const many = Object.fromEntries([..."abcdefghijklmnopq"].map((letter, i) => [letter, "#0000" + (16 + i).toString(16)]));
  assert.deepEqual(readSprites("abcdefghijklmnopq", many).problems.map((p) => p.kind), ["too-many-colors"]);
  assert.equal(readSprites("abcdefghijklmnop", many).ok, true, "16 colours are allowed");
  assert.deepEqual(readSprites("kyw", PALETTE, { maxColors: 2 }).problems.map((p) => p.kind), ["too-many-colors"]);
  // a colour the palette lists and the picture does not use is not counted
  assert.equal(readSprites("kk", PALETTE, { maxColors: 1 }).ok, true);
  assert.deepEqual(readSprites("k".repeat(65), PALETTE).problems.map((p) => p.kind), ["too-big"]);
  assert.equal(readSprites("k".repeat(64), PALETTE).ok, true);
  assert.deepEqual(readSprites("k\nk\nk", PALETTE, { maxSize: 2 }).problems.map((p) => p.kind), ["too-big"]);
});

test("nothing to read is a problem, not an empty picture", () => {
  for (const text of ["", "\n \n\t\n"]) {
    const result = readSprites(text, PALETTE);
    assert.deepEqual(result.problems.map((p) => p.kind), ["empty"]);
    assert.equal(result.frames.length, 0);
  }
});

test("readSprite stops with every problem in its message, so a broken picture never reaches the game", () => {
  assert.throws(() => readSprite(BEE.replace("kywyywyk", "kyxyywy"), PALETTE), /ragged-row[\s\S]*unknown-letter/);
  assert.throws(() => readSprite("kk\n\nyy", PALETTE), /found 2 frames/);
});

test("the dot can be another letter", () => {
  const sprite = readSprite("_k_", PALETTE, { transparent: "_" });
  assert.deepEqual(pixelAt(sprite, 0, 0), [0, 0, 0, 0]);
  assert.deepEqual(readSprites(".k.", PALETTE, { transparent: "_" }).problems.map((p) => p.kind), ["unknown-letter"]);
});

test("a picture goes to text and back without losing a pixel", () => {
  const sprite = readSprite(BEE, PALETTE);
  const text = spriteToText(sprite, PALETTE);
  assert.equal(text, "..kkkk..\n.kyyyyk.\nkywyywyk\nkyyyyyyk\n.kyyyyk.\n..kkkk..");
  assert.deepEqual(readSprite(text, PALETTE), sprite);
});

test("a picture you already have gets a palette, the most used colour first", () => {
  const sprite = readSprite(BEE, PALETTE);
  const palette = paletteFrom(sprite);
  assert.deepEqual(palette, { a: "#f2c14e", b: "#1f2142", c: "#ffffff" });
  assert.deepEqual(readSprite(spriteToText(sprite, palette), palette), sprite);
  // a colour that is not in the palette stops the writing, with its place
  assert.throws(() => spriteToText(sprite, { k: "#1f2142", y: "#f2c14e" }), /Row 3, column 3 has the colour #ffffff/);
  // a photo is not pixel art: more colours than letters
  const noisy: Pixels = { width: 70, height: 1, data: new Uint8ClampedArray(70 * 4).map((_, i) => (i % 4 === 3 ? 255 : i)) };
  assert.throws(() => paletteFrom(noisy), /more than the 62 letters/);
});

test("scaling up by a whole number turns every pixel into a square block", () => {
  const sprite = readSprite(BEE, PALETTE);
  for (const factor of [1, 2, 3, 8]) {
    const big = scaleUp(sprite, factor);
    assert.equal(big.width, 8 * factor);
    assert.equal(big.height, 6 * factor);
    for (let y = 0; y < big.height; y++) {
      for (let x = 0; x < big.width; x++) assert.deepEqual(pixelAt(big, x, y), pixelAt(sprite, Math.floor(x / factor), Math.floor(y / factor)));
    }
    for (const color of Object.values(PALETTE)) assert.equal(countOf(big, color), countOf(sprite, color) * factor * factor);
  }
  for (const bad of [2.5, 0, -1, Number.NaN]) assert.throws(() => scaleUp(sprite, bad), /whole number/, String(bad));
});

test("the SVG paints exactly the picture's pixels, with sharp edges", () => {
  const sprite = readSprite(BEE, { ...PALETTE, w: "#ffffff80" });
  const svg = spriteToSvg(sprite, 10);
  assert.match(svg, /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg" width="80" height="60" viewBox="0 0 8 6" shape-rendering="crispEdges"><path /);
  assert.ok(svg.includes(svgShapes(sprite)), "the file holds the same shapes svgShapes gives");
  // paint the shapes back onto a picture and compare
  const back: Pixels = { width: sprite.width, height: sprite.height, data: new Uint8ClampedArray(sprite.data.length) };
  const shapes = [...svg.matchAll(/<path fill="(#[0-9a-f]{6})"(?: fill-opacity="([\d.]+)")? d="([^"]+)"\/>/g)];
  assert.equal(shapes.length, 3, "one shape for each colour");
  assert.equal(shapes.length, svg.split("<path").length - 1, "every shape is read");
  for (const [, fill, opacity, d] of shapes) {
    const color = parseColor(fill) as number[];
    const boxes = [...d.matchAll(/M(\d+) (\d+)h(\d+)v1h-(\d+)z/g)];
    assert.equal(boxes.map((b) => b[0]).join(""), d, "the shape is made of boxes one pixel high and nothing else");
    for (const [, x, y, width, back2] of boxes) {
      assert.equal(width, back2);
      for (let i = 0; i < Number(width); i++) {
        const at = (Number(y) * back.width + Number(x) + i) * 4;
        assert.equal(back.data[at + 3], 0, "no pixel is painted twice");
        back.data.set([color[0], color[1], color[2], opacity ? Math.round(Number(opacity) * 255) : 255], at);
      }
    }
  }
  assert.deepEqual(back, sprite);
  // a run of one colour is one box, so the file stays small: the top row of the bee is one box
  assert.equal([...svg.matchAll(/M\d+ 0h/g)].length, 1);
});

Common questions

can an ai draw pixel art

Yes, when it writes the picture as text. Each letter is one pixel and a short list gives every letter its colour, so the AI can read its own picture back and correct single pixels. Small sprites work best.

why does my ai pixel art look blurry

Most likely an image tool painted a soft picture that only looks like pixel art, with thousands of colours and no clean grid, or the sprite was scaled by a number that is not whole. Pixel art written as text has exactly the colours of its palette, and it is scaled by 2, 3 or 4, never by 2.5.

how do i change one pixel in a sprite my ai made

If the sprite is text, tell the AI the row, the column and the letter you want there. The check then confirms that every row still has the same length.

Was this page helpful?

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

Next step

Code recipe

Sprite sheet check

Measures a sheet of animation frames and reports what will go wrong with it in a game: a background that is painted and not see-through, frames that cannot be cut evenly, a figure cut in two, feet that are not on one line, a body that jumps sideways and a loop that jerks. Every finding names the frames and the pixel rows it is about.