xxxxxxxxxx
116
let cols = 9; // Number of columns
let rows = 9; // Number of rows
let w, h; // Width and height of each square
let symbols = ["☭", "ﷲ", "✄", "✿", "✽", "♡", "ء", "★", "✤"];
let colors = ["#f9ec00", "#f47920", "#e21d3c", "#583f99", "#9a258f", "#17479e", "#00addc", "#ed1846", "#000000"];
let sudokuGrid = []; // 9x9 grid for Sudoku
function setup() {
createCanvas(450, 450); // Canvas size
w = width / cols; // Width of each square
h = height / rows; // Height of each square
noLoop(); // No continuous drawing
// Initialize the grid
generateSolvedSudoku();
// Create a button to generate a new Sudoku puzzle
let button = createButton('Generate New Sudoku');
button.position(10, height + 10);
button.mousePressed(generateSolvedSudoku);
drawBackground();
drawSudoku();
}
// Function to draw the background
function drawBackground() {
let pink = color('#ffaee2');
let green = color('#b8eea4');
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
let index = x + (y % 2);
fill(index % 2 === 0 ? pink : green);
noStroke(); // Remove strokes from the rectangles
rect(x * w, y * h, w, h);
}
}
}
// Function to generate a solved Sudoku puzzle
function generateSolvedSudoku() {
sudokuGrid = Array.from({ length: 9 }, () => Array(9).fill(0)); // Reset grid
fillSudoku(0, 0);
}
// Function to check if a symbol can be placed
function canPlaceSymbol(row, col, symbol) {
// Check the row and column
for (let i = 0; i < 9; i++) {
if (sudokuGrid[row][i]?.symbol === symbol || sudokuGrid[i][col]?.symbol === symbol) {
return false;
}
}
// Check the 3x3 subgrid
let startRow = Math.floor(row / 3) * 3;
let startCol = Math.floor(col / 3) * 3;
for (let i = startRow; i < startRow + 3; i++) {
for (let j = startCol; j < startCol + 3; j++) {
if (sudokuGrid[i][j]?.symbol === symbol) {
return false;
}
}
}
return true;
}
// Recursive function to fill the Sudoku grid
function fillSudoku(row, col) {
if (col === 9) { // Move to the next row
col = 0;
row++;
if (row === 9) return true; // Solved
}
// Shuffle the symbols and colors to create randomness
let shuffledIndices = [Array(symbols.length).keys()];
shuffledIndices = shuffle(shuffledIndices);
// Try placing each symbol in the current cell
for (let index of shuffledIndices) {
let symbol = symbols[index];
let colorCode = colors[index];
if (canPlaceSymbol(row, col, symbol)) {
sudokuGrid[row][col] = { symbol, colorCode }; // Place the symbol and color
if (fillSudoku(row, col + 1)) {
return true; // Continue to next cell
}
sudokuGrid[row][col] = 0; // Backtrack
}
}
return false; // No valid placement found
}
// Function to draw the Sudoku grid
function drawSudoku() {
textSize(90);
textAlign(CENTER, CENTER);
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (sudokuGrid[row][col] !== 0) {
fill(sudokuGrid[row][col].colorCode);
// Draw the symbol centered in a 4x4 block
text(sudokuGrid[row][col].symbol, col * 4 * w + 2 * w, row * 4 * h + 2 * h);
}
}
}
}