// after we get the best move (button) we return this button to perform click public Button performMove(int[,] board) { AiMove bestMove = getBestMove(board, _aiplayer); board[bestMove.x, bestMove.y] = _aiplayer; Button bt = new Button(); bt.Text = "O"; bt.Name = "b" + bestMove.x.ToString() + bestMove.y.ToString(); return(bt); }
// apply minimax algorithm private AiMove getBestMove(int[,] board, int player) { // base case --> check for end state (win,lose,draw) int result = iswinner(board); if (result == _aiplayer) { AiMove temp = new AiMove(); temp.SetScore(10); return(temp); } else if (result == _humanplayer) { AiMove temp = new AiMove(); temp.SetScore(-10); return(temp); } else if (result == TIE) { AiMove temp = new AiMove(); temp.SetScore(0); return(temp); } List <AiMove> moves = new List <AiMove>(); // Do the recursive function calls and construct the moves list (all availabe moves) for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i, j] == NO_VALUE) { AiMove move = new AiMove(); move.x = i; move.y = j; board[i, j] = player; if (player == _aiplayer) { move.score = getBestMove(board, _humanplayer).score; } else { move.score = getBestMove(board, _aiplayer).score; } moves.Add(move); board[i, j] = NO_VALUE; } } } // get the best move for the current player int bestMove = 0; if (player == _aiplayer) { int bestScore = -100000; for (int i = 0; i < moves.Count; i++) { if (moves[i].score > bestScore) { bestScore = moves[i].score; bestMove = i; } } } else { int bestScore = 100000; for (int i = 0; i < moves.Count; i++) { if (moves[i].score < bestScore) { bestScore = moves[i].score; bestMove = i; } } } // return the best move return(moves[bestMove]); }