Если сетка 4х4, где каждый квадрат нумеруется сверху вниз, слева направо, как здесь:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Вы хотите сопоставить любые два квадрата x
и y
, где y
больше x
и:
y - x == 1 3 && (x+1) % 4 > 0 //for horizontally adjacent squares
y - x == 4 //for vertically adjacent squares
y - x == 3 && (y+1) % 4 == 0 //for squares at opposite ends of a row
Обновление: контрольный пример
let grid = document.querySelector(".grid")
for(i=0;i<16;i++){
let sq = document.createElement("div")
sq.classList.add("sq")
sq.dataset.id = i
grid.appendChild(sq)
}
let squares = document.querySelectorAll(".sq")
let x = null,y = null
squares.forEach(el => {
el.addEventListener("click", (e) => {
let dId = e.target.dataset.id
if(!x){
x = dId
e.target.classList.add("x")
}else if(!y){
y = dId
e.target.classList.add("y")
checkIfWinner(x,y)
}
})
})
document.getElementById("reset").onclick = () => {
console.clear()
x=null
y=null
squares.forEach(el => {el.classList.remove("x"); el.classList.remove("y")})
}
function checkIfWinner(x,y){
let high = x > y ? x : y
let low = x > y ? y : x
if( (high - low == 1 && (parseInt(low)+1) % 4 > 0) || high - low == 4 || (high - low == 3 && (parseInt(high)+1) % 4 == 0)){
console.log("Winner")
}else{
console.log("Try Again")
}
}
.grid{
display:inline-grid;
grid-template-columns: repeat(4,1fr);
grid-gap: 4px;
}
.grid > div{
border: solid 2px gray;
height: 30px;
width: 30px;
}
h3{margin:0 0 5px}
.x{background-color: dodgerblue}
.y{background-color: orangered}
<h3>Click any two squares<h3>
<div class="grid"></div>
<button id="reset">Reset</button>