xxxxxxxxxx
107
let pieceCount = 7;
let pieces = [];
let img;
let gridSize = 500; // Size of the jigsaw square
let pieceSize;
function preload() {
img = loadImage('nyu.jpg');
}
function setup() {
createCanvas(windowWidth, windowHeight);
pieceSize = gridSize / pieceCount;
initializePieces();
}
function draw() {
background(200);
for (let piece of pieces) {
piece.show();
}
}
function initializePieces() {
let startX = width / 2 - gridSize / 2;
let startY = height / 2 - gridSize / 2;
for (let row = 0; row < pieceCount; row++) {
for (let col = 0; col < pieceCount; col++) {
let imgX = col * (img.width / pieceCount);
let imgY = row * (img.height / pieceCount);
let imgW = img.width / pieceCount;
let imgH = img.height / pieceCount;
// Determine the edge types for the jigsaw pattern
let edges = [
row === 0 ? 0 : -pieces[(row - 1) * pieceCount + col].edges[2], // Top
col === pieceCount - 1 ? 0 : random([-1, 1]), // Right
row === pieceCount - 1 ? 0 : random([-1, 1]), // Bottom
col === 0 ? 0 : -pieces[row * pieceCount + col - 1].edges[1], // Left
];
pieces.push(
new Piece(
startX + col * pieceSize + pieceSize / 2,
startY + row * pieceSize + pieceSize / 2,
pieceSize,
img.get(imgX, imgY, imgW, imgH),
edges,
row,
col
)
);
}
}
}
class Piece {
constructor(x, y, size, img, edges, correctRow, correctCol) {
this.x = x;
this.y = y;
this.size = size;
this.img = img;
this.edges = edges; // Jigsaw pattern edges: 0 = flat, 1 = tab, -1 = blank
this.correctRow = correctRow;
this.correctCol = correctCol;
this.rotation = 0; // Rotation in increments of 90 degrees
}
show() {
push();
translate(this.x, this.y);
rotate(this.rotation * HALF_PI);
imageMode(CENTER);
image(this.img, 0, 0, this.size, this.size);
pop();
// Draw jigsaw borders
for (let i = 0; i < 4; i++) {
if (this.edges[i] !== 0) {
this.drawBorder(i * HALF_PI, this.edges[i]);
}
}
}
drawBorder(theta, edgeType) {
let startPoint = createVector(-0.5 * this.size, -0.5 * this.size);
let endPoint = createVector(0.5 * this.size, -0.5 * this.size);
let offsetX = this.size * 0.35;
let offsetY = edgeType * this.size * 0.2; // Positive for tab, negative for blank
fill(255, 255, 255, 0);
push();
translate(this.x, this.y);
rotate(theta);
beginShape();
curveVertex(startPoint.x, startPoint.y);
curveVertex(startPoint.x, startPoint.y);
curveVertex(startPoint.x + offsetX, startPoint.y);
curveVertex(startPoint.x + offsetX, startPoint.y + offsetY);
curveVertex(endPoint.x - offsetX, endPoint.y + offsetY);
curveVertex(endPoint.x - offsetX, endPoint.y);
curveVertex(endPoint.x, endPoint.y);
curveVertex(endPoint.x, endPoint.y);
endShape();
pop();
}
}