xxxxxxxxxx
123
let img;
let cols = 3, rows = 3;
let tileWidth, tileHeight;
let tiles = [];
let board = [];
let selectedTile = null;
let offsetX, offsetY;
let dropZoneX, dropZoneY, dropZoneW, dropZoneH;
function preload() {
img = loadImage('puzzle.png'); // Replace with your image
}
function setup() {
createCanvas(1200, 600); // Wider canvas to accommodate the drop zone
tileWidth = img.width / cols;
tileHeight = img.height / rows;
dropZoneX = 500; // Drop zone starts from x=500
dropZoneY = 50;
dropZoneW = img.width;
dropZoneH = img.height;
prepareTiles();
shuffleTiles();
}
function prepareTiles() {
tiles = [];
board = [];
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let tile = {
img: img.get(i * tileWidth, j * tileHeight, tileWidth, tileHeight),
x: random(50, 300), // Left-side spawn (without distortion)
y: random(50, height - tileHeight),
correctX: dropZoneX + i * tileWidth,
correctY: dropZoneY + j * tileHeight
};
tiles.push(tile);
board.push(tile);
}
}
}
function shuffleTiles() {
for (let i = board.length - 1; i > 0; i--) {
let j = floor(random(i + 1));
[board[i], board[j]] = [board[j], board[i]];
}
}
function draw() {
background(255);
// Draw Drop Zone
fill(200, 230, 255, 100);
stroke(0);
rect(dropZoneX, dropZoneY, dropZoneW, dropZoneH);
// Draw all puzzle pieces
for (let tile of board) {
image(tile.img, tile.x, tile.y, tileWidth, tileHeight);
}
if (isSolved()) {
fill(0, 255, 0, 150);
rect(0, 0, width, height);
fill(0);
textSize(32);
textAlign(CENTER, CENTER);
text("Puzzle Solved!", width / 2, height / 2);
text("The answer to Clue 1 is:", width / 2, height / 2 + 60);
text("jOw", width / 2, height / 2 + 110);
}
}
function mousePressed() {
for (let tile of board) {
if (mouseX > tile.x && mouseX < tile.x + tileWidth &&
mouseY > tile.y && mouseY < tile.y + tileHeight) {
selectedTile = tile;
offsetX = mouseX - tile.x;
offsetY = mouseY - tile.y;
break;
}
}
}
function mouseDragged() {
if (selectedTile) {
selectedTile.x = constrain(mouseX - offsetX, 0, width - tileWidth);
selectedTile.y = constrain(mouseY - offsetY, 0, height - tileHeight);
}
}
function mouseReleased() {
if (selectedTile) {
let closestDist = Infinity;
let closest = null;
for (let tile of board) {
let d = dist(selectedTile.x, selectedTile.y, tile.correctX, tile.correctY);
if (d < closestDist) {
closestDist = d;
closest = tile;
}
}
if (closest && closestDist < tileWidth / 2) {
selectedTile.x = closest.correctX;
selectedTile.y = closest.correctY;
}
selectedTile = null;
}
}
function isSolved() {
return board.every(tile => tile.x === tile.correctX && tile.y === tile.correctY);
}