title: MinMax - generating game tree
body: <p>I try to write a MinMax program in Java for connect-four game, but this program should also be applicable to other games. But, I encountered a problem, which I cannot pass for few days. The values for nodes are not set properly. I am sharing my piece of code which is responsible for generating a tree.</p>
  
  <p>Maybe you will notice where I made a mistake.</p>
  
  <p>If anyone could help me with this, I will be very happy.</p>
  
  <pre><code>public Node generateTree(Board board, int depth) {
      Node rootNode = new Node(board);
      generateSubtree(rootNode, depth);
      minMax(rootNode, depth);
      return rootNode;
  }
  
  private void generateSubtree(Node subRootNode, int depth) {
      Board board = subRootNode.getBoard();
  
      if (depth == 0) {
          subRootNode.setValue(board.evaluateBoard());
          return;
      }
  
      for (Move move : board.generateMoves()) {
          Board tempBoard = board.makeMove(move);
          Node tempNode = new Node(tempBoard);
          subRootNode.addChild(tempNode);
          generateSubtree(tempNode, depth - 1);
      }
  }
  
  public void minMax(Node rootNode, int depth) {
      maxMove(rootNode, depth);
  }
  
  public int maxMove(Node node, int depth) {
      if (depth == 0) {
          return node.getValue();
      }
      int bestValue = Integer.MIN_VALUE;
      for (Node childNode : node.getChildren()) {
          int tempValue = minMove(childNode, depth - 1);
          childNode.setValue(tempValue);
          if (tempValue &gt; bestValue) {
              bestValue = tempValue;
          }
      }
      return bestValue;
  }
  
  public int minMove(Node node, int depth) {
      if (depth == 0) {
          return node.getValue();
      }
      int bestValue = Integer.MAX_VALUE;
      for (Node childNode : node.getChildren()) {
          int tempValue = maxMove(childNode, depth - 1);
          childNode.setValue(tempValue);
          if (tempValue &lt; bestValue) {
              bestValue = tempValue;
          }
      }
      return bestValue;
  }
  </code></pre>
  
  <p><strong>Board</strong> class is the representation of the board state.</p>
  
  <p><strong>Move</strong> class hold the move to perform (integer [0-8] for tic-tac-toe, [0-6] for Connect Four).</p>
  
  <p><strong>Node</strong> class holds the Move and value how good given move is. Also, holds all its children.</p>
  
  <p>In the code I use this method like this:</p>
  
  <pre><code>Node newNode = minmax.generateTree(board, depth, board.getPlayer());
  Move newMove = new TicTacToeMove(board.getPlayer(), newNode.getBestMove().getMove(), depth);
  board = board.makeMove(newMove);
  </code></pre>
  
  <p>And when it's obvious that given move is a losing move (or winning), I do not receive this move.</p>