Search code examples
javascripttic-tac-toe

TicTacToe - trouble alternating players


First mouse click gives me the expected 'x' marker but the next mouse click results in the alert ("Player o: tile has already been selected) even though the grid-item is blank. What am I doing wrong?

In the HTML body, I have created a 3x3 grid, 9 gridItems in total.

$(document).ready(function(){

        let grid = $("#grid-container") 
        let gridItem = $(".grid-item")

        function select(){ 
            for (i = 0; i < gridItem.length; i++){
                gridItem[i].addEventListener("click", function(){ 
                    if ($(this).html() == ""){
                        $(this).html("x");
                        nextSelect(); 
                    } else {alert ("Player X: tile has already been selected"); select()}
                })
            }
        }

        function nextSelect(){
            for (i = 0; i < gridItem.length; i++){
                gridItem[i].addEventListener("click", function(){  
                    if ($(this).html() == ""){
                        $(this).html("o");
                        select();
                    } else {alert ("Player o: tile has already been selected"); nextSelect()}   
                })
            }   
        }

        select()

    });   

Solution

  • The addEventListener should be executed only once. Your problem is that you're adding multiple event handlers. A possible version in the snippet bellow.

    The idea is that you only need one function and attach it to click event only once per cell, which is done with jQuery .click(callback). To manage the turns you can use a boolean variable (isTurnOfPlayerOne).

    $(document).ready(function() {
      let isTurnOfPlayerOne = true;
      $(".grid-item").click(handleClick);
    
      function handleClick() {
        if ($(this).html() == "&nbsp;") {
          let symbol = (isTurnOfPlayerOne ? "x" : "o");
          $(this).html(symbol);
        } else {
          alert("Tile has already been selected");
        }
    
        isTurnOfPlayerOne = !isTurnOfPlayerOne;
      }
    
    });
    .grid-item {
      width: 40px;
      height: 40px;
      display: inline-block;
      border: solid 1px #000;
      text-align: center;
      margin-bottom: 3px;
      line-height: 30px;
      font-size: 30px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="grid-container">
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
      <br/>
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
      <br/>
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
      <div class="grid-item">&nbsp;</div>
    </div>