tic tac脚趾:html脚本
#javascript #编程 #教程 #gamedev

介绍
用HTML脚本构建永恒的游戏TIC TAC TOE。

Image description

UX组件
以下代码使用CSS定义了TIC TAC脚趾板及其单元格的布局和样式。它为木板创建了3x3网格布局,每个单元格为150x150像素。细胞具有边界,并且含量(x或o)在垂直和水平上均居中。内容显示为2em的字体大小,光标在悬停在单元格上时变为指针,表明它是可单击的。

    <style>
        .board {
            display: grid;
            grid-template-columns: repeat(3, 150px);
            grid-template-rows: repeat(3, 150px);
        }

        .cell {
            width: 150px;
            height: 150px;
            border: 2px solid black;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2em;
            cursor: pointer;
        }
    </style>

事件触发组件
板表示为带有九个细胞的网格。每个单元格是一个

元素,带有类名称为“单元格”。单击任何单元格时,调用相应的makeMove函数,将单击单元格的索引作为参数
    <div class="board" id="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>

规则引擎
他通过处理玩家的动作,检查胜利或绘制并在需要时重置游戏来实现TIC TAC TOE游戏的功能。游戏的逻辑和流程在此脚本中定义,使用户可以在HTML和CSS设计的板上玩游戏。

 <script>
        const board = document.getElementById('board');
        const cells = board.querySelectorAll('.cell');
        let currentPlayer = 'X';
        let moves = 0;
        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]
        ];

        function checkWinner(player) {
            return winningCombinations.some(combination => {
                return combination.every(cell => cells[cell].textContent === player);
            });
        }

        function makeMove(index) {
            if (cells[index].textContent === '') {
                cells[index].textContent = currentPlayer;
                moves++;

                if (checkWinner(currentPlayer)) {
                    alert(currentPlayer + ' wins!');
                    resetGame();
                } else if (moves === 9) {
                    alert('It\'s a draw!');
                    resetGame();
                } else {
                    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
                }
            }
        }

        function resetGame() {
            cells.forEach(cell => cell.textContent = '');
            currentPlayer = 'X';
            moves = 0;
        }
    </script>

演示
Demo

Power Apps Tic Tac Toe