有这样的代码,二维数组:
let app = document.getElementById('app');
let table = document.createElement('div');
table.classList.add('table');
app.appendChild(table);
const BASE = 9;
let arrNum = [];
for(let iNum = 1; iNum < 20; iNum ++ ) {
if(iNum%10 === 0) continue;
let strNum = iNum.toString();
arrNum.push(...strNum);
}
let n = arrNum.length;
let x = BASE;
let y = Math.floor(n / BASE);
for(let iy = 0; iy < y; iy++){
let tr = document.createElement('div');
tr.classList.add('tr');
table.appendChild(tr);
for(let ix = 0; ix < x; ix++){
let td = document.createElement('div');
td.classList.add('td');
td.dataset.x = ix;
td.dataset.y = iy;
tr.appendChild(td);
}
}
const nums = document.querySelectorAll('.td');
arrNum.forEach((num, i) => {
nums[i].innerHTML = num;
});
let isNum = false;
let firstNum, secondNum;
function flipNum(){
if(this === firstNum) return;
this.classList.add('select');
if(!isNum) {
isNum = true;
firstNum = this;
return;
}
secondNum = this;
getIndex();
checkForMatch();
}
function getIndex(){
//console.log(firstNum.dataset.x + ' ' + firstNum.dataset.y);
}
function checkForMatch() {
let firstNumVal = +firstNum.innerHTML;
let secondNumVal = +secondNum.innerHTML;
let isMatch = firstNumVal + secondNumVal === BASE + 1 || firstNumVal === secondNumVal;
console.log(isMatch);
isMatch ? disableNum() : resetMatch();
}
function disableNum(){
firstNum.removeEventListener('click', flipNum);
secondNum.removeEventListener('click', flipNum);
firstNum.classList.add('match');
secondNum.classList.add('match');
resetNum();
}
function resetMatch(){
firstNum.classList.remove('select');
secondNum.classList.remove('select');
resetNum();
}
function resetNum(){
isNum = false;
firstNum = null;
secondNum = null;
}
nums.forEach(num => num.addEventListener('click', flipNum));
* {
box-sizing: border-box;
}
html,
body {
padding: 0;
margin: 0;
}
.table {
max-width: 500px;
margin: 2rem auto;
}
.tr {
display: flex;
}
.td {
width: calc(100% / 9);
height: 2.5rem;
line-height: 2.5rem;
text-align: center;
cursor: pointer;
border: 1px solid;
}
.select {
background: #8BC34A;
}
.match {
background: #bdbdbd;
}
<div id="app"></div>
问题:如何实现只点击相邻单元格(上、下、左、右),如何禁止点击对角单元格?
问题的本质:从块中创建一个特定的矩形
A x B,您需要学习如何找到每个块的相邻单元格。每行中的单元格数量是预先知道的,它仍然与单击按钮的数量有一点关系:相邻单元格是由它们的坐标相差一个这一事实来确定的。
如果我们只取水平和垂直方向,那么只有一个坐标,x 或 y,应该不同,另一个应该匹配。
这引起了以下检查
因此,代码可能如下所示: