-3

I'm trying to implement a code that decides who is the winner but I can't figure out how to do that. I was try using conditionals and forEach to solve the problem, but seeing tutorials on internet about how to code this game, I think that my code isn't very good. The mayority of the code is intended to be created with module pattern and factory functions. I will leave my code below:

let displayController = (function () {
  let tableCells = document.querySelectorAll(".table-cell");
  let resetButton = document.querySelector(".reset-button");

  tableCells.forEach((element, index) => {
    element.setAttribute("data-index", index + 1);
  });

  return {
    tableCells: tableCells,
    resetButton: resetButton,

    addUserChoose: function (array, obj) {
      array.push(obj);
    },

    renderUserChoose: function (element, cssClassName) {
      element.id = cssClassName;
    },

    resetGame: function (array) {
      tableCells.forEach((element) => {
        element.removeAttribute('id')
        array.length = [];
      });
    },

    itsATie: function(){
      console.log('Its a tie!')
    }
  };

})();

let gameBoard = (function () {
  let tableCells = displayController.tableCells;
  let resetButton = displayController.resetButton;
  let gameBoardSelections = [];

  tableCells.forEach((element) => {
    element.addEventListener("click", (e) => {

      let playerIndex = element.dataset.index;
      let lastElement = gameBoardSelections.length - 1;

      if (gameBoardSelections.length == 0 ) {
        let player = playerFactory("X", playerIndex);
        displayController.addUserChoose(gameBoardSelections, player);
        displayController.renderUserChoose(element, "userChooseX");
      }else if(gameBoardSelections.length == 9){
        displayController.itsATie()
        
      } else if (gameBoardSelections[lastElement].playerOption == "X" && gameBoardSelections[lastElement].markedCell != playerIndex) {
        let player = playerFactory("O", playerIndex);
        displayController.addUserChoose(gameBoardSelections, player);
        displayController.renderUserChoose(element, "userChooseO");

      } else if (gameBoardSelections[lastElement].playerOption == "O" && gameBoardSelections[lastElement].markedCell != playerIndex ) {
        let player = playerFactory("X", playerIndex);
        displayController.addUserChoose(gameBoardSelections, player);
        displayController.renderUserChoose(element, "userChooseX");
      }
      
    });
  });

  resetButton.addEventListener("click", () => {
    displayController.resetGame(gameBoardSelections);
  });
})();

function playerFactory(option, cellIndex) {
  let playerOption = option;
  let markedCell = cellIndex;
  return { playerOption, markedCell };
}

I was try using conditionals and forEach and trying to putting it in another function to run it. It expect to create the logic that decides who is the winner when the player select a complete row, column or diagonal.

0 Answers0