本文へスキップ
レシピ番号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行

かんたんな説明

9〜11歳の子ども向けの夏休みのパズルブックで、クロスワード、単語探し、迷路が入っています。簡単な文字の並びからパズルのマス目を作る方法を示します。

できあがり

9〜11歳の子ども向けの夏休みのドリルです。表紙、海をテーマにした3つのパズル、解答のページで構成されます。2〜5ページは、下端が波形の色面(海の青、ミント、サンゴ色、解答は黄色)と、Lilita Oneの46 ptの題で始まります。コードはクロスワードと単語探しを文字の行から表として組み、それぞれに独自の表スタイルを与えます。クロスワードは罫で区切ったマス、単語探しは白い目地と角丸の淡いタイルです。クロスワードの黒マスと、単語探しですでに見つけた単語はセルの塗りで、カギの番号は隅の上付き文字です。迷路はシードから描くSVGです。最後のページは同じデータから3つの解答を横に並べて印刷し、その下にアカウミガメの産卵についての囲みを置きます。

このレシピが答える質問

  • 1つの文書の中で、複数の表を異なるスタイル(塗り、縞模様のセル、角丸の枠)にするには?
  • 画像や表を、Markdownの![]()ではなくコードから(リソースとして)追加するには?
  • 数式を使わずに、上付き文字、下付き文字、化学式を書くには?
  • キーボードのキー、タグ、練習問題の語群などのインラインのチップを作るには?
  • 囲みの中を2段にするには(本文の段と図の段を並べる)?

手短な答え

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 · 1つの表スタイルから3つの見た目

コードは上の手短な答えにあります。tableStyleはすべてのマス目にChivo Monoを設定します。tableStylesの名前付きスタイルは、それぞれ独自の文字サイズ、内側余白、罫を設定し、表はtable.styleIdでその1つを選びます。列の幅は表の幅に対する割合で決まりますが、行の深さは行数に内側余白を加えた値なので、各マスの深さを決めるのは内側余白です。単語探しは、15 ptの大文字1行のまわりにクロスワードと同じ9.41 mmのマスを保ちます。pad()はその1行の上下に残る2.9 ptを割り出します。紙の色をした幅2.4 ptの罫が淡い塗りをタイルに切り分け、borderRadiusが枠の角を4 mmの角丸にして、塗りもそこで切り取ります。解答ページではkey()が9マスまたは12マスを54 mmに収めます。クロスワードは6 mmのマスに8 ptの文字、単語探しは4.5 mmのマスに6 ptの文字です。迷路の解答も54 mm四方で描くので、3つの解答は深さがそろい、キャプションは上端から106.4 mmの同じベースラインに並びます。

#2 · 9マスで15行

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) };
}

白マスには8.9 ptのChivo Monoで2行(カギの番号と空の行)が1 ptの内側余白の中に入り、合計26.7 ptになります。9.41 mm、表の幅の9分の1です。9マスで84.7 mmの深さになり、16 ptの本文15行分に相当するので、カギの囲みは1行下のベースライングリッドから始まります。横か縦の単語が始まるマスには、読む順に番号が振られます。番号は5.2 pt(8.9 ptの58 %)の太字の上付きで、3 pt(8.9 ptの3分の1)持ち上げてあり、マスの上の隅に収まります。空の行はワードジョイナー(U+2060)です。何も置かない行はセルの高さに数えられず、マス目の深さが45.5 mmになってしまいます。黒マスは、inkにリンクした独自のbackgroundを指定した空のセルです。

#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;
}

マス目は、探す単語の一覧のあとに、専用の原稿ファイルの中で大文字12行として書かれています。locate()は各単語を8方向に探し、一致がちょうど1つでなければ例外を投げます。そのため、マス目か一覧に打ち間違いがあれば、誰にも見つけられない単語を印刷する前にビルドが止まります。setCellBackgroundは、塗ったマスを1つ増やした新しい表モデルを返します。塗りはパレットの項目にリンクし、スタイルのタイルを覆います。3ページではUMBRELLAがサンゴ色、5ページでは10語すべてがミントです。最初のアレンジでは、表スタイルのbodyAlternateBackgroundで1行おきに色を敷きます。セル自身の塗りはその縞の上に重なります。マス目の上の単語一覧は、中央にそろえた2行のチップです。UMBRELLAのチップはそのマスと同じサンゴ色で塗られ、ほかの9つは白地に紺の枠です。

#4 · 扉は1つ、色は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ページは1つのデザインを共有します。色面は上端から40 mm下まで伸び、紙の色で描いた波形の下端で終わります。肩書き、題、白い楕円の中のテーマは、見出しの行とその属性から取ります。色面とノンブルの円はパレット項目bandにリンクしていて、各ページの見出しスタイルがbandに独自の値を与えるので、# Word Search {style="sopa"}は3ページで両方をミントにします。この本は1段組みですが、レベル1には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' }) }),
];

解答ページは、パズルと同じ原稿ファイルに対してcrossword()をsolved付きで、wordSearch()を10語すべてで呼び出します。そのためマス目を編集すれば解答も変わります。パズルと図は種類Plainを使い、その空のcaptionPrefixのおかげで、キャプションのテキストがないリソースにはキャプションが印刷されません。解答は種類Solutionを使い、肩書きPuzzle 1〜Puzzle 3に合わせて読む順に1〜3の番号が振られます。解答は本文中の:::columns{count=3 breaks="2,3" gap=6mm}グループに入っていて、囲みで包んでいません(postext 1.25)。breaksが2つ目と3つ目の解答で新しい段を始め、gapが段の間隔を6 mmにします。各解答は55.3 mmの段の中で幅54 mmです。囲みDid you know?は自分のグループを作り、breaks="2"で巣の図を段落の横に置いています。

レシピの全体

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 = '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上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#単語探しの行を縞にする

1行おきに濃い黄色を敷くと、子どもが文字の行を目で追いやすくなります。セル自身の塗りが縞の上に重なるので、UMBRELLAはサンゴ色のままです。解答のマス目は別のスタイルなので、縞は付きません。

     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) },

#もっと難しい迷路を描く

21×11マスなら、1マス8.4 mmで同じ幅に収まります。5ページの解答も新しい迷路から描かれます。

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

よくあるつまずき

  • 囲みの中のカギの番号は原稿ファイルに手で書いたもので、マス目の中の番号は計算で求めたものです。コードは両者を照合しないので、マス目を編集したらカギと突き合わせて確かめてください。
  • 見出しスタイルのパレットはデザイン要素、テキスト、表の罫と塗りの色を変えますが、SVGの中身は変えません。そのため各色面の下端の波は紙の色で描き、1つの図を4つの色面で使い回しています。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Lexend (SIL OFL 1.1) · Lilita One (SIL OFL 1.1) · Chivo Mono (SIL OFL 1.1)
Sandbox