I'm trying to make a JS puzzle game (image drag and drop). I'm trying to assign the tiles (images) of the puzzle to the event listeners, but then the populate function doesn't work and won't populate the board. When removed it prints the images with no problem. I guess a workaround would be to make an assignEvents()
function after the board has been populated. Every help would be much appreciated.
class PuzzleGame extends Game {
constructor() {
super();
this.rows = 3;
this.columns = 3;
//current clicked image, other the one we swap with
this.currTile;
this.otherTile;
this.turns = 0;
this.imageOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9];
this.randomOrder = [];
}
populateBoard() {
for (let r = 0; r < this.rows; r++) {
for (let c = 0; c < this.columns; c++) {
let tile = document.createElement("img");
tile.id = r.toString() + "-" + c.toString();
tile.src = "./images/" + this.randomOrder.shift() + ".png";
// drag functions
tile.addEventListener("dragstart", dragStart);
tile.addEventListener("dragover", dragOver);
tile.addEventListener("dragenter", dragEnter);
tile.addEventListener("dragleave", dragLeave);
tile.addEventListener("drop", dragDrop);
tile.addEventListener("dragend", dragEnd);
document.getElementById("board").append(tile);
}
}
}
_randomizeOrder() {
if (!this.imageOrder) return undefined;
this.randomOrder = this.imageOrder.sort(function () {
return Math.random() - 0.5;
});
return this.randomOrder;
}
puzzleStart() {
this._randomizeOrder();
this.populateBoard();
}
dragStart() {
this.currTile = this; //image being dragged
}
dragOver(e) {
e.preventDefault();
}
dragEnter(e) {
e.preventDefault();
}
dragLeave() {}
dragDrop() {
this.otherTile = this; //image tile being dropped on
}
dragEnd() {
let currImg = this.currTile.src;
let otherImg = this.otherTile.src;
this.currTile.src = otherImg;
this.otherTile.src = currImg;
}
}
I tried to assign the addeventlisteners
to the tiles of the game while populating the board. In each iteration of the loop I tried to assign the events expecting to populate it AND at the same time painting the image on the board.