Борис К,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&display=swap');
.color {
background-color: var(--color);
width: 200px;
height: 100px;
text-align: center;
line-height: 100px;
}
.color:after {
display: block;
content: var(--txt);
color: #FFFFFF;
font-size: 48px;
font-family: 'Playfair Display', serif;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
let temp = [];
let form = document.querySelector(".game");
let tds = Array.from(form.querySelectorAll(".color"));
let colors = "#FF0000|#008000|#0000CD".split("|");
let txts = "Hello|Java|script".split("|");
let win;
function show() {
tds.forEach(td => {
let i = td.dataset.id;
td.style.setProperty("--color", colors[i]);
td.style.setProperty("--txt", `"${txts[i]}"`);
});
}
function randomId() {
win = false; temp = [];
let length = colors.length;
let ids = Array.from({
length
}, (v, i) => i);
ids.forEach((_, i) => {
let a = Math.trunc(Math.random() * length);
[ids[i], ids[a]] = [ids[a], ids[i]];
});
tds.forEach(({
dataset
}, i) => dataset.id = ids[i]);
show();
}
randomId()
function exch(event) {
if (win) return;
let td = event.target.closest(".color");
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];
show();
temp = [];
}
} else {
temp = [td, cellIndex, rowIndex];
}
win = tds.every(({
dataset: {
id
}
}, i) => id == i);
if (win) alert("Hello JavaScript!");
}
}
form.addEventListener("click", exch);
});
</script>
</head>
<body>
<div class="block">
<form class="game">
<table align="center" cellspacing="0" cellpadding="0">
<tr>
<td class="color"></td>
<td class="color"></td>
<td class="color"></td>
</tr>
</table>
</form>
</div>
</body>
</html>