File size: 12,559 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/**
 * Pattern matrix puzzle generator.
 * Generates a 3×3 grid of cells with visual attributes (shape, fill, size, rotation)
 * where each attribute follows a consistent pattern across rows and columns.
 * The bottom-right cell is hidden and the player must select the correct answer
 * from multiple choices.
 *
 * Difficulty scaling:
 *   easy:   2 attributes, simple cycles (all-same or all-different per row)
 *   medium: 3 attributes, mixed rule types
 *   hard:   4 attributes, all-different + progressive rules
 */

export type PatternDifficulty = "easy" | "medium" | "hard";

/** Visual attributes for each cell */
export type Shape = "circle" | "triangle" | "square" | "diamond" | "star" | "hexagon";
export type Fill = "solid" | "striped" | "empty";
export type Size = "small" | "medium" | "large";
export type Rotation = 0 | 45 | 90 | 135 | 180 | 225 | 270 | 315;

export interface PatternCell {
  shape: Shape;
  fill: Fill;
  size: Size;
  rotation: Rotation;
}

export interface PatternPuzzle {
  /** 3×3 grid (row-major), last cell (index 8) is the answer */
  grid: (PatternCell | null)[];
  /** The correct answer cell */
  answer: PatternCell;
  /** Multiple choice options (includes the answer) */
  choices: PatternCell[];
  /** Index of the correct choice in the choices array */
  correctIndex: number;
  /** Which attributes carry the puzzle's patterns */
  activeAttributes: string[];
  /** Difficulty level */
  difficulty: PatternDifficulty;
  /** Hint describing one of the active patterns */
  hint: string;
}

// --- Attribute value pools ---

const SHAPES: Shape[] = ["circle", "triangle", "square", "diamond", "star", "hexagon"];
const FILLS: Fill[] = ["solid", "striped", "empty"];
const SIZES: Size[] = ["small", "medium", "large"];
const ROTATIONS: Rotation[] = [0, 45, 90, 135, 180, 225, 270, 315];

// Triads: groups of 3 values used for all-different / cycling patterns
const SHAPE_TRIADS: Shape[][] = [
  ["circle", "triangle", "square"],
  ["diamond", "star", "hexagon"],
  ["circle", "diamond", "star"],
  ["triangle", "square", "hexagon"],
  ["circle", "square", "star"],
  ["triangle", "diamond", "hexagon"],
];

const FILL_TRIADS: Fill[][] = [["solid", "striped", "empty"]];

const SIZE_TRIADS: Size[][] = [["small", "medium", "large"]];

const ROTATION_TRIADS: Rotation[][] = [
  [0, 90, 180],
  [0, 45, 90],
  [45, 135, 225],
  [0, 135, 270],
];

/**
 * Rule types that define how an attribute varies across a row:
 *   - "same":      all 3 cells in a row have the same value
 *   - "cycle":     each row uses all 3 values from a triad, but in different order
 *   - "row-shift": row 0 = [a,b,c], row 1 = [b,c,a], row 2 = [c,a,b]
 */
type RuleType = "same" | "cycle" | "row-shift";

interface AttributeRule<T> {
  type: RuleType;
  /** The 3 distinct values (triad) used when type is cycle/row-shift */
  triad?: T[];
  /** The single value used when type is "same" */
  sameValue?: T;
}

// --- Random helpers ---

function randomInt(max: number): number {
  return Math.floor(Math.random() * max);
}

function pick<T>(arr: readonly T[]): T {
  return arr[randomInt(arr.length)];
}

function pickTriad<T>(triads: T[][]): T[] {
  return [...triads[randomInt(triads.length)]];
}

