Beispiel #1
0
        private (Team?WinningTeam, Point Move) BestMove(Board board)
        {
            (bool Win, Point Move)ai     = (false, new Point());
            (bool Win, Point Move)player = (false, new Point());

            var _possibleMoves = new Stack <Point>(board.PossibleMoves());

            while (_possibleMoves.Count > 0)
            {
                var possibleMove = _possibleMoves.Pop();

                if (board.IsWinningMove(possibleMove, Team.Ai))
                {
                    ai = (true, possibleMove);
                    break;
                }

                if (board.IsWinningMove(possibleMove, Team.Player))
                {
                    player = (true, possibleMove);
                }
            }

            if (!ai.Win && !player.Win)
            {
                _possibleMoves = new Stack <Point>(board.PossibleMoves());

                bool CheckMove(Point point, Team team)
                {
                    board.AddStone(point, team);

                    var winningMove = _possibleMoves
                                      .Concat(point.GetNeighbors().Where(p => !board.Stones.ContainsKey(p)))
                                      .Any(p => board.IsWinningMove(p, team));

                    board.RemoveStone(point);
                    return(winningMove);
                }

                while (_possibleMoves.Count > 0)
                {
                    var possibleMove = _possibleMoves.Pop();

                    if (CheckMove(possibleMove, Team.Ai))
                    {
                        ai = (true, possibleMove);
                    }

                    if (CheckMove(possibleMove, Team.Player))
                    {
                        player = (true, possibleMove);
                    }
                }
            }

            if (!ai.Win && !player.Win)
            {
                return(null, new Point());
            }
            if (ai.Win || (ai.Win && player.Win))
            {
                return(Team.Ai, ai.Move);
            }
            return(Team.Player, player.Move);
        }