GameOverlays

This commit is contained in:
2025-10-15 21:21:45 +01:00
parent 800d9d083f
commit 73ce666f53
10 changed files with 611 additions and 119 deletions
+176 -20
View File
@@ -1,4 +1,4 @@
import { useState, useCallback } from "react";
import { useState, useCallback, useMemo } from "react";
import { sudoku } from "../lib/Sudoku";
import type { UseCursorType } from "./useCursor";
@@ -8,40 +8,190 @@ export function useBoardState(cursorManager: UseCursorType) {
const [initialBoard, setInitialBoard] = useState<string>(board);
const [solution, setSolution] = useState<string | null>(null);
const setDigit = useCallback(
(d: string) => {
const i = cursor.r * 9 + cursor.c;
const arr = board.split("");
arr[i] = d;
setBoard(arr.join(""));
},
[cursor, board]
);
const givenCells = () => {
const cells = new Set<number>();
for (let i = 0; i < initialBoard.length; i++) {
if (initialBoard[i] !== ".") {
cells.add(i);
}
}
return cells;
};
const canEditCell = (row: number, col: number): boolean => {
const index = row * 9 + col;
return !givenCells().has(index);
};
const isValidPlacement = (testBoard: string, row: number, col: number, digit: string): boolean => {
if (digit === ".") return true;
const idx = row * 9 + col;
for (let c = 0; c < 9; c++) {
const checkIdx = row * 9 + c;
if (c !== col && testBoard[checkIdx] === digit) {
return false;
}
}
for (let r = 0; r < 9; r++) {
const checkIdx = r * 9 + col;
if (r !== row && testBoard[checkIdx] === digit) {
return false;
}
}
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let r = boxRow; r < boxRow + 3; r++) {
for (let c = boxCol; c < boxCol + 3; c++) {
const checkIdx = r * 9 + c;
if ((r !== row || c !== col) && testBoard[checkIdx] === digit) {
return false;
}
}
}
return true;
};
const getConflicts = (testBoard: string, row: number, col: number): number[] => {
const conflicts: number[] = [];
const digit = testBoard[row * 9 + col];
if (digit === ".") return conflicts;
for (let c = 0; c < 9; c++) {
if (c !== col && testBoard[row * 9 + c] === digit) {
conflicts.push(row * 9 + c);
}
}
for (let r = 0; r < 9; r++) {
if (r !== row && testBoard[r * 9 + col] === digit) {
conflicts.push(r * 9 + col);
}
}
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let r = boxRow; r < boxRow + 3; r++) {
for (let c = boxCol; c < boxCol + 3; c++) {
if ((r !== row || c !== col) && testBoard[r * 9 + c] === digit) {
const idx = r * 9 + c;
if (!conflicts.includes(idx)) {
conflicts.push(idx);
}
}
}
}
return conflicts;
};
const isFullyValid = (testBoard: string): boolean => {
for (let r = 0; r < 9; r++) {
let rowSum = 0;
for (let c = 0; c < 9; c++) {
const digit = testBoard[r * 9 + c];
if (digit === ".") return false;
rowSum += parseInt(digit, 10);
}
if (rowSum !== 45) return false;
}
for (let c = 0; c < 9; c++) {
let colSum = 0;
for (let r = 0; r < 9; r++) {
const digit = testBoard[r * 9 + c];
colSum += parseInt(digit, 10);
}
if (colSum !== 45) return false;
}
for (let boxRow = 0; boxRow < 3; boxRow++) {
for (let boxCol = 0; boxCol < 3; boxCol++) {
let boxSum = 0;
for (let r = boxRow * 3; r < boxRow * 3 + 3; r++) {
for (let c = boxCol * 3; c < boxCol * 3 + 3; c++) {
const digit = testBoard[r * 9 + c];
boxSum += parseInt(digit, 10);
}
}
if (boxSum !== 45) return false;
}
}
return true;
};
const isComplete = (testBoard: string): boolean => {
return !testBoard.includes(".");
};
const setDigit = (d: string) => {
const i = cursor.r * 9 + cursor.c;
if (!canEditCell(cursor.r, cursor.c)) {
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return false;
}
const arr = board.split("");
arr[i] = d;
const newBoard = arr.join("");
if (!isValidPlacement(newBoard, cursor.r, cursor.c, d)) {
const conflicts = getConflicts(newBoard, cursor.r, cursor.c);
window.dispatchEvent(
new CustomEvent("sudoku-invalid-move", {
detail: { row: cursor.r, col: cursor.c, digit: d, conflicts },
})
);
return false;
}
setBoard(newBoard);
window.dispatchEvent(
new CustomEvent("sudoku-valid-move", {
detail: { row: cursor.r, col: cursor.c, digit: d },
})
);
return true;
};
const erase = () => {
if (!canEditCell(cursor.r, cursor.c)) {
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return false;
}
const erase = useCallback(() => {
const i = cursor.r * 9 + cursor.c;
const arr = board.split("");
arr[i] = ".";
setBoard(arr.join(""));
}, [cursor, board]);
return true;
};
const reset = useCallback(() => {
const newBoard = sudoku.generate("medium");
const reset = () => {
const newBoard = sudoku.generate("easy");
setBoard(newBoard);
setInitialBoard(newBoard);
setSolution(null);
setCursor({ r: 0, c: 0 });
}, [setCursor]);
};
const solveBoard = useCallback(() => {
const solved = sudoku.solve(board);
const solveBoard = () => {
const solved = sudoku.solve(initialBoard);
if (solved) {
setSolution(solved);
setBoard(solved);
window.dispatchEvent(new CustomEvent("sudoku-game-won"));
}
}, [board]);
};
const boardToString = useCallback((human: boolean = false) => {
const boardToString = (human: boolean = false) => {
// Computer-optimized: compact 81-character string
if (!human) {
return board;
@@ -60,7 +210,7 @@ export function useBoardState(cursorManager: UseCursorType) {
if (r === 2 || r === 5) result += "------+-------+------\n";
}
return result;
}, [board]);
};
return {
board,
@@ -71,6 +221,12 @@ export function useBoardState(cursorManager: UseCursorType) {
reset,
solveBoard,
boardToString,
canEditCell,
isValidPlacement,
getConflicts,
isFullyValid,
isComplete,
givenCells,
};
}
+54 -2
View File
@@ -30,6 +30,40 @@ export function useCursor(rendererManager: UseRenderer) {
setTimeout(() => el.classList.remove("locked-cell"), 300);
}, [cursor, getCellEl]);
const flashValid = useCallback(() => {
const el = getCellEl(cursor.r, cursor.c);
if (!el) return;
el.classList.add("valid-move");
setTimeout(() => el.classList.remove("valid-move"), 300);
}, [cursor, getCellEl]);
const highlightConflicts = useCallback((conflictIndices: number[]) => {
const container = containerRef.current;
if (!container) return;
const sudokuDiv = container.querySelector("#sudoku");
if (!sudokuDiv) return;
conflictIndices.forEach((idx) => {
const r = Math.floor(idx / 9);
const c = idx % 9;
const el = getCellEl(r, c);
if (el) {
el.classList.add("conflict");
}
});
setTimeout(() => {
conflictIndices.forEach((idx) => {
const r = Math.floor(idx / 9);
const c = idx % 9;
const el = getCellEl(r, c);
if (el) {
el.classList.remove("conflict");
}
});
}, 2000);
}, [containerRef, getCellEl]);
const moveCursor = useCallback(
(dr: number, dc: number, steps = 1) => {
if (animatingRef.current) return;
@@ -54,9 +88,25 @@ export function useCursor(rendererManager: UseRenderer) {
useEffect(() => {
const onLockedCell = () => flashLocked();
const onValidMove = () => flashValid();
const onInvalidMove = (e: Event) => {
const detail = (e as CustomEvent).detail;
if (detail?.conflicts) {
highlightConflicts(detail.conflicts);
}
flashInvalid();
};
window.addEventListener("sudoku-locked-cell", onLockedCell);
return () => window.removeEventListener("sudoku-locked-cell", onLockedCell);
}, [flashLocked]);
window.addEventListener("sudoku-valid-move", onValidMove);
window.addEventListener("sudoku-invalid-move", onInvalidMove as EventListener);
return () => {
window.removeEventListener("sudoku-locked-cell", onLockedCell);
window.removeEventListener("sudoku-valid-move", onValidMove);
window.removeEventListener("sudoku-invalid-move", onInvalidMove as EventListener);
};
}, [flashLocked, flashValid, flashInvalid, highlightConflicts]);
return {
cursor,
@@ -64,6 +114,8 @@ export function useCursor(rendererManager: UseRenderer) {
moveCursor,
getCellEl,
flashInvalid,
flashValid,
highlightConflicts,
};
}
+15 -1
View File
@@ -14,7 +14,17 @@ export function useGame(platformHook?: unknown) {
const gameManager = useGameStatus(rendererManager, cursorManager);
const { gameStatus, setGameStatus, startGame, stopGame } = gameManager;
const boardManager = useBoardState(cursorManager);
const { board, initialBoard, solution, setDigit, erase, reset, solveBoard } = boardManager;
const {
board,
initialBoard,
solution,
setDigit,
erase,
reset,
solveBoard,
isComplete,
isFullyValid,
} = boardManager;
// ---------------------------
// Keybindings
@@ -37,6 +47,10 @@ export function useGame(platformHook?: unknown) {
const scoreManager = useScore({
gameContext: { gameStatus, setGameStatus },
keystrokeCount: keyLog.length,
board,
isComplete,
isFullyValid,
initialBoard,
});
// ---------------------------
+51 -4
View File
@@ -78,16 +78,22 @@ export function useKeyBindings(ctx: Ctx) {
return;
}
// R or C to enter edit mode
if (k === "r" || k === "R" || k === "c" || k === "C") {
// R to replace (only works on user-filled cells)
if (k === "r" || k === "R") {
recordKey(k);
// Check if current cell is a pre-filled clue (not editable)
const cellIndex = ctx.cursor.r * 9 + ctx.cursor.c;
const isClue = ctx.initialBoard[cellIndex] !== ".";
const isEmpty = ctx.board[cellIndex] === ".";
if (isClue) {
// Flash red - cell is locked
// Flash red - cell is locked (pre-filled clue)
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return;
}
if (isEmpty) {
// Flash red - cell is empty (use I to insert)
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return;
}
@@ -96,6 +102,47 @@ export function useKeyBindings(ctx: Ctx) {
return;
}
// I to insert (only works on empty cells)
if (k === "i" || k === "I") {
recordKey(k);
const cellIndex = ctx.cursor.r * 9 + ctx.cursor.c;
const isClue = ctx.initialBoard[cellIndex] !== ".";
const isEmpty = ctx.board[cellIndex] === ".";
if (isClue) {
// Flash red - cell is locked (pre-filled clue)
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return;
}
if (!isEmpty) {
// Flash red - cell already has a value (use R to replace)
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return;
}
setEditMode("edit");
return;
}
// D or X to delete cell value in navigation mode
if (k === "d" || k === "D" || k === "x" || k === "X") {
recordKey(k);
const cellIndex = ctx.cursor.r * 9 + ctx.cursor.c;
const isClue = ctx.initialBoard[cellIndex] !== ".";
if (isClue) {
// Flash red - can't delete clues
window.dispatchEvent(new CustomEvent("sudoku-locked-cell"));
return;
}
ctx.erase();
return;
}
// Escape cancels count prefix
if (k === "Escape") {
recordKey(k);