Skip to main content
Recipe number 69

Cookbook · Chapter 8 · Tables

Puzzle book: crossword, word search and maze

A crossword and a word search built as tables from lines of letters: black squares and found words are cell fills, clue numbers are superscripts.

pp. 2–3 of 5

  • Trim 210 × 210 mm
  • 1 column
  • Lexend 11.5/16
  • Chivo Mono
  • Lilita One
  • 5 pages
  • Level
  • Postext 1.57.1
  • Laid out in 84 ms
  • 249 lines of code

In short

A summer puzzle book for children aged nine to eleven, with a crossword, a word search and a maze. It shows how to build the puzzle grids from simple lines of letters.

What you'll build

A summer workbook for children of nine to eleven: a cover, three puzzles about the sea and a page of answers. Pages 2 to 5 open under a colour field with a wavy foot (sea blue, mint, coral, then yellow for the answers) and a 46 pt title in Lilita One. The code builds the crossword and the word search as tables from lines of letters and gives each its own table style: ruled squares for the crossword, pale tiles with white joints and rounded corners for the word search. The crossword's black squares and the word already found in the word search are cell fills, and the clue numbers are superscripts in the corners. The maze is an SVG drawn from a seed. The last page prints the three answers side by side from the same data, above a box on how loggerhead turtles nest.

This recipe answers

  • How do I style several tables differently (fills, zebra cells, rounded frames) in one document?
  • How do I add images and tables from code (resources) instead of Markdown ![]()?
  • How do I write superscripts, subscripts and chemical formulas without full maths?
  • How do I make inline chips: keyboard keys, tags, word banks for exercises?
  • How do I put two columns inside a box (a text column beside a figure column)?

The short answer

script.js · lines 34–60in full code
// Every grid shares tableStyle; a named style sets its size, padding, rules and fills.
// A row is as tall as its lines plus the padding and a column is its share of the
// table's width, so the padding sets how deep a square is.
const CELL = (15 * LEAD) / 9; // pt: nine squares are fifteen lines of text, 9.4 mm each
const PAD = 1; // pt: a clue number sits this close to the corner, clear of the 1 pt rule
const CLUE_FACE = (CELL - 2 * PAD) / (2 * LEAD / BODY); // 8.9 pt: two lines fill a square
const LETTER = 15; // pt: the word search's capitals
const pad = (cell, face) => pt((cell - face * LEAD / BODY) / 2); // one line fills the cell
const KEY = 54; // mm: the three answers are this deep, so their captions share a line
const key = (count) => { // count squares in KEY mm, letters of 4/3 pt per mm of square
  const side = (KEY / count) * PT_PER_MM, face = (KEY / count) * 4 / 3;
  return { id: `solucion-${count}`, bodyFontSize: pt(face), cellPadding: pad(side, face),
    borderWidth: pt(0.5) };
};
// No grid has a head row; the grey head is off for the Cookbook's default-skin check.
const tableStyle = { headerBackgroundEnabled: false, bodyFontFamily: LABEL };
const tableStyles = [
  { id: 'crucigrama', bodyFontSize: pt(CLUE_FACE), cellPadding: pt(PAD), borderWidth: pt(1) },
  { id: 'sopa', bodyFontSize: pt(LETTER), cellPadding: pad(CELL, LETTER), // same squares
    bodyBackgroundEnabled: true, bodyBackground: col('tint'), // tiles with white joints
    borderColor: col('paper'), borderWidth: pt(2.4), borderRadius: mm(4) },
  key(9), key(12), // 6 mm squares with 8 pt letters, 4.5 mm squares with 6 pt letters
];
// A table resource names its style; a cell's own background covers the style's fill.
const here = (width) => ({ position: 'here', width, align: 'center' }); // of the column
const grid = (id, typeId, model, styleId, width, extra) => ({ id, typeId, kind: 'table',
  createdAt: 0, updatedAt: 0, table: { model, styleId }, placement: here(width), ...extra });

A named table style for each grid, picked by the table's styleId

Ingredients

