For my final project in a class, I am developing a Pentomino puzzle game. All twelve puzzle pieces have been created, and they can be moved around using this interactive demo. However, when attempting to rotate the array without using canvas.rotate(), the code provided below swaps the X and Y coordinates while drawing:
var newPiece = targetPiece;
pieces.splice(pieces.indexOf(targetPiece), 1);
targetPiece = null;
console.log(newPiece);
var geometry = [];
for (var i = 0; i < newPiece.geometry.length; i++) {
geometry.push([newPiece.geometry[i][3], newPiece.geometry[i][0]]);
}
var offset = [newPiece.offset[1], newPiece.offset[0]];
console.log(geometry);
console.log(offset);
newPiece.geometry = geometry;
newPiece.position = geometry;
newPiece.offset = offset;
pieces.push(newPiece);
console.log(pieces);
for (var j = 0; j < pieces.length; j++) {
draw(pieces[j]);
}
This method shows potential but is not functioning correctly.
In this isolated example in the following fiddle link, the issue has been narrowed down to rotating a single piece using canvas.rotate(). However, it seems that each block of the array rotates individually, resulting in no visible change due to all blocks being squares:
function doubleClickListener(e) {
var br = canvas.getBoundingClientRect();
mouse_x = (e.clientX - br.left) * (canvas.width / br.width);
mouse_y = (e.clientY - br.top) * (canvas.height / br.height);
var pieceToggle = false;
for (var i = 0; i < pieces.length; i++) {
if (onTarget(pieces[i], mouse_x, mouse_y)) {
targetPiece = pieces[i];
rotate(targetPiece);
}
}
}
function rotate() {
targetPiece.rotationIndex = targetPiece.rotationIndex === 0 ?
1 : targetPiece.rotationIndex === 1 ?
2 : targetPiece.rotationIndex === 2 ?
3 : 0;
for (var j = 0; j < pieces.length; j++) {
draw(pieces[j]);
}
}
Despite initial attempts to create individual polygons for puzzle pieces, difficulty was faced in capturing them with mousedown events for movement. Canvas rectangle arrays were then used as they were simpler to manipulate.
To achieve a working puzzle before the deadline, two solutions are considered: implementing separate geometries for all piece rotations and mirrors, or utilizing fabric.js for a complete rewrite after the class ends.
The desired functionality is to rotate the array of five blocks by double-clicking, allowing sequential 90° rotations.
Towards a Functional Puzzle:
With assistance from @absolom, progress has been made on the puzzle game. Pieces can be dragged with a click and drag, rotated with a double-click, and mirrored with a right-click (although rotation only applies after moving the piece again). Z-order manipulation ensures the active piece remains on top:
Final Iteration:
The completed game has been submitted for grading. While there are still tweaks to be made, overall, I am satisfied with the outcome. For future improvements, such as fixing delayed rotation, an updated version using feedback received will be considered: