Javascript sliding puzzle multilevel (solvable)
3x3, 4x4, 5x5, 6x6, etc.
by dj515
HTML
<div id="puzzle-wrapper">
<div></div>
</div>
JavaScript
// Source from https://github.com/thecodeholic/JsPicturePuzzle
class PicturePuzzle {
constructor(el, imageSrc, width, dimmension) {
this.parentEl = el;
this.dimmension = dimmension;
this.imageSrc = imageSrc;
this.width = width;
this.cells = [];
this.shuffling = false;
this.totalMoves = 1;
// events
this.onFinished = () => {};
this.onSwap = () => {};
this.init();
const img = new Image();
img.onload = () => {
this.height = img.height * this.width / img.width;
this.el.style.width = `${this.width}px`;
this.el.style.height = `${this.height}px`;
this.setup();
};
img.src = this.imageSrc;
}
init() {
this.el = this.createWrapper();
this.parentEl.appendChild(this.el);
}
createWrapper() {
const div = document.createElement('div');
div.style.position = 'relative';
div.style.margin = ' 0 auto';
return div;
}
setup() {
for (let i = 0; i < this.dimmension * this.dimmension; i++) {
this.cells.push(new Cell(this, i));
}
// =============================
//Shuffle until is solvable
// =============================
const isSaved = true;
if(isSaved){
this.shuffle();
}else{
while(true){
this.shuffle();
const list = this.listOfInds();
const emptyIndex = this.findEmptyIndexFromBottom(list);
const N = this.dimmension % 2 == 0 ? true : false;
const emptyRow = emptyIndex % 2 == 0 ? true : false;
const solvable = this.isSolvable();
if(N && emptyRow && solvable == false){
break;
}else if(N && emptyRow == false && solvable){
break;
}else if(N == false && solvable){
break;
...