0
点赞
收藏
分享

微信扫一扫

前端小游戏(井字游戏)

前端小游戏(井字游戏)_Math

一、功能介绍

井字游戏是一款经典的策略性棋盘游戏,也被称为井字棋或三子棋。游戏通过在3x3的棋盘上轮流落子,目标是将自己的棋子以横、竖或对角线的形式连成一条线,先达成连线的一方获胜。这款游戏简单易学,但需要一定的思考和策略,是一款适合所有年龄段的休闲游戏。

游戏开始时,棋盘上显示一个3x3的网格,玩家扮演的是"X"棋子,计算机扮演的是"O"棋子。玩家和计算机轮流落子,每个回合可以在空白的格子中放置自己的棋子。玩家通过点击空白格子来放置"X"棋子,计算机会自动进行下棋。当任意一方的棋子以横、竖或对角线的形式连成一条线时,该方获得胜利。如果棋盘填满且没有任何一方获胜,则游戏为平局。挑战计算机,思考最佳策略,争取在井字游戏中获得胜利吧!

二、页面搭建

1)创建文件

首先创建一个HTML文件,命名随意 xxx.html 

2)DOM结构搭建

首先列出9个盒子

<div class="board">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
</div>
<div id="result"></div>

3)添加样式

<style>
    .board {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);
        gap: 5px;
        width: 300px;
        height: 300px;
        margin: 0 auto;
        border: 1px solid #ccc;
        padding: 5px;
    }

    .cell {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        background-color: #f2f2f2;
        cursor: pointer;
    }

    #result {
        text-align: center;
        font-size: 24px;
        margin-top: 20px;
    }
</style>

4)逻辑部分

通过监听格子的点击事件,调用 updateGameState 函数处理玩家的移动,并在页面加载完成后调用 resetGame 函数初始化游戏。

<script>
    function updateGameState(cellIndex) {
        if (!gameEnded && board[cellIndex] === "") {
            board[cellIndex] = currentPlayer;
            renderBoard();
            if (checkWin(currentPlayer)) {
                endGame("Player " + currentPlayer + " wins!");
            } else if (checkDraw()) {
                endGame("It's a draw!");
            } else {
                currentPlayer = currentPlayer === "X" ? "O" : "X";
                if (currentPlayer === "O") {
                    setTimeout(makeComputerMove, 500);
                }
            }
        }
    }

    function checkWin(player) {
        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 i = 0; i < winningCombinations.length; i++) {
            const [a, b, c] = winningCombinations[i];
            if (board[a] === player && board[b] === player && board[c] === player) {
                return true;
            }
        }
        return false;
    }

    function checkDraw() {
        return board.every(cell => cell !== "");
    }

    function endGame(message) {
        gameEnded = true;
        resultElement.textContent = message;
    }

    function makeComputerMove() {
        const emptyCells = board.reduce((acc, cell, index) => {
            if (cell === "") {
                acc.push(index);
            }
            return acc
        }
            , []);
        if (emptyCells.length > 0) {
            const randomIndex = Math.floor(Math.random() * emptyCells.length);
            const computerMove = emptyCells[randomIndex];
            updateGameState(computerMove);
        }
    }

    function renderBoard() {
        for (let i = 0; i < cells.length; i++) {
            cells[i].textContent = board[i];
        }
    }

    function resetGame() {
        board.fill("");
        currentPlayer = "X";
        gameEnded = false;
        resultElement.textContent = "";
        renderBoard();
    }

    cells.forEach((cell, index) => {
        cell.addEventListener("click", () => updateGameState(index));
    });

    resetGame();
</script>

三、完整代码

<!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">
    <title>Document</title>

    <style>
        .board {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 5px;
            width: 300px;
            height: 300px;
            margin: 0 auto;
            border: 1px solid #ccc;
            padding: 5px;
        }

        .cell {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            background-color: #f2f2f2;
            cursor: pointer;
        }

        #result {
            text-align: center;
            font-size: 24px;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="board">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
    <div id="result"></div>
</body>

<script>
    const board = ["", "", "", "", "", "", "", "", ""];
    const cells = document.querySelectorAll(".cell");
    const resultElement = document.getElementById("result");
    let currentPlayer = "X";
    let gameEnded = false;

    function updateGameState(cellIndex) {
        if (!gameEnded && board[cellIndex] === "") {
            board[cellIndex] = currentPlayer;
            renderBoard();
            if (checkWin(currentPlayer)) {
                endGame("Player " + currentPlayer + " wins!");
            } else if (checkDraw()) {
                endGame("It's a draw!");
            } else {
                currentPlayer = currentPlayer === "X" ? "O" : "X";
                if (currentPlayer === "O") {
                    setTimeout(makeComputerMove, 500);
                }
            }
        }
    }

    function checkWin(player) {
        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 i = 0; i < winningCombinations.length; i++) {
            const [a, b, c] = winningCombinations[i];
            if (board[a] === player && board[b] === player && board[c] === player) {
                return true;
            }
        }
        return false;
    }

    function checkDraw() {
        return board.every(cell => cell !== "");
    }

    function endGame(message) {
        gameEnded = true;
        resultElement.textContent = message;
    }

    function makeComputerMove() {
        const emptyCells = board.reduce((acc, cell, index) => {
            if (cell === "") {
                acc.push(index);
            }
            return acc
        }
            , []);
        if (emptyCells.length > 0) {
            const randomIndex = Math.floor(Math.random() * emptyCells.length);
            const computerMove = emptyCells[randomIndex];
            updateGameState(computerMove);
        }
    }

    function renderBoard() {
        for (let i = 0; i < cells.length; i++) {
            cells[i].textContent = board[i];
        }
    }

    function resetGame() {
        board.fill("");
        currentPlayer = "X";
        gameEnded = false;
        resultElement.textContent = "";
        renderBoard();
    }

    cells.forEach((cell, index) => {
        cell.addEventListener("click", () => updateGameState(index));
    });

    resetGame();
</script>

</html>










举报

相关推荐

0 条评论