Rise, вот так оно всё должно выглядеть в конечном результате, но только в этом варианте всё время будет одно и то же изображение собираться, поэтому я изначально в этой теме хотел каждый раз новое изображение генерировать для сборки:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
[data-id="1"] {
background-image:url(https://i.ibb.co/cb6tXTH/canvas-01.jpg);
width: 200px;
height: 200px;
}
[data-id="2"] {
background-image:url(https://i.ibb.co/r3nXCKj/canvas-02.jpg);
width: 200px;
height: 200px;
}
[data-id="3"] {
background-image:url(https://i.ibb.co/PFc43HB/canvas-03.jpg);
width: 200px;
height: 200px;
}
[data-id="4"] {
background-image:url(https://i.ibb.co/r5dVWj7/canvas-04.jpg);
width: 200px;
height: 200px;
}
[data-id="5"] {
background-image:url(https://i.ibb.co/jGp056d/canvas-05.jpg);
width: 200px;
height: 200px;
}
[data-id="6"] {
background-image:url(https://i.ibb.co/GRVYX8H/canvas-06.jpg);
width: 200px;
height: 200px;
}
[data-id="7"] {
background-image:url(https://i.ibb.co/QbR97Fr/canvas-07.jpg);
width: 200px;
height: 200px;
}
[data-id="8"] {
background-image:url(https://i.ibb.co/StcY4gm/canvas-08.jpg);
width: 200px;
height: 200px;
}
[data-id="9"] {
background-image:url(https://i.ibb.co/bB70pMR/canvas-09.jpg);
width: 200px;
height: 200px;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
let temp = [];
let form = document.querySelector(".game");
let tds = Array.from(form.querySelectorAll("[data-id]"));
let idEnd = tds.map(({
dataset: {
id
}
}) => id);
let win;
function exch(event) {
if (win) return;
let td = event.target.closest("[data-id]");
if (td) {
let cellIndex = td.cellIndex;
let rowIndex = td.closest("tr").rowIndex;
if (temp.length) {
let x = Math.abs(cellIndex - temp[1]);
let y = Math.abs(rowIndex - temp[2]);
if ((x == 0 && y == 1) || (x == 1 && y == 0) || td === temp[0]) {
[td.dataset.id, temp[0].dataset.id] = [temp[0].dataset.id, td.dataset.id]
temp = [];
}
} else {
temp = [td, cellIndex, rowIndex];
}
win = tds.every(({
dataset: {
id
}
}, i) => id === idEnd[i]);
if (win) alert("Hello world!");
}
}
form.addEventListener("click", exch);
let color = idEnd.slice(0), len = color.length;
color.forEach((_, i) => {
let a = Math.trunc(Math.random() * len);
[color[i], color[a]] = [color[a], color[i]];
});
tds.forEach(({dataset}, i) => dataset.id = color[i]);
});
</script>
</head>
<body>
<form class="game">
<table align="center" cellspacing="0" cellpadding="0">
<tr>
<td data-id="1"></td>
<td data-id="2"></td>
<td data-id="3"></td>
</tr>
<tr>
<td data-id="4"></td>
<td data-id="5"></td>
<td data-id="6"></td>
</tr>
<tr>
<td data-id="7"></td>
<td data-id="8"></td>
<td data-id="9"></td>
</tr>
</table>
</form>
</body>
</html>