用HTML做井字棋代码如下
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe Game</title>
<style>
table {
border-collapse: collapse;
margin: auto;
}
td {
width: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
vertical-align: middle;
font-size: 3em;
font-weight: bold;
}
</style>
</head>
<body>
<table>
<tr>
<td id="11" οnclick="playTurn(1,1)"></td>
<td id="12" οnclick="playTurn(1,2)"></td>
<td id="13" οnclick="playTurn(1,3)"></td>
</tr>
<tr>
<td id="21" οnclick="playTurn(2,1)"></td>
<td id="22" οnclick="playTurn(2,2)"></td>
<td id="23" οnclick="playTurn(2,3)"></td>
</tr>
<tr>
<td id="31" οnclick="playTurn(3,1)"></td>
<td id="32" οnclick="playTurn(3,2)"></td>
<td id="33" οnclick="playTurn(3,3)"></td>
</tr>
</table>
<script>
var currentPlayer = "X";
var gameOver = false;
function playTurn(row, col) {
var cell = document.getElementById(row.toString() + col.toString());
if (!gameOver && cell.innerHTML === "") {
cell.innerHTML = currentPlayer;
checkWin();
switchPlayer();
}
}
function switchPlayer() {
currentPlayer = (currentPlayer === "X") ? "O" : "X";
}
function checkWin() {
var cells = document.getElementsByTagName("td");
if (checkRowWin(cells) || checkColWin(cells) || checkDiagonalWin(cells)) {
alert(currentPlayer + " wins!");
gameOver = true;
} else if (checkTie(cells)) {
alert("Tie game.");
gameOver = true;
}
}
function checkRowWin(cells) {
for (var i = 0; i < cells.length; i += 3) {
if (cells[i].innerHTML !== "" && cells[i].innerHTML === cells[i+1].innerHTML && cells[i+1].innerHTML === cells[i+2].innerHTML) {
return true;
}
}
return false;
}
function checkColWin(cells) {
for (var i = 0; i < 3; i++) {
if (cells[i].innerHTML !== "" && cells[i].innerHTML === cells[i+3].innerHTML && cells[i+3].innerHTML === cells[i+6].innerHTML) {
return true;
}
}
return false;
}
function checkDiagonalWin(cells) {
if (cells[0].innerHTML !== "" && cells[0].innerHTML === cells[4].innerHTML && cells[4].innerHTML === cells[8].innerHTML) {
return true;
} else if (cells[2].innerHTML !== "" && cells[2].innerHTML === cells[4].innerHTML && cells[4].innerHTML === cells[6].innerHTML) {
return true;
} else {
return false;
}
}
function checkTie(cells) {
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML === "") {
return false;
}
}
return true;
}
</script>
</body>
</html>