/// <summary> /// Makes a move for the given player in the given board /// </summary> /// <param name="board">The board</param> /// <param name="player">The player</param> public BoardMove MakeMove(Board board, BoardTileType player) { var move = new BoardMove(-1, -1); this.Minimax(player, board, player, out move); return(move); }
/// <summary> /// Calculates the best move for the given player /// </summary> /// <param name="player">The player</param> /// <param name="board">The board</param> /// <param name="turnPlayer">The current player in the turn</param> /// <param name="move">The move to make</param> /// <returns>The score</returns> private int Minimax(BoardTileType player, Board board, BoardTileType turnPlayer, out BoardMove move) { var winner = board.GetWinner(); if (winner != null) { move = new BoardMove(-1, -1); return(this.Score(player, winner.Value)); } var scores = new List <int>(); var moves = new List <BoardMove>(); //Go through all possible games from the current board foreach (var possibleMove in board.GetMoves()) { var possibleBoard = board.WithMove(possibleMove.X, possibleMove.Y, turnPlayer); scores.Add(this.Minimax(player, possibleBoard, this.NextPlayer(turnPlayer), out move)); moves.Add(possibleMove); } if (player == turnPlayer) { //Max calculation var maxIndex = FindBestIndex(scores, (x, y) => x > y); move = moves[maxIndex]; return(scores[maxIndex]); } else { //Min calculation var minIndex = FindBestIndex(scores, (x, y) => x < y); move = moves[minIndex]; return(scores[minIndex]); } }