跳到主要内容
食谱编号69

排版食谱 · 第8章 · 表

益智游戏书:填字、找词和迷宫

由一行行字母生成表格,做出填字游戏和找词游戏:黑格和已找到的词用单元格填色,线索编号用上标。

第2–3页,共5页

  • 西班牙文样例:尚无中文版本
  • 成品尺寸210 × 210 mm
  • 1栏
  • Lexend 11.5/16
  • Chivo Mono
  • Lilita One
  • 5页
  • 难度
  • Postext 1.57.1
  • 排版用时67 ms
  • 249行代码

简单来说

一本给九到十一岁孩子的暑期游戏书,有填字游戏、找词游戏和迷宫。示例演示怎样用几行字母生成游戏方格。

成品一览

一本给九到十一岁孩子的暑假作业:一个封面、三个关于大海的谜题和一页答案。第2到第5页都在一块底边呈波浪形的色块下开始(依次为海蓝、薄荷绿、珊瑚色,答案页为黄色),标题用46 pt的Lilita One。代码由一行行字母生成填字游戏和找词游戏的表格,并给每个表格一套自己的表格样式:填字游戏用带格线的方格,找词游戏用淡色方砖,白色砖缝,四角为圆角。填字游戏的黑格和找词游戏中已找到的词都是单元格填色,线索编号是角上的上标。迷宫是由种子绘制的SVG。最后一页用同一份数据并排印出三个答案,下面是一个讲红海龟如何筑巢的框。

这道食谱解答

  • 怎样在一份文档里给几张表设不同的样式(填色、斑马纹单元格、圆角边框)?
  • 怎样用代码(资源)而不是Markdown的![]()添加图片和表格?
  • 不用完整的数学公式,怎样写上标、下标和化学式?
  • 怎样做行内标签:键盘按键、标签、练习用的词库?
  • 怎样在框里分两栏(文字栏旁边是图栏)?

简短回答

script.js · 第34–60行在完整代码中
// 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 });

用料

类型
Lexend, Lilita One, Chivo Mono(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 一个表格样式,三种外观

代码见上文的简短回答。tableStyle为所有网格设定Chivo Mono。tableStyles中的每个命名样式各自设定字号、内边距和格线,表格用table.styleId选用其中一个。一列的宽度是它在表格宽度中所占的份额,而一行的高度是其中文字行的总高再加上内边距,所以内边距决定了每个方格的高度。找词游戏沿用填字游戏9.41 mm的方格,里面是一行15 pt的大写字母,pad()算出这一行上下各剩2.9 pt。它的格线宽2.4 pt,用纸张的颜色,把淡色底切成一块块方砖;borderRadius把边框四角做成4 mm圆角,并把填色裁切到圆角内。在答案页上,key()把九个或十二个方格排进54 mm:填字游戏是6 mm方格配8 pt字母,找词游戏是4.5 mm方格配6 pt字母。迷宫答案画成54 mm见方,所以三个答案一样高,它们的题注共用一条距上边缘106.4 mm的基线。

#2 · 九个方格,十五行

script.js · 第64–78行在完整代码中
// 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) };
}

一个白格在1 pt内边距内容纳两行8.9 pt的Chivo Mono(线索编号和一个空行),合计26.7 pt,即9.41 mm,是表格宽度的九分之一。九个方格高84.7 mm,等于十五行16 pt正文的高度,线索框从下一行的基线网格开始。只要有横向或纵向的单词从某个方格开始,这个方格就按阅读顺序得到一个编号。编号是5.2 pt的粗体上标(8.9 pt的58 %),上移3 pt(8.9 pt的三分之一),落在方格的上角。空行是一个单词连接符(U+2060)。真正留空的一行不会给单元格增加高度,网格就只有45.5 mm高。黑格是一个带有自己background的空单元格,关联到ink。

#3 · 由代码在网格中找词

script.js · 第82–100行在完整代码中
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;
}

网格是单独内容文件中的十二行大写字母,排在待找单词列表之后。locate()在八个方向上查找每个单词,匹配不是恰好一处就抛出异常,所以网格或列表中的错字会在印出一个谁也找不到的单词之前中止构建。setCellBackground返回一个新的表格模型,多填一个方格。填色关联到调色板中的一项,覆盖样式的方砖:第3页上UMBRELLA用珊瑚色,第5页上全部十个单词用薄荷绿。第一个变化用表格样式的bodyAlternateBackground给隔行加底色,单元格自己的填色会盖住这层底色。方阵上方的词库是两行居中的标签:UMBRELLA的标签与它的方格一样填成珊瑚色,其余九个是白底海军蓝边框。

#4 · 一个章首页设计,四种颜色

script.js · 第104–132行在完整代码中
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] } }));

第2到第5页共用一个设计。色块从上边缘向下40 mm,末端是一道用纸张颜色画的波浪形底边;眉题、标题和白色胶囊里的主题取自标题行及其属性。色块和页码圆片都关联到调色板中的band,每页的标题样式给band一个自己的值,所以# Word Search {style="sopa"}让第3页上的两者都变成薄荷绿。虽然这本书只有一栏,一级标题仍设了span: 'page':留在栏内的设计会在栏底被裁掉,那样封面的图画就会在离下边缘16 mm处被切断。色块的框计入章首页预留的高度,所以正文从下一条网格线开始,距上边缘44.2 mm,在波浪下方4 mm。

#5 · 答案来自同一份数据

script.js · 第499–515行在完整代码中
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' }) }),
];

答案页用solved调用crossword(),用全部十个单词调用wordSearch(),所用的内容文件与谜题相同,所以改动一个网格,它的答案也随之改变。谜题和插图使用Plain类型,它的captionPrefix为空,对没有题注文字的资源不印题注。答案使用Solution类型,按阅读顺序编号为1到3,与眉题Puzzle 1到Puzzle 3对应。它们放在正文中的:::columns{count=3 breaks="2,3" gap=6mm}组里,外面不套框(postext 1.25):breaks在第二个和第三个答案处另起一栏,gap让各栏相隔6 mm;每个答案宽54 mm,所在栏宽55.3 mm。Did you know?框里也有一个这样的组,以breaks="2"把巢穴剖面图排在它的段落旁边。

完整食谱

沙盒
// ═══ 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 = 'es'; // @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.

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#给找词方阵加隔行底色

每隔一行用深一点的黄色,能帮小读者顺着一行字母看下去。单元格自己的填色会盖住隔行底色,所以UMBRELLA仍是珊瑚色;答案网格用的是另一个样式,不加隔行底色。

     bodyBackgroundEnabled: true, bodyBackground: col('tint'), // tiles with white joints
+    bodyAlternateBackgroundEnabled: true, // 每隔一行,比方砖深一个色阶
+    bodyAlternateBackground: { hex: '#ffdd80', model: 'hex' },
     borderColor: col('paper'), borderWidth: pt(2.4), borderRadius: mm(4) },

#画一个更难的迷宫

二十一乘十一个方格,每格8.4 mm,放得进同样的宽度;第5页的答案也按新迷宫绘制。

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

常见问题

  • 框里的线索编号是在内容文件中手写的,而网格中的编号是计算出来的。改动网格后,请对照检查线索,因为代码不会比较两者。
  • 标题样式的调色板会给设计元素、文字以及表格的格线和填色重新着色,但不会改变SVG内部的颜色,所以每个色块底部的波浪用纸张颜色绘制,一幅图就能用于全部四个色块。

致谢

文本
原创文字, CC BY 4.0
字体
Lexend (SIL OFL 1.1) · Lilita One (SIL OFL 1.1) · Chivo Mono (SIL OFL 1.1)
沙盒