private void MeasureStrength(object md) { MoveData data = (MoveData)md; strengths[data.Move] = moveStrength(data.Board, data.Move, data.Depth); }
// Same minimax algorithm but optimized with multithreading private Board FasterMiniMax_Bot(Board b, int depth) { Array.Fill(strengths, -1); Console.WriteLine("\nthinking...\n"); int bestWinningMove = -1; int bestWinningMoveStrength = 0; int bestAlternateMove = -1; int bestAlternateMoveStrength = 1000; depth += (7 - b.ValidMoveCount()); Console.WriteLine("Searching at depth " + depth + "..."); List <Thread> threads = new List <Thread>(); for (int i = 0; i < 7; i++) { Thread t = new Thread(new ParameterizedThreadStart(MeasureStrength)); MoveData data = new MoveData(b, i, depth); t.Start(data); threads.Add(t); } foreach (var thread in threads) { thread.Join(); } for (int move = 0; move < 7; move++) { //int strength = moveStrength(b, move, depth); if (strengths[move] != -1) { Console.WriteLine("Strength of move " + move + ": " + strengths[move]); if ((strengths[move] / 100) == 2 && strengths[move] > bestWinningMoveStrength) { bestWinningMove = move; bestWinningMoveStrength = strengths[move]; } else if (strengths[move] == 0 || ((strengths[move] / 100) == 1 && strengths[move] < bestAlternateMoveStrength)) { bestAlternateMove = move; bestAlternateMoveStrength = strengths[move]; } } } if (bestWinningMove != -1) // if there is a winning move to play, play the strongest one { //Console.WriteLine("\npursuing winning move: " + bestWinningMove); b.AddPiece(2, bestWinningMove); return(b); } else // if there is no winning move, play the optimal alternate one { //Console.WriteLine("\npursuing optimal alternate move: " + bestAlternateMove + " (strength " + bestAlternateMoveStrength + ")"); b.AddPiece(2, bestAlternateMove); return(b); } }