RotNot / src /lib /puzzles /patterns.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
12.6 kB
/**
* 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 };