Type
Lexend, Lilita One, Chivo Mono (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · One table style, three looks

The code is the short answer above. tableStyle sets Chivo Mono for every grid. Each named style in tableStyles sets its own type size, padding and rules, and a table picks one with table.styleId. A column's width is its share of the table's width, but a row is as deep as its lines plus the padding, so the padding sets the depth of each square. The word search keeps the crossword's 9.41 mm square around one line of 15 pt capitals, and pad() works out the 2.9 pt that line leaves above and below it. Its rules, 2.4 pt wide and in the paper's colour, cut the pale fill into tiles, and borderRadius rounds the frame's corners to 4 mm and clips the fills to them. On the answer page key() fits nine or twelve squares into 54 mm: 6 mm squares with 8 pt letters for the crossword, 4.5 mm squares with 6 pt letters for the word search. The maze answer is drawn 54 mm square, so the three answers are equally deep and their captions share a baseline 106.4 mm from the top edge.

#2 · Nine squares, fifteen lines

script.js · lines 64–78in full code
// Two lines of CLUE_FACE (a number, an empty line) and the padding make a square.
function crossword(source, solved = false) {
  const lines = source.trim().split('\n');
  const white = (r, c) => (lines[r]?.[c] ?? '#') !== '#';
  let clue = 0;
  const rows = lines.map((line, r) => [...line].map((letter, c) => {
    if (!white(r, c)) return { content: '', background: col('ink') }; // a black square
    if (solved) return { content: letter, align: 'center' };
    // A square is numbered when a word starts in it, across or down, in reading order.
    const starts = (!white(r, c - 1) && white(r, c + 1)) || (!white(r - 1, c) && white(r + 1, c));
    const number = starts ? `**^${++clue}^**` : JOINER; // a bold superscript, or nothing
    return { content: `${number}\n${JOINER}` }; // an empty second line would add no depth
  }));
  return { rows, columnWidths: rows[0].map(() => 1) };
}

A white square holds two lines of 8.9 pt Chivo Mono (the clue number and an empty line) inside 1 pt of padding, 26.7 pt in all: 9.41 mm, a ninth of the table's width. Nine squares are 84.7 mm deep, the depth of fifteen 16 pt lines of body text, and the clue box starts on the baseline grid one line below. A square gets a number, in reading order, when an across or a down word starts in it. The number is a bold superscript of 5.2 pt (58 % of 8.9 pt) raised 3 pt (a third of 8.9 pt), which puts it in the square's top corner. The empty line is a word joiner (U+2060). A line left empty adds no depth to the cell, and the grid would come out 45.5 mm deep. A black square is an empty cell with a background of its own, linked to ink.

#3 · The code finds the words in the grid

script.js · lines 82–100in full code
const STEPS = [[0, 1], [1, 0], [1, 1], [-1, 1], [0, -1], [-1, 0], [-1, -1], [1, -1]];
function locate(letters, word) { // the squares of a word, in any of eight directions
  const hits = [];
  letters.forEach((line, r) => [...line].forEach((_, c) => STEPS.forEach(([dr, dc]) => {
    const cells = [...word].map((_, i) => ({ row: r + i * dr, col: c + i * dc }));
    if (cells.every(({ row, col: k }, i) => letters[row]?.[k] === word[i])) hits.push(cells);
  })));
  if (hits.length !== 1) throw new Error(`${word} is in the grid ${hits.length} times`);
  return hits[0];
}
function wordSearch(source, fills) { // fills: [word, palette id] pairs
  const letters = source.trim().split('\n').slice(-12);
  let model = { rows: letters.map((line) => [...line].map((content) => ({ content,
    align: 'center' }))) };
  for (const [word, fill] of fills) {
    for (const at of locate(letters, word)) model = setCellBackground(model, at, col(fill));
  }
  return model;
}

The grid is twelve lines of capitals in its own content file, after the list of words to find. locate() looks for each word in eight directions and throws unless there is exactly one match, so a typo in the grid or in the list stops the build before it prints a word nobody can find. setCellBackground returns a new table model with one more square filled. The fill is linked to a palette entry and covers the style's tile: coral for UMBRELLA on page 3, mint for all ten words on page 5. The first Variation stripes every other row from the table style (bodyAlternateBackground), and a cell's own fill covers the stripe. The word bank above the grid is two centred rows of chips: UMBRELLA's is filled coral like its squares, and the other nine are white with a navy border.

#4 · One opener, four colours

script.js · lines 104–132in full code
const BAND = 40; // mm: the colour field, from the top edge
const pin = (to, edge, x, y, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const text = (id, content, family, size, placement, extra) => ({ kind: 'text', id, content,
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', placement,
  align: placement.anchor.edge.endsWith('right') ? 'right' : 'left', ...extra });
const CAPS = { fontWeight: 700, textTransform: 'uppercase', letterSpacing: em(1 / 6) };
// The field's box sets the opener's depth: the text starts on the next grid line below.
const opener = { enabled: true, slot: { elements: [
  { kind: 'box', id: 'field', style: { backgroundColor: col('band') },
    placement: pin('page', 'top-left', 0, 0, { width: 'fill', height: mm(BAND) }) },
  { kind: 'image', id: 'surf', resourceId: 'olas', // the field's foot, cut in waves
    placement: pin('page', 'top-left', 0, BAND - 3, { width: mm(PAGE), height: mm(3.2) }) },
  text('kicker', '{attr.kicker}', LABEL, 8.5, pin('page', 'top-left', MARGIN, 11), CAPS),
  text('title', '{titleText}', DISPLAY, 46, pin('#kicker', 'below', -0.6, 0.5),
    { lineHeight: 1 }), // set solid
  text('theme', '{attr.theme}', TEXT, 10, pin('page', 'top-right', -MARGIN, 23.5), {
    fontWeight: 700, box: { backgroundColor: col('paper'), borderRadius: mm(3.5),
      padding: { top: mm(1.6), right: mm(3.2), bottom: mm(1.6), left: mm(3.2) } } }),
] } };
// parity 'any': each puzzle opens the next page. span 'page' even in one column: a design kept
// in its column is cut at the column's foot, which would trim the cover's picture.
const puzzleLevel = { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'any' },
  advancedDesign: opener };
// '# Sopa de letras {style="sopa"}': the style's palette turns 'band' mint on that page,
// in the field, the folio disc and anything else linked to it.
const BANDS = { crucigrama: 'band', sopa: 'mint', laberinto: 'coral', soluciones: 'sun' };
const puzzleStyles = Object.entries(BANDS)
  .map(([id, band]) => ({ id, palette: { band: palette[band] } }));

Pages 2 to 5 share one design. A colour field runs 40 mm down from the top edge and ends in a wavy foot drawn in the paper's colour; the kicker, the title and the theme in its white pill come from the heading line and its attributes. The field and the folio disc are linked to the palette entry band, and each page's heading style gives band its own value, so # Word Search {style="sopa"} turns both mint on page 3. Level 1 sets span: 'page' although the book has a single column: a design kept in its column is cut at the column's foot, which would end the cover's picture 16 mm short of the bottom edge. The field's box counts towards the depth the opener reserves, so the text starts on the next grid line, 44.2 mm from the top edge and 4 mm under the waves.

#5 · The answers come from the same data

script.js · lines 499–515in full code
const resourceTypes = [ // a plain resource prints no caption; an answer is numbered
  { id: 'plain', name: 'Plain', shortLabel: '', captionPrefix: '' },
  { id: 'solucion', ...t({ en: { name: 'Solution', captionPrefix: 'Solution' },
    es: { name: 'Solución', captionPrefix: 'Solución' } }), shortLabel: 'Sol.' },
].map((type) => ({ numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  ...type }));
const ANSWER_GAP = 6; // mm between the three answers: gap=6mm on their :::columns fence
const ANSWER_WIDTH = KEY / ((MEASURE - 2 * ANSWER_GAP) / 3); // 54 mm of a 55.3 mm column
const answers = [
  grid('sol-crucigrama', 'solucion', crossword(crosswordText, true), 'solucion-9', ANSWER_WIDTH,
    { caption: t({ en: 'Crossword', es: 'Crucigrama' }) }),
  grid('sol-sopa', 'solucion', wordSearch(searchText, words.map((w) => [w, 'mint'])),
    'solucion-12', ANSWER_WIDTH, { caption: t({ en: 'Word search', es: 'Sopa de letras' }) }),
  picture('sol-laberinto', 'solucion', { placement: here(ANSWER_WIDTH), caption: t({
    en: 'Maze', es: 'Laberinto' }), altText: t({ en: 'The maze and its way out to the sea',
    es: 'El laberinto y su salida al mar' }) }),
];

The answer page calls crossword() with solved and wordSearch() with all ten words, on the same content files as the puzzles, so an edit to a grid changes its answer too. The puzzles and the drawings use the type Plain, whose empty captionPrefix prints no caption for a resource with no caption text. The answers use the type Solution, numbered 1 to 3 in reading order to match the kickers Puzzle 1 to Puzzle 3. They sit in a :::columns{count=3 breaks="2,3" gap=6mm} group in the text, with no box around it (postext 1.25): breaks opens a new column at the second and third answers, and gap sets the columns 6 mm apart; each answer is 54 mm wide in a 55.3 mm column. The Did you know? box holds a group of its own, with breaks="2", to set the nest drawing beside its paragraph.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 069 · Puzzle book: crossword, word search and maze ═══════
// https://postext.dev/en/cookbook/puzzle-book
// Code: MIT · Text and puzzles: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Lexend, Lilita One, Chivo Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
  setCellBackground,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'puzzle-book';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = {
  ink: '#1f2a44', // text, grid rules and the black squares: a navy near-black
  paper: '#ffffff',
  band: '#2d9cdb', // a puzzle's colour field: sea blue until a puzzle's style replaces it
  sun: '#ffb627', coral: '#ff6f59', mint: '#5cc8a8', // the other fields; coral marks a find
  tint: '#fff1cc', // boxes and word-search tiles
  muted: '#5b6477', // running titles and the colophon
};
// Every colour is linked to its palette entry by id: a puzzle's palette recolours 'band'.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.ink })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['Lexend', 'Lilita One', 'Chivo Mono'];
const PAGE = 210, MARGIN = 16; // mm: a square booklet, the same margin on every side
const MEASURE = PAGE - 2 * MARGIN; // 178 mm
const BODY = 11.5, LEAD = 16; // pt: large, open text for young readers
const PT_PER_MM = 72 / 25.4;
const JOINER = '\u2060'; // a word joiner: a line with nothing on it that still counts

// #region answer: a named table style for each grid, picked by the table's styleId
// Every grid shares tableStyle; a named style sets its size, padding, rules and fills.
// A row is as tall as its lines plus the padding and a column is its share of the
// table's width, so the padding sets how deep a square is.
const CELL = (15 * LEAD) / 9; // pt: nine squares are fifteen lines of text, 9.4 mm each
const PAD = 1; // pt: a clue number sits this close to the corner, clear of the 1 pt rule
const CLUE_FACE = (CELL - 2 * PAD) / (2 * LEAD / BODY); // 8.9 pt: two lines fill a square
const LETTER = 15; // pt: the word search's capitals
const pad = (cell, face) => pt((cell - face * LEAD / BODY) / 2); // one line fills the cell
const KEY = 54; // mm: the three answers are this deep, so their captions share a line
const key = (count) => { // count squares in KEY mm, letters of 4/3 pt per mm of square
  const side = (KEY / count) * PT_PER_MM, face = (KEY / count) * 4 / 3;
  return { id: `solucion-${count}`, bodyFontSize: pt(face), cellPadding: pad(side, face),
    borderWidth: pt(0.5) };
};
// No grid has a head row; the grey head is off for the Cookbook's default-skin check.

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Stripe the word search's rows

A deeper yellow on every other row helps a young reader follow a line of letters. A cell's own fill covers the stripe, so UMBRELLA stays coral; the answer grid has a style of its own and takes no stripes.

     bodyBackgroundEnabled: true, bodyBackground: col('tint'), // tiles with white joints
+    bodyAlternateBackgroundEnabled: true, // a shade deeper than the tiles on every other row
+    bodyAlternateBackground: { hex: '#ffdd80', model: 'hex' },
     borderColor: col('paper'), borderWidth: pt(2.4), borderRadius: mm(4) },

#Draw a harder maze

Twenty-one by eleven squares fit the same width at 8.4 mm each, and the answer on page 5 is drawn from the new maze.

-const theMaze = maze(17, 9, 2027);
+const theMaze = maze(21, 11, 2027);

Pitfalls

  • The clue numbers in the box are typed in the content file, while the ones in the grid are computed. After you edit a grid, check the clues against it, since the code does not compare them.
  • A heading style's palette recolours design elements, text, and the rules and fills of tables, but not the inside of an SVG, so the waves at the foot of each field are drawn in the paper's colour and one drawing serves all four fields.

Credits

Text
Original prose, CC BY 4.0
Fonts
Lexend (SIL OFL 1.1) · Lilita One (SIL OFL 1.1) · Chivo Mono (SIL OFL 1.1)
Sandbox