function shuffle<T>(arr: T[]): T[] {
  const result = [...arr];
  for (let i = result.length - 1; i > 0; i--) {
    const j = randomInt(i + 1);
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

// --- Rule application ---

/**
 * Given a rule, returns a 3×3 layout of values (row-major, 9 elements).
 */
function applyRule<T>(rule: AttributeRule<T>): T[] {
  if (rule.type === "same") {
    const v = rule.sameValue!;
    return [v, v, v, v, v, v, v, v, v];
  }

  const triad = rule.triad!;

  if (rule.type === "cycle") {
    // Each row has all 3 values in a (possibly different) permutation
    const row0 = shuffle([...triad]);
    const row1 = shuffle([...triad]);
    const row2 = shuffle([...triad]);
    return [...row0, ...row1, ...row2];
  }

  // row-shift: deterministic shifting pattern
  // row 0: [a, b, c]
  // row 1: [b, c, a]
  // row 2: [c, a, b]
  const [a, b, c] = triad;
  return [a, b, c, b, c, a, c, a, b];
}

/**
 * Pick a rule for a given attribute at a given difficulty.
 */
function pickShapeRule(difficulty: PatternDifficulty): AttributeRule<Shape> {
  const ruleTypes: RuleType[] =
    difficulty === "easy" ? ["same", "row-shift"] :
    difficulty === "medium" ? ["same", "row-shift", "cycle"] :
    ["row-shift", "cycle"];

  const type = pick(ruleTypes);
  if (type === "same") {
    return { type, sameValue: pick(SHAPES) };
  }
  return { type, triad: shuffle(pickTriad(SHAPE_TRIADS)) };
}

function pickFillRule(difficulty: PatternDifficulty): AttributeRule<Fill> {
  const ruleTypes: RuleType[] =
    difficulty === "easy" ? ["same", "row-shift"] :
    difficulty === "medium" ? ["same", "row-shift", "cycle"] :
    ["row-shift", "cycle"];

  const type = pick(ruleTypes);
  if (type === "same") {
    return { type, sameValue: pick(FILLS) };
  }
  return { type, triad: shuffle(pickTriad(FILL_TRIADS)) };
}

function pickSizeRule(difficulty: PatternDifficulty): AttributeRule<Size> {
  const ruleTypes: RuleType[] =
    difficulty === "easy" ? ["same", "row-shift"] :
    difficulty === "medium" ? ["same", "row-shift", "cycle"] :
    ["row-shift", "cycle"];

  const type = pick(ruleTypes);
  if (type === "same") {
    return { type, sameValue: pick(SIZES) };
  }
  return { type, triad: shuffle(pickTriad(SIZE_TRIADS)) };
}

function pickRotationRule(difficulty: PatternDifficulty): AttributeRule<Rotation> {
  const ruleTypes: RuleType[] =
    difficulty === "easy" ? ["same"] :
    difficulty === "medium" ? ["same", "row-shift"] :
    ["same", "row-shift", "cycle"];

  const type = pick(ruleTypes);
  if (type === "same") {
    return { type, sameValue: pick(ROTATIONS) };
  }
  return { type, triad: shuffle(pickTriad(ROTATION_TRIADS)) };
}

// --- Attribute counts by difficulty ---

const ATTR_COUNTS: Record<PatternDifficulty, number> = {
  easy: 2,
  medium: 3,
  hard: 4,
};

const ALL_ATTRIBUTES = ["shape", "fill", "size", "rotation"] as const;
type AttributeName = (typeof ALL_ATTRIBUTES)[number];

// --- Hint generation ---

const RULE_HINTS: Record<RuleType, Record<AttributeName, string>> = {
  same: {
    shape: "Each row uses the same shape.",
    fill: "Each row uses the same fill pattern.",
    size: "Each row uses the same size.",
    rotation: "Each row uses the same rotation.",
  },
  "row-shift": {
    shape: "Shapes shift position from row to row.",
    fill: "Fill patterns shift position from row to row.",
    size: "Sizes shift position from row to row.",
    rotation: "Rotations shift position from row to row.",
  },
  cycle: {
    shape: "Each row contains 3 different shapes.",
    fill: "Each row contains all 3 fill patterns.",
    size: "Each row contains all 3 sizes.",
    rotation: "Each row contains 3 different rotations.",
  },
};

// --- Distractor generation ---

/**
 * Generate plausible but wrong choices by tweaking 1-2 attributes of the answer.
 */
function generateDistractors(
  answer: PatternCell,
  grid: PatternCell[],
  count: number,
): PatternCell[] {
  const distractors: PatternCell[] = [];
  const seen = new Set<string>();
  seen.add(cellKey(answer));

  // Also avoid duplicating existing grid cells
  for (const cell of grid) {
    seen.add(cellKey(cell));
  }

  // Collect attribute values that appear in the grid for realistic distractors
  const gridShapes = [...new Set(grid.map((c) => c.shape))];
  const gridFills = [...new Set(grid.map((c) => c.fill))];
  const gridSizes = [...new Set(grid.map((c) => c.size))];
  const gridRotations = [...new Set(grid.map((c) => c.rotation))];

  let attempts = 0;
  while (distractors.length < count && attempts < 200) {
    attempts++;
    const d = { ...answer };

    // Randomly change 1-2 attributes
    const numChanges = 1 + randomInt(2);
    const attrsToChange = shuffle([...ALL_ATTRIBUTES]).slice(0, numChanges);

    for (const attr of attrsToChange) {
      switch (attr) {
        case "shape": {
          const pool = gridShapes.length > 1 ? gridShapes : SHAPES;
          d.shape = pick(pool.filter((s) => s !== answer.shape));
          if (d.shape === undefined) d.shape = pick(SHAPES.filter((s) => s !== answer.shape));
          break;
        }
        case "fill": {
          const pool = gridFills.length > 1 ? gridFills : FILLS;
          d.fill = pick(pool.filter((f) => f !== answer.fill));
          if (d.fill === undefined) d.fill = pick(FILLS.filter((f) => f !== answer.fill));
          break;
        }
        case "size": {
          const pool = gridSizes.length > 1 ? gridSizes : SIZES;
          d.size = pick(pool.filter((s) => s !== answer.size));
          if (d.size === undefined) d.size = pick(SIZES.filter((s) => s !== answer.size));
          break;
        }
        case "rotation": {
          const pool = gridRotations.length > 1 ? gridRotations : ROTATIONS;
          d.rotation = pick(pool.filter((r) => r !== answer.rotation));
          if (d.rotation === undefined) d.rotation = pick(ROTATIONS.filter((r) => r !== answer.rotation));
          break;
        }
      }
    }

    const key = cellKey(d);
    if (!seen.has(key)) {
      seen.add(key);
      distractors.push(d);
    }
  }

  return distractors;
}

function cellKey(cell: PatternCell): string {
  return `${cell.shape}-${cell.fill}-${cell.size}-${cell.rotation}`;
}

// --- Main generator ---

/**
 * Generate a pattern matrix puzzle.
 */
export function generatePattern(difficulty: PatternDifficulty): PatternPuzzle {
  const attrCount = ATTR_COUNTS[difficulty];
  const activeAttrs = shuffle([...ALL_ATTRIBUTES]).slice(0, attrCount);

  // Generate rules for each active attribute
  const rules: Partial<Record<AttributeName, AttributeRule<unknown>>> = {};
  for (const attr of activeAttrs) {
    switch (attr) {
      case "shape":
        rules.shape = pickShapeRule(difficulty);
        break;
      case "fill":
        rules.fill = pickFillRule(difficulty);
        break;
      case "size":
        rules.size = pickSizeRule(difficulty);
        break;
      case "rotation":
        rules.rotation = pickRotationRule(difficulty);
        break;
    }
  }

  // Apply rules to generate the 9-cell grid
  const shapeValues = rules.shape
    ? applyRule(rules.shape as AttributeRule<Shape>)
    : Array(9).fill(pick(SHAPES)) as Shape[];
  const fillValues = rules.fill
    ? applyRule(rules.fill as AttributeRule<Fill>)
    : Array(9).fill(pick(FILLS)) as Fill[];
  const sizeValues = rules.size
    ? applyRule(rules.size as AttributeRule<Size>)
    : Array(9).fill(pick(SIZES)) as Size[];
  const rotationValues = rules.rotation
    ? applyRule(rules.rotation as AttributeRule<Rotation>)
    : Array(9).fill(0 as Rotation) as Rotation[];

  const fullGrid: PatternCell[] = [];
  for (let i = 0; i < 9; i++) {
    fullGrid.push({
      shape: shapeValues[i],
      fill: fillValues[i],
      size: sizeValues[i],
      rotation: rotationValues[i],
    });
  }

  const answer = fullGrid[8];

  // Build the displayed grid with the last cell hidden
  const displayGrid: (PatternCell | null)[] = fullGrid.map((cell, i) =>
    i === 8 ? null : cell,
  );

  // Generate choices: answer + 5 distractors (6 total), shuffled
  const numChoices = difficulty === "easy" ? 4 : difficulty === "medium" ? 5 : 6;
  const distractors = generateDistractors(answer, fullGrid.slice(0, 8), numChoices - 1);
  const choices = shuffle([answer, ...distractors]);
  const correctIndex = choices.findIndex((c) => cellKey(c) === cellKey(answer));

  // Generate hint from a random active attribute's rule
  const hintAttr = pick(activeAttrs);
  const hintRule = rules[hintAttr]!;
  const hint = RULE_HINTS[hintRule.type as RuleType]?.[hintAttr] ?? "Look for patterns across rows.";

  return {
    grid: displayGrid,
    answer,
    choices,
    correctIndex,
    activeAttributes: [...activeAttrs],
    difficulty,
    hint,
  };
}

/**
 * Validate if the selected choice matches the answer.
 */
export function validatePattern(selected: PatternCell, answer: PatternCell): boolean {
  return cellKey(selected) === cellKey(answer);
}

/**
 * Score a pattern puzzle attempt. Returns 0 or 1 (binary — either correct or not).
 */
export function scorePattern(selected: PatternCell, answer: PatternCell): number {
  return validatePattern(selected, answer) ? 1.0 : 0.0;
}

/**
 * Serialize a PatternCell for comparison.
 */
export { cellKey };