Рони, а возможно сделать, чтобы в стилях были не ссылки на изображения, а текстовый контент в самом коде?
Я немного упростил код для удобства:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
[data-id="red"] {
background-image:url(https://placehold.co/200x100/ff0000/EEE?font=playfair-display&text=Hello);
width: 200px;
height: 100px;
}
[data-id="orange"] {
background-image:url(https://placehold.co/200x100/ff9900/EEE?font=playfair-display&text=Java);
width: 200px;
height: 100px;
}
[data-id="green"] {
background-image:url(https://placehold.co/200x100/006600/EEE?font=playfair-display&text=script!);
width: 200px;
height: 100px;
}
</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 JavaScript!");
}
}
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>
<div class="block">
<form class="game">
<table align="center" cellspacing="0" cellpadding="0">
<tr>
<td data-id="red"></td>
<td data-id="orange"></td>
<td data-id="green"></td>
</tr>
</table>
</form>
</div>
</body>
</html>