HTML5井字棋源代碼
<!DOCTYPE html> <html> <head> <title>HTML5井字棋游戲</title> <meta charset="UTF-8"> <style> table { border-collapse: collapse; margin-bottom: 20px; } th, td { border: 1px solid #999; padding: 10px; text-align: center; width: 100px; height: 100px; } th { background-color: #ddd; } td:hover { background-color: #eee; } #winner { font-size: 24px; font-weight: bold; text-align: center; margin-top: 20px; } </style> </head> <body> <h1>HTML5井字棋游戲</h1> <table id="game"> <tr> <td id="0-0" onclick="place('0-0')"></td> <td id="0-1" onclick="place('0-1')"></td> <td id="0-2" onclick="place('0-2')"></td> </tr> <tr> <td id="1-0" onclick="place('1-0')"></td> <td id="1-1" onclick="place('1-1')"></td> <td id="1-2" onclick="place('1-2')"></td> </tr> <tr> <td id="2-0" onclick="place('2-0')"></td> <td id="2-1" onclick="place('2-1')"></td> <td id="2-2" onclick="place('2-2')"></td> </tr> </table> <div id="winner"></div> <button onclick="reset()">重新開始</button> <script> var player = "x"; var winner = null; function place(cell) { var cellElement = document.getElementById(cell); if (cellElement.innerHTML !== "") { return; } cellElement.innerHTML = player; check_winner(); switch_player(); } function check_winner() { var gameBoard = document.getElementById("game"); var winningCombinations = [ ["0-0", "0-1", "0-2"], ["1-0", "1-1", "1-2"], ["2-0", "2-1", "2-2"], ["0-0", "1-0", "2-0"], ["0-1", "1-1", "2-1"], ["0-2", "1-2", "2-2"], ["0-0", "1-1", "2-2"], ["0-2", "1-1", "2-0"] ]; for (var i = 0; i< winningCombinations.length; i++) { var combo = winningCombinations[i]; var a = document.getElementById(combo[0]); var b = document.getElementById(combo[1]); var c = document.getElementById(combo[2]); if (a.innerHTML === "" || b.innerHTML === "" || c.innerHTML === "") { continue; } if (a.innerHTML === b.innerHTML && b.innerHTML === c.innerHTML) { winner = a.innerHTML; a.style.backgroundColor = "#00ff00"; b.style.backgroundColor = "#00ff00"; c.style.backgroundColor = "#00ff00"; break; } } if (winner !== null) { var winnerElement = document.getElementById("winner"); winnerElement.innerHTML = winner + "獲勝!"; } } function switch_player() { if (player === "x") { player = "o"; } else { player = "x"; } } function reset() { player = "x"; winner = null; var gameBoard = document.getElementById("game"); for (var i = 0; i< gameBoard.rows.length; i++) { for (var j = 0; j< gameBoard.rows[i].cells.length; j++) { gameBoard.rows[i].cells[j].innerHTML = ""; gameBoard.rows[i].cells[j].style.backgroundColor = ""; } } var winnerElement = document.getElementById("winner"); winnerElement.innerHTML = ""; } </script> </body> </html>
上一篇html5交互式導圖代碼
下一篇mysql中插入電話號碼