Home > database >  How can I build logic checks for wins, losses, and ties in a JavaScript Tic-Tac-Toe game?
How can I build logic checks for wins, losses, and ties in a JavaScript Tic-Tac-Toe game?

Time:05-22

I am creating a tic-tac-toe game in html,CSS,and JavaScript. I want to check when the game is over in the form of tie, win or loss. However for some reason my functions aren't working and aren't returning either a tie win or loss upon selection of a winning Combination. Codepen (https://codepen.io/nolimitz71/pen/jOYENdL) . Here is the JS:


    const gameBoard = (() => {
        var initialPLayer = "X";
        var board = [];
        var gameResults = document.querySelector('#warning');
        var playerDisplay = document.querySelector("#para-display")
        var cells = document.querySelectorAll("#box");
        var boardBoxes = document.getElementById("piece").getElementsByTagName("td");
    
        const winningCombos = [
            [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 playerMovement() {
            if (initialPLayer === 'X') {
                initialPLayer = "O";
                playerDisplay.innerHTML = "O"
            } else {
                initialPLayer = "X";
                playerDisplay.innerHTML = "X"
            }
        }
    
        function playGame() {
            if (this.innerHTML == '') {
                this.innerHTML = initialPLayer;
                playerMovement();
            }
        }
    
        var boardBoxes = document.getElementById("piece").getElementsByTagName("td");
        for (var i = 0; i < boardBoxes.length; i  ) {
            boardBoxes[i].onclick = playGame;
        }
        document.getElementById("reset").onclick = function() {
            for (var i in boardBoxes) {
                boardBoxes[i].innerHTML = '';
            }
        }
    
        function gameLogic() {
            if (checkWinX()) {
                gameResults.innerHTML = "Player X wins the game"
            }
            if (checkWinO()) {
                gameResults.innerHTML = "Player O wins the game"
            }
            if (Tie()) {
                gameResults.innerHTML = "Tie!!"
            }
        }
        gameLogic()
    
        function checkWinX() {
            return winningCombos.some((combination) => {
                return combination.every((i) => {
                    return cells[i].innerHTML === "X";
                })
            })
        }
    
        function checkWinO() {
            return winningCombos.some((combination) => {
                return combination.every((i) => {
                    return cells[i].innerHTML === "O";
                })
            })
        }
    
        function Tie() {
            return cells.forEach((cells) => {
                return cells.innerText === "X" || cells.innerText === "O";
            })
        }
    
    
    })();```
    
    **HTML:** 
    ```<!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>Tic-Tac-Toe</title>
        <link rel = "stylesheet" href="styles.css">
    </head>
    <body>
        <h1>Tic-Tac-Toe</h1>
        <div id = "game">
          <table id = "piece">
             <div class = "control">
              <tr  id = "board1">
                  <td  id = "box" class = 'cell'></td>
                  <td  id = "box" class = 'vert cell1'></td>
                  <td id = "box" class = "cell2"></td>
              </tr>
              <tr id = "board2">
                  <td  id = "box" class = 'hori cell3'></td>
                  <td id = "box" class = "vert hori cell4"></td>
                  <td id = "box" class = "hori cell5"></td>
              </tr>
              <tr id = "board3">
                  <td  id = "box" class = "cell6"></td>
                  <td id = "box"  class = "vert cell7"></td>
                  <td  id = "box"  class = "cell8"></td>
              </tr>
            </tbody>
        </div>
          </table>
          <button id = "reset">New Game</button>
          <p id = "result">It's <span id="para-display">X</span>'s turn.</p>
          
          <p id="warning"></p>
    <script src = "app.js" defer></script> 
    </body>
    </html>```

CodePudding user response:

Place gameLogic into playGame. Do remember to remove the whoever wins the game when users reset the game. Also, the tie function is not working.

const gameBoard = (() => {
    var initialPLayer = "X";
    var board = [];
    var gameResults = document.querySelector('#warning');
    var playerDisplay = document.querySelector("#para-display")
    var cells = document.querySelectorAll("#box");
    var boardBoxes = document.getElementById("piece").getElementsByTagName("td");

    const winningCombos = [
        [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 playerMovement() {
        if (initialPLayer === 'X') {
            initialPLayer = "O";
            playerDisplay.innerHTML = "O"
        } else {
            initialPLayer = "X";
            playerDisplay.innerHTML = "X"
        }
    }

    function playGame() {
        if (this.innerHTML == '') {
            this.innerHTML = initialPLayer;
            playerMovement();
            gameLogic()
        }
    }

    var boardBoxes = document.getElementById("piece").getElementsByTagName("td");
    for (var i = 0; i < boardBoxes.length; i  ) {
        boardBoxes[i].onclick = playGame;
    }
    document.getElementById("reset").onclick = function() {
        for (var i in boardBoxes) {
            boardBoxes[i].innerHTML = '';
        }
    }

    function gameLogic() {
        if (checkWinX()) {
            gameResults.innerHTML = "Player X wins the game"
        }
        if (checkWinO()) {
            gameResults.innerHTML = "Player O wins the game"
        }
        if (Tie()) {
            gameResults.innerHTML = "Tie!!"
        }
    }

    function checkWinX() {
        return winningCombos.some((combination) => {
            return combination.every((i) => {
                return cells[i].innerHTML === "X";
            })
        })
    }

    function checkWinO() {
        return winningCombos.some((combination) => {
            return combination.every((i) => {
                return cells[i].innerHTML === "O";
            })
        })
    }

    function Tie() {
        return cells.forEach((cells) => {
            return cells.innerText === "X" || cells.innerText === "O";
        })
    }


})();
h1{
    text-align: center;
}
td{
    width:100px;
    height:100px;
}
table{
    margin:5px auto;
}
.vert{
    border-left:2px solid black;
    border-right: 2px solid black;
}
.hori{
    border-top:2px solid black;
    border-bottom:2px solid black;
}
<!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>Tic-Tac-Toe</title>
    <link rel = "stylesheet" href="styles.css">
</head>
<body>
    <h1>Tic-Tac-Toe</h1>
    <div id = "game">
      <table id = "piece">
         <div class = "control">
          <tr  id = "board1">
              <td  id = "box" class = 'cell'></td>
              <td  id = "box" class = 'vert cell1'></td>
              <td id = "box" class = "cell2"></td>
          </tr>
          <tr id = "board2">
              <td  id = "box" class = 'hori cell3'></td>
              <td id = "box" class = "vert hori cell4"></td>
              <td id = "box" class = "hori cell5"></td>
          </tr>
          <tr id = "board3">
              <td  id = "box" class = "cell6"></td>
              <td id = "box"  class = "vert cell7"></td>
              <td  id = "box"  class = "cell8"></td>
          </tr>
        </tbody>
    </div>
      </table>
      <button id = "reset">New Game</button>
      <p id = "result">It's <span id="para-display">X</span>'s turn.</p>
      
      <p id="warning"></p>
<script src = "app.js" defer></script> 
</body>
</html>

  • Related