代码和效果
点击方块,若五雷则显示周围雷的个数,若有雷则显示为红色方块,详细注释已写在代码中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<table id="board" border="1"></table>
<script>
const N = 8 //扫雷区域的大小,此处为 8*8
let mines = [0,5,15,21,32,33,41,43,51,53] //雷所处单元格的编号
let cells = genMineCells(mines) //将上述一维数组转换为二维数组
console.log(cells)
function genMineCells(mines){
let cells =new Array(N)
for(let i=0;i<cells.length;i++){
cells[i] = new Array(N)
for(let j=0;j<cells[i].length;j++)
cells[i][j]=0
}
mines.forEach((item,index,arr)=>{
//给有雷的赋值为-1
let row=arr[index]/N
row=Math.floor(row)
let col=arr[index]%N
cells[row][col] = -1
})
return cells;
}
countingMinesAround(mines,cells)
console.log(cells)
function countingMinesAround(mines,cells){ //计算每个单元格的周边的雷的数量
mines.forEach((item,index,arr)=>{
let i = Math.floor(item/N)//行
let j = item%N //列
if (i>0){
if (cells[i-1][j]>=0){//上
cells[i-1][j]++
}
if (j>0 && cells[i-1][j-1]>=0){//左上
cells[i-1][j-1]++
}
if (j<N-1 && cells[i-1][j+1]>=0){//右上
cells[i-1][j+1]++
}
}
if (i<N-1 && cells[i+1][j]>=0){//下
cells[i+1][j]++
}
if (i<N-1 && j>0&& cells[i+1][j-1]>=0){//左下
cells[i+1][j-1]++
}
if (i<N-1 && j<N-1&& cells[i+1][j+1]>=0){//右下
cells[i+1][j+1]++
}
if (j>0 && cells[i][j-1]>=0){//左
cells[i][j-1]++
}
if (j<N-1 && cells[i][j+1]>=0){//右
cells[i][j+1]++
}
})
}
$(document).ready(()=>{
//加载js中生成的html代码
$('#board').html(getTableHtml(N))
})
function getTableHtml(n){
var table=document.getElementById("board");
table.style.width="600px"
table.style.height="600px"
let w=600/n;
for(let i=0;i<n;i++){
//创建一行
var row = document.createElement("tr");
for(let j=0;j<n;j++){
创建一行中的一列
var col = document.createElement("td");
col.style.background="gray"
col.style.width=w+"px"
col.style.height=w+"px"
col.style.textAlign="center"
row.appendChild(col);
}
table.appendChild(row);//加入到表格中
}
$('td').click((event)=>{
let cell = event.target //获取单击的单元格
let i = $(cell).parent().prevAll().length //获取行号
let j = $(cell).prevAll().length //获取列号
//当该单元格有雷,显示为暗红色;
if(cells[i][j]==-1)
cell.style.background="#8B0000"
//当该单元格无雷,显示为浅绿色,并标注其周边雷的数目。
else{
cell.style.background="#90EE90"
cell.innerText=cells[i][j];
}
})
}
</script>
</body>
</html>