Борис К,
картинки располагать в таблице по порядку.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#red {
background-color: #ff0000;
width: 100px;
height: 100px;
}
#orange {
background-color: #ff9900;
width: 100px;
height: 100px;
}
#green {
background-color: #006600;
width: 100px;
height: 100px;
}
#blue {
background-color: #0000ff;
width: 100px;
height: 100px;
}
</style>
<script type="text/javascript">
let temp = [];
let end = ["r", "g", "b", "o"];
let win;
function exch(event) {
if (win) return;
let img;
if (img = event.target.closest(".click")) {
let cellIndex = event.target.closest("td").cellIndex;
let rowIndex = event.target.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) || img === temp[0]) {
[img.src, temp[0].src] = [temp[0].src, img.src]
temp = [];
}
} else {
temp = [img, cellIndex, rowIndex];
}
const numbers = Array.from(document.querySelectorAll(".click")).map(({
src
}) =>
src.split('=')[2]);
if (!event.random) win = numbers.every((a, i) => a === end[i]);
if (win) alert("Hello world!");
}
}
document.addEventListener("DOMContentLoaded", function() {
let img = Array.from(document.querySelectorAll(".click"));
img.sort(_ => Math.random() - .5);
img.forEach(target => exch({
target,
random: true
}));
temp = [];
});
</script>
</head>
<body>
<form onclick="exch(event)">
<table align="center" cellspacing="0" cellpadding="0">
<tr>
<td><img class="click" name="1" src="https://placehold.co/100x100/0000ff/ffffff?font=playfair-display&text=r"></td>
<td><img class="click" name="2" src="https://placehold.co/100x100/006600/ffffff?font=playfair-display&text=g"></td>
</tr>
<tr>
<td><img class="click" name="3" src="https://placehold.co/100x100/ff0000/ffffff?font=playfair-display&text=b"></td>
<td><img class="click" name="4" src="https://placehold.co/100x100/ff9900/ffffff?font=playfair-display&text=o"></td>
</tr>
</table>
</form>
</body>
</html>