1

I have tried so many concepts but finally not able to conclude the answer. I have made a tic-tac-toe game, which is fully functioning but I have a problem where, when I my winning status is displayed on windisplay column, after that also I am able to take input from user.

I want to disable my boxes click when a winner is found.

const GameBoard = (() => {
    const PlayerFactory = (name, mark, turn) => {
        return { name, mark, turn }
    };

    var p1arr = [];
    var p2arr = [];
    const player1 = PlayerFactory("Player 1", "X", true);
    const player2 = PlayerFactory("Player 2", "O", false);

    const windisplay = document.querySelector('.win-display');

    var boxes = document.getElementsByClassName("box");

    let gameover = false;

    if (gameover) {
        return;
    }
    
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].addEventListener("click", function () {
            boxClicked(this);
        });

    }

    function boxClicked(box) {
        if (box.innerHTML === "") {
            if (player1.turn === true) {
                box.textContent = player1.mark;
                // alert("Kaam 1 ho gya");
                p1arr[box.id] = player1.mark;
                console.log(p1arr);
                player1.turn = false;
                player2.turn = true;
                checkwinner();
            }
            else if (player2.turn === true) {
                box.textContent = player2.mark;
                // alert("Kaam 2 ho gya");
                p2arr[box.id] = player2.mark;
                console.log(p2arr);
                player1.turn = true;
                player2.turn = false;
                checkwinner();
            }
        } else {
            console.log("This box is already occupied!");
        }
    }

    const winCombos = [
        [0, 1, 2],
        [0, 3, 6],
        [3, 4, 5],
        [6, 7, 8],
        [1, 4, 7],
        [2, 4, 6],
        [2, 5, 8],
        [0, 4, 8]
    ];

    function checkwinner() {
        // Check if any winCombos match the numbers in array1
        var isWinner1 = checkWinCombos(p1arr);
        if (isWinner1) {
            console.log("Winner is X! ");
            windisplay.textContent = "Winner is X! ";
            gameover = true;
        }

        // Check if any winCombos match the numbers in array2
        var isWinner2 = checkWinCombos(p2arr);
        if (isWinner2) {
            console.log("Winner is O!");
            windisplay.textContent = "Winner is O! ";
            gameover = true;
        }


        // Function to check if any winCombos match the given array
        function checkWinCombos(array) {
            for (var i = 0; i < winCombos.length; i++) {
                var combo = winCombos[i];
                var isMatch = true;
                for (var j = 0; j < combo.length; j++) {
                    if (!array[combo[j]]) {
                        isMatch = false;
                        break;
                    }
                }
                if (isMatch) {
                    return true;
                }
            }
            return false;
        }

        // Function to count occurrences of 'X' and 'O' in an array
        function countOccurrences(array, symbol) {
            let count = 0;
            for (let i = 0; i < array.length; i++) {
                if (array[i] === symbol) {
                    count++;
                }
            }
            return count;
        }

        // Count the occurrences of 'X' and 'O' in both arrays
        const oCount = countOccurrences(p1arr, 'O') + countOccurrences(p2arr, 'O');
        const xCount = countOccurrences(p1arr, 'X') + countOccurrences(p2arr, 'X');

        // Check if all 9 boxes are occupied
        if (xCount + oCount === 9) {
            console.log('Tie!');
            windisplay.textContent = "Tie!";
        }

    }

    let resetbutton = document.querySelector('.reset')
    resetbutton.addEventListener('click', function () {
        // alert("Kaam ho gya!");
        resetgame();
    });

    function resetgame() {
        p1arr = [];
        p2arr = [];
        for (var i = 0; i < boxes.length; i++) {
            boxes[i].innerHTML = "";
        }
        windisplay.textContent = "";
    }

})();
halfer
  • 19,824
  • 17
  • 99
  • 186
Ujjawal
  • 51
  • 4

1 Answers1

2

This is the wrong place to check if the game is over, as obviously you've just set it to false:

let gameover = false;

if (gameover) {
    return;
}

In below code, the event listener for the box click is wrapped inside an if condition if (!gameover) to check if the game is already over. Like this:

let gameover = false;

for (var i = 0; i < boxes.length; i++) {
  boxes[i].addEventListener("click", function () {
    if (!gameover) {
      boxClicked(this);
    }
  });
}
trincot
  • 317,000
  • 35
  • 244
  • 286
Y Nawodya
  • 55
  • 6
  • 1
    Answer is correct just add a code in reset function : `gameover = false`. Another problem in this code is that when the winner is decided at last step(i.e. 9th box) it shows both answers : 1. Winner is __ ! and 2. Tie ! , I want to remove this tie message. Try it if you can make it possible with this code. – Ujjawal Jul 15 '23 at 12:08
  • 1
    try add `if (xCount + oCount === 9) { if (!isWinner1 && !isWinner2) { //...other codes ; gameover = true;}}` reason for that `if (!isWinner1 && !isWinner2)` give you idea about give Tie messege when no winner found – Y Nawodya Jul 15 '23 at 13:25
  • 1
    `gameover=true` is not initial.. but when the game was tied that meant game was ended. so it will help you to prevent unnecessary changes – Y Nawodya Jul 15 '23 at 13:35