I want to move a block to the empty space (swap the block with the empty block) when clicked.
But before doing so, I have to verify if the block is movable.
I'm confused with how to apply the logic here. I've seen many solutions but I don't really understand and others used jQuery plus I don't still get it :-/
I need some help please.
Here's what I tried doing:
randomOrder.forEach((el, i) => {
const block = document.createElement('div')
block.classList.add('block')
block.id = "b" + el
block.style.left = (4 + 98 * (i % 3)) + 'px'
block.style.top = (4 + 98 * Math.floor(i / 3)) + 'px'
block.innerText = el == 9 ? "" : el
if(el == 9){ freeBlock = block }
container.appendChild(block)
}) //////////////
// get clicked block
container.addEventListener("click", (e) => {
var clickedBlock = e.target
if (e.target.id === "b9") {
return 0
}
else {
moveBlock(clickedBlock)
}
}) ///////////////
// Function To Move Block
function moveBlock(clickedBlock) {
// check if the block is movable before moving it
if (isMovable(clickedBlock)) {
console.log(clickedBlock.offsetLeft)
}
} /////////////// end moveBlock()
// check if block is movable
function isMovable(clickedBlock) {
if(clickedBlock.offsetLeft === freeBlock.offsetLeft){
if(clickedBlock.offsetTop === freeBlock.offsetTop){
return true
}
}
} //////////// end check if movable
Anyone knows how I can do this ?
I would first change two things in your setup:
Don't create a block in the DOM for value 9. Just only make blocks for the other values (8 blocks)
Keep the array from which you created the blocks updated with every move. It is good practice to keep the state of the game in variables and treat the display as a sort of side effect.
Here is how you could do it: