Search code examples
javascriptif-statement

I have created Tic-Tac-Toe game. There is a problem I'm facing is whenever the game was draw it prints the score value 2 while it should print 1


I have created Tic Tac Toe Game. I am tracking the game score whenever the game was draw or win, there is a problem I'm facing is whenever the game was draw it prints the score value 2 while it should print 1. I think the problem is in the else statement, it runs two times.I have tried many ways but it couldn't solve. How can I solve this problem?

  let button = document.querySelectorAll(".box");
   let resetbtn = document.querySelector(".reset");
   let textValue = "X";
   let winMsg = document.querySelector(".msg");
   let newbtn = document.querySelector(".new");
   let moveCount = 0;
   let scoreX = 0;
   let scoreO = 0;
   let tie = 0;
   let scoreOfX = document.querySelector(".score-X");
   let scoreOfO = document.querySelector(".score-O");
   const tieResult = document.querySelector(".score-draw");

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

   const resetgame = ()=>{
   moveCount = 0;
   textValue = "X";
   enableBox();
   winMsg.innerText="";
   newbtn.classList.add("hide");
  };

    button.forEach((box) =>{ 
      box.addEventListener("click", ()=>{
        if(textValue === "X"){
          textValue = "O";
          box.innerText ="X";
          box.style.color="green";
          winMsg.innerText = "Player(O) " ;
          newbtn.classList.add("hide");
          }else{
           textValue = "X";
           box.innerText = "O";
           box.style.color="red";
           winMsg.innerText = "Player(X) " ;
           newbtn.classList.add("hide");
        }
            box.disabled =true;
            moveCount++;
            console.log(moveCount, box.innerText );
            checkWinner(); 
        });
     });

     const disabledBox =()=>{
        for(let box of button){
           box.disabled=true;        
     }}; 

     const enableBox =()=>{
       for(let box of button){
         box.disabled=false;
         box.innerText="";
     }
     }

     const showWinner = (winner)=>{
      winMsg.innerText=`Congratulations Winner is  ${winner}`;
      newbtn.classList.remove("hide");
      if(winner === "X"){
      scoreX ++;
      scoreOfX.innerText = scoreX;
      }else{
      scoreO++;
      scoreOfO.innerText = scoreO;
     }
      disabledBox();
   };

    const checkDraw = (moveCount)=>{
     winMsg.innerText="Game was Draw! Play Again";
     newbtn.classList.remove("hide");
     disabledBox();
    }

     const checkWinner = ()=>{
       for(let pattern of winPatterns){     
         let pos1 =  button[pattern[0]].innerText;
         let pos2 =  button[pattern[1]].innerText;
         let pos3 =  button[pattern[2]].innerText;
         if(pos1!= "" && pos2!= "" && pos3!=""){
         if(pos1 === pos2 && pos2 === pos3){
           showWinner(pos1);
          }else{
            if(pos1 !== pos2 && pos2 !== pos3 ){
             if(moveCount === 9){
               checkDraw(moveCount);
               tie ++;
               tieResult.innerText = tie;
             }
           }
          }
        }
       }
    };
     newbtn.addEventListener("click",resetgame);
     resetbtn.addEventListener("click",()=>{
     console.log("reset");
     scoreO = 0 ;
     scoreOfO.innerText = scoreO;
     scoreX = 0 ;
     scoreOfX.innerText = scoreX;
     tie = 0;
     tieResult.innerText = tie;
     resetgame();
     });
<main>
    <h1>Tic Tac Toe </h1>
       <div>
        <p class="msg"></p>
        <button class="new hide"> New Game </button>
       </div>
       
       <div class="container">
        <div class="game">
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
            <button class="box"></button>
        </div>
       </div>
       <div class="elements">
       <div class="scores1">
       <h3 class="score-X">0</h3>
       <h2 class="play-x">Player X</h2>
       </div>
       <div class="scores2">
       <h3 class="score-O">0</h3>
       <h2 class="play-o">Player O</h2>
       </div>
       <div class="scores3">
       <h3 class="score-draw">0</h3>
       <h2 class="play-draw">Tie</h2>
       </div>
       </div>
    <button class="reset">Reset Button</button>
</main>


Solution

  • You don't need to check for pos1 === pos2 && pos2 === pos3 twice. I believe your issue is coming from checking for if(moveCount === 9){ inside the for...of loop, which could make it execute multiple times. I've cleaned up the code for you, which should fix the issue.

    const checkWinner = () => {
      let winFound = false;
      for(let pattern of winPatterns) {     
        let pos1 = button[pattern[0]].innerText;
        let pos2 = button[pattern[1]].innerText;
        let pos3 = button[pattern[2]].innerText;
        if(pos1 === pos2 && pos2 === pos3) {
          winFound = true;
          showWinner(pos1);
        }
      }
    
      if(!winFound && moveCount === 9) {
        checkDraw(moveCount);
        tie++;
        tieResult.innerText = tie;
      }
    };