如何做出一个井字棋游戏(网站版):
2023-09-10 19:43:19
发布于:江苏
1.新建3个txt文件
2.在第一个txt文件上输入以下代码:
<!DOCTYPE html>
<html>
<head>
<title>井字棋游戏</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1>井字棋游戏</h1>
<div class="game-board">
<div class="cell" onclick="makeMove(0)"></div>
<div class="cell" onclick="makeMove(1)"></div>
<div class="cell" onclick="makeMove(2)"></div>
<div class="cell" onclick="makeMove(3)"></div>
<div class="cell" onclick="makeMove(4)"></div>
<div class="cell" onclick="makeMove(5)"></div>
<div class="cell" onclick="makeMove(6)"></div>
<div class="cell" onclick="makeMove(7)"></div>
<div class="cell" onclick="makeMove(8)"></div>
</div>
<div id="message"></div>
</body>
</html>
3.将文件名带后缀改为index.html
4.在第二个txt文件上输入以下代码:
.game-board {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.cell {
width: 150px;
height: 150px;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
cursor: pointer;
}
#message {
margin-top: 20px;
font-size: 24px;
text-align: center;
}
5.将文件名带后缀改为styles.css
6.在第三个txt文件上输入以下代码:
let gameBoard = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameOver = false;
function makeMove(index) {
if (!gameOver && gameBoard[index] === "") {
gameBoard[index] = currentPlayer;
document.getElementsByClassName("cell")[index].innerText = currentPlayer;
checkGameOver();
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
}
function checkGameOver() {
const winningCombinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // 横
[0, 3, 6], [1, 4, 7], [2, 5, 8], // 竖
[0, 4, 8], [2, 4, 6] // 斜
];
for (let combination of winningCombinations) {
const [a, b, c] = combination;
if (
gameBoard[a] !== "" &&
gameBoard[a] === gameBoard[b] &&
gameBoard[b] === gameBoard[c]
) {
gameOver = true;
document.getElementById("message").innerText = `游戏结束,${gameBoard[a]} 赢了!`;
return;
}
}
if (!gameBoard.includes("")) {
gameOver = true;
document.getElementById("message").innerText = "游戏结束,平局!";
}
}
7.将文件名带后缀改为script.js
8.把三个文件放到同一个文件夹里
这是一个简单的井字棋游戏,通过点击格子进行下棋操作,并根据规则判断游戏结束。
这里空空如也
有帮助,赞一个