public void AIMakeTurn(int ply, Board b, int turn) { PossibleMove move = this.ProduceBest(ply, b, turn); // Debug.Log("move = " + move.x + "," + move.y); b.AddPiece(move.x, move.y, turn); AI.TakeTurn(move.x, move.y, turn, b); }
public PossibleMove AlphaBeta (BoardNode node, int depth, PossibleMove alpha, PossibleMove beta, bool maximizingPlayer) { if (depth == 0) // || node.IsLeaf) { // Debug.Log("node._move[0] = " + node._move.x); // test node collection here { return(new PossibleMove(node._move.x, node._move.y, BoardNode.GetHeuristicValue(node, depth))); } if (maximizingPlayer == true) { // Debug.Log("Max"); List <PossibleMove> childs = CheckLegalMoves(node._bData, 1); // List<BoardNode> children = BoardNode.GetChildren(node, 1); PossibleMove score; foreach (PossibleMove kid in childs) { var bn = BoardNode.GetChild(node._bData, kid, 1); score = AlphaBeta(bn, depth - 1, alpha, beta, !maximizingPlayer); alpha = alpha.score == Mathf.Max(alpha.score, score.score) ? alpha : score; alpha.x = kid.x; alpha.y = kid.y; if (beta.score <= alpha.score) { break; // beta cut-off } } // Debug.Log("alpha = " + alpha.score); return(alpha); } else { // Debug.Log("Min"); List <PossibleMove> childs = CheckLegalMoves(node._bData, 0); // List<BoardNode> children = BoardNode.GetChildren(node, 0); PossibleMove score; foreach (PossibleMove kid in childs) { var bn = BoardNode.GetChild(node._bData, kid, 0); score = AlphaBeta(bn, depth - 1, alpha, beta, !maximizingPlayer); beta = beta.score == Mathf.Min(beta.score, score.score) ? beta : score; // beta = min(beta,score) beta.x = kid.x; beta.y = kid.y; if (beta.score <= alpha.score) { break; // alpha cut-off } } // Debug.Log("beta = " + beta.score); return(beta); } }
// randomize list function public static void ShufflePossibleMovesList(List <PossibleMove> list) { System.Random rng = new System.Random(); int n = list.Count; while (n > 1) { n--; int k = rng.Next(n - 1); PossibleMove value = list[k]; list[k] = list[n]; list[n] = value; } }
public static List <PossibleMove> CheckLegalMoves(Board b, int turn) { var legal = new List <PossibleMove>(); for (int i = 0; i < b._size; i++) { for (int j = 0; j < b._size; j++) { if (CheckCurrent(i, j, turn, b)) { PossibleMove temp = new PossibleMove(i, j, int.MinValue); legal.Add(temp); } } } AI.ShufflePossibleMovesList(legal); return(legal); }
public PossibleMove ProduceBest(int level, Board b, int color) { // ensure a current working board Board scratchBoard = new Board(b._size); Board.CopyBoard(scratchBoard, b); BoardNode root = new BoardNode(scratchBoard); // root._turn = (color == 1) ? 0 : 1; // Start alphabeta algorithm and store the best H value PossibleMove bestH = this.AlphaBeta(root, level, new PossibleMove(-1, -1, int.MinValue), new PossibleMove(-1, -1, int.MaxValue), true); // Debug.Log("ProduceBest = " + bestH.x + ", " + bestH.y + ", score = " + bestH.score); return(bestH); }