Ejemplo n.º 1
0
        /// <summary>
        /// Calculate the heuristic for the state of the board, recursively.
        /// </summary>
        /// <param name="board">The current state of the board in the search.</param>
        /// <param name="depth">The current depth of the search.</param>
        /// <param name="nodesVisitedCount">The total number of nodes visited.</param>
        /// <param name="move">The best move.</param>
        /// <returns>The heuristic for this node in the search.</returns>
        private int CalculateMiniMaxHeuristic(Board board, int depth,
                                              ref int nodesVisitedCount, out Move move)
        {
            // safety-check the board parameter
            if (board == null)
            {
                throw new ArgumentNullException("board");
            }

            bool        myTurn       = board.CurrentColor == BoardColor;
            BoardColors currentColor = myTurn ? BoardColor :
                                       (BoardColor == BoardColors.White ? BoardColors.Black : BoardColors.White);
            int heuristic = myTurn ? Int32.MaxValue * -1 : Int32.MaxValue;

            nodesVisitedCount++;
            move = new Move(-1, -1);

            // cut short the algorithm if it's time to give up
            if (nodesVisitedCount >= nodesVisitedLimit)
            {
                return(0);
            }

            // at the bottom of the tree, just calculate the value
            if (depth <= 0)
            {
                return(CalculateMiniMaxHeuristic(board));
            }

            for (int row = 0; row < board.BoardSize; row++)
            {
                for (int column = 0; column < board.BoardSize; column++)
                {
                    Move  newMove  = new Move(row, column);
                    Board newBoard = board.CheckMove(BoardColor, newMove);
                    if (newBoard != null)
                    {
                        Move deeperMove;                         // we only care about moves in the top level
                        int  newHeuristic = CalculateMiniMaxHeuristic(newBoard,
                                                                      depth - 1, ref nodesVisitedCount, out deeperMove);
                        if (nodesVisitedCount >= nodesVisitedLimit)
                        {
                            move = newMove;
                            return(0);
                        }
                        if ((myTurn && (newHeuristic > heuristic)) ||
                            (!myTurn && (newHeuristic < heuristic)))
                        {
                            move      = newMove;
                            heuristic = newHeuristic;
                        }
                    }
                }
            }

            return(heuristic);
        }