Сообщение от Борис К
|
красный, зелёный, синий, оранжевый
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
[data-id="red"] {
background-color: #ff0000;
width: 100px;
height: 100px;
}
[data-id="orange"] {
background-color: #ff9900;
width: 100px;
height: 100px;
}
[data-id="green"] {
background-color: #006600;
width: 100px;
height: 100px;
}
[data-id="blue"] {
background-color: #0000ff;
width: 100px;
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];
}
if (!event.random) win = tds.every(({
dataset: {
id
}
}, i) => id === idEnd[i]);
if (win) alert("Hello world!");
}
}
form.addEventListener("click", exch);
tds.slice(0).sort(_ => Math.random() - .5)
.forEach(target => exch({
target,
random: true
}));
temp = [];
});
</script>
</head>
<body>
<form class="game">
<table align="center" cellspacing="0" cellpadding="0">
<tr>
<td data-id="red"></td>
<td data-id="green"></td>
</tr>
<tr>
<td data-id="blue"></td>
<td data-id="orange"></td>
</tr>
</table>
</form>
</body>
</html>