title: simplest MiniMax algorithm for TicTacToe AI in Java
body: <p>I was trying to get a grasp of MiniMax algorithm, and have read up on it. My initial approach was to implement a simple MiniMax algorithm, and then to add alpha-beta pruning. However this is my current code: </p>
  
  <pre><code>public int miniMax(char[] node, int playerNum)
  {
      int victor = checkWin(node); // returns 0 if game is ongoing, 1 for p1, 2 for p2, 3 for tie.
      if(victor != 0) //game over .
          return score(victor);   
  
      if(playerNum == 2) //AI
      {
          int bestVal = Integer.MIN_VALUE;
          int bestSpot = 0;
          for(int i = 0; i &lt; node.length; i++)
          {
              if(node[i] != '-')
                  continue;
              node[i] = getSymbol(playerNum);
              int value = miniMax(node, 1); 
              if(value &gt; bestVal)
              {
                  bestVal = value;
                  bestSpot = i;
              }
  
              node[i] = '-';
          }
          return bestSpot;
      }
      else
      {
          int bestVal = Integer.MAX_VALUE;
          int bestSpot = 0;
          for(int i = 0; i &lt; node.length; i++)
          {
              if(node[i] != '-')
                  continue;
              node[i] = getSymbol(playerNum);
              int value = miniMax(node, 2); 
              if(value &lt; bestVal)
              {
                  bestVal = value;
                  bestSpot = i;
              }
              node[i] = '-';
          }
          return bestSpot;
      }
  }
  </code></pre>
  
  <p>And my score function </p>
  
  <pre><code>private int Score(int gameState)
  {
      if(gameState ==2) //O wins.
          return 10;
      else if(gameState==1) //X wins
          return -10;
      return 0;
  }
  </code></pre>
  
  <p>Now, I have a working AI that tries to block my move and win, however sometimes it is making non-intelligent choices for instance this is the output I get if my input read from console is 6,7,8 in that order. It does not attempt to block my win. But in other cases it does.</p>
  
  <hr>
  
  <p>|   O  |   O  |      | </p>
  
  <hr>
  
  <p>|      |      |      | </p>
  
  <hr>
  
  <p>|   X  |   X  |   X  | </p>
  
  <hr>
  
  <p>In my second attempt I tried 4,3 and it blocked my winning move.</p>
  
  <hr>
  
  <p>|      |   O  |      | </p>
  
  <hr>
  
  <p>|   X  |   X  |   O  | </p>
  
  <hr>
  
  <p>|      |      |      | </p>
  
  <hr>
  
  <p>I was wondering anyone could point out what is wrong with my implementation?</p>