HTML5代碼實例掃雷
<!DOCTYPE html> <html> <head> <title>掃雷游戲</title> <meta charset="UTF-8"> <style> body{ font-family: Arial, sans-serif; } table{ border-collapse: collapse; margin-left: auto; margin-right: auto; } th, td{ border: 1px solid black; padding: 10px; } td button{ width: 30px; height: 30px; background-color: lightgrey; font-weight: bold; font-size: 18px; cursor: pointer; } </style> </head> <body> <h1>掃雷游戲</h1> <p>點擊任意一個格子,開始游戲。紅色代表雷,數字代表周圍雷的數量。</p> <table> <tbody> <tr> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> </tr> <tr> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> </tr> <tr> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> <td><button onclick="openCell(this)"></button></td> </tr> </tbody> </table> <script> var bombCells = new Set([2, 5, 6]); // 炸彈格子 function openCell(cell){ var cellIndex = Array.from(cell.parentNode.parentNode.children).indexOf(cell.parentNode); cellIndex = cellIndex * 3 + Array.from(cell.parentNode.children).indexOf(cell); if(bombCells.has(cellIndex)){ cell.style.backgroundColor = "red"; alert("你輸了!"); }else{ var count = countNeighborBombs(cellIndex); if(count >0){ cell.innerHTML = count; }else{ cell.innerHTML = ""; } cell.style.backgroundColor = "white"; cell.disabled = true; } } function countNeighborBombs(cellIndex){ var count = 0; var row = Math.floor(cellIndex/3); var col = cellIndex % 3; for(var i = row - 1; i<= row + 1; i++){ for(var j = col - 1; j<= col + 1; j++){ if(i >= 0 && i< 3 && j >= 0 && j< 3 && !(i == row && j == col)){ var neighborIndex = i*3 + j; if(bombCells.has(neighborIndex)){ count++; } } } } return count; } </script> </body> </html>
上一篇html5代碼完成課程表
下一篇HTML5代碼實現扭蛋機