예제 #1
0
파일: Game.cs 프로젝트: ghis9917/Breakthru
        public Game(int[,] configuration, Color PlayerChoice)
        {
            Turn = new Turn();

            GameStatus = Const.GAME_ON;

            MovesHistory = new List <Tuple <Move, int, Point> >();

            Board = new Board(configuration);

            Human = false ? Color.Empty : PlayerChoice;

            FlagshipPosition = new Point(5, 5);

            AlphaBetaSearch = new ImprovedABSearch(this);

            IterativeDeepening = new IterativeDeepening(AlphaBetaSearch);

            TranspositionTable = new TranspositionTable(Board);

            Evaluator = new Evaluation(this);

            MCEvaluator = new MonteCarloEvaluation(this);

            SearchStats = new StatsAB();

            LegalMoves = new int[11, 11];
            for (int i = 0; i < 11; i++)
            {
                for (int j = 0; j < 11; j++)
                {
                    LegalMoves[i, j] = Const.ILLEGAL_MOVE;
                }
            }
        }
예제 #2
0
파일: Game.cs 프로젝트: ghis9917/Breakthru
 public void AI()
 {
     Console.WriteLine("__________________________AI STARTS_____________________________");
     var(bestScore, bestMove) = true ? IterativeDeepening.Start() : AlphaBetaSearch.NegaMax(2, Const.MIN_VALUE, Const.MAX_VALUE);
     if (bestMove == null)
     {
         Console.WriteLine("STALEMATE");
         GameStatus = Const.GAME_OVER;
         return;
     }
     Console.WriteLine(bestMove.ToString() + "\t-->\t" + bestScore);
     MakeMove(bestMove);
 }
예제 #3
0
 private void SearchEntryPoint()
 {
     try
     {
         var bestMove = IterativeDeepening.FindBestMove(_uciClient.SearchContext);
         _uciClient.Send($"bestmove {bestMove}");
     }
     catch (Exception e)
     {
         Program.OnUnhandledException(this, new UnhandledExceptionEventArgs(e, true));
         Environment.Exit(-1);
     }
 }
예제 #4
0
        private string FormatScore(int score)
        {
            if (IterativeDeepening.IsScoreNearCheckmate(score))
            {
                var movesToCheckmate = IterativeDeepening.GetMovesToCheckmate(score);
                if (score < 0)
                {
                    movesToCheckmate = -movesToCheckmate;
                }

                return("mate " + movesToCheckmate);
            }

            return("cp " + score);
        }
예제 #5
0
        public static int TTToRegularScore(int score, int ply)
        {
            if (IterativeDeepening.IsScoreNearCheckmate(score))
            {
                if (score > 0)
                {
                    return(score - ply);
                }
                else
                {
                    return(score + ply);
                }
            }

            return(score);
        }
예제 #6
0
        private void Test(BoardState boardState, string name, int depth)
        {
            _interactiveConsole.WriteLine($" == {name}:");

            TranspositionTable.Clear();
            PawnHashTable.Clear();
            EvaluationHashTable.Clear();
            KillerHeuristic.Clear();
            HistoryHeuristic.Clear();

            var context = new SearchContext(boardState)
            {
                MaxDepth = depth
            };

            IterativeDeepening.OnSearchUpdate += IterativeDeepening_OnSearchUpdate;
            IterativeDeepening.FindBestMove(context);
            IterativeDeepening.OnSearchUpdate -= IterativeDeepening_OnSearchUpdate;

            _interactiveConsole.WriteLine();
        }
예제 #7
0
        private static void Main(string[] args)
        {
            Stopwatch stopwatch;

            TextWriter textWriter;

            var initialState = new GridState();

            initialState.Agent = new Position(0, 0);
            initialState.Puzzles.Add(new Tuple <Position, string>(new Position(1, 0), "a"));
            initialState.Puzzles.Add(new Tuple <Position, string>(new Position(1, 1), "b"));
            initialState.Puzzles.Add(new Tuple <Position, string>(new Position(1, 2), "c"));

            var goalState = new GridState();

            goalState.Puzzles.Add(new Tuple <Position, string>(new Position(1, 1), "a"));
            goalState.Puzzles.Add(new Tuple <Position, string>(new Position(2, 1), "b"));
            goalState.Puzzles.Add(new Tuple <Position, string>(new Position(3, 1), "c"));

            var offsets = new List <Tuple <int, int> >
            {
                new Tuple <int, int>(-1, 0),
                new Tuple <int, int>(0, -1),
                new Tuple <int, int>(1, 0),
                new Tuple <int, int>(0, 1)
            };

            var actions = new List <Action>();

            foreach (var offset in offsets)
            {
                var o = offset;

                var action = new Action
                {
                    Cost = s => 1 + s.HeuristicDifference(goalState), //A* heuristic
                    Succ = s => MoveState(s, o)
                };

                actions.Add(action);
            }

            var depthFirstSearch =
                new DepthFirstSearch(initialState, goalState, actions, maxDepth: 16);

            var breadthFirstSearch =
                new BreadthFirstSearch(initialState, goalState, actions, maxDepth: 16);

            var iterativeDeepening1 =
                new IterativeDeepening(initialState, goalState, actions, depthFirstSearch, maxDepth: 16);

            var iterativeDeepening2 =
                new IterativeDeepening(initialState, goalState, actions, breadthFirstSearch, maxDepth: 16);

            var algorythms = new Dictionary <string, Search>()
            {
                { "a-star.txt", new UniformCostSearch(initialState, goalState, actions) },
                //{ "breadth-first-search.txt", breadthFirstSearch },
                //{ "depth-first-search.txt", depthFirstSearch },
                { "iterative-deepening-with-depth-first-search.txt", iterativeDeepening1 },
                //{ "iterative-deepening-with-breadth-first-search.txt", iterativeDeepening2 }
            };

            foreach (var a in algorythms)
            {
                var fileName  = a.Key;
                var algorythm = a.Value;
                //using (var textWriter = Console.Out)
                using (textWriter = File.CreateText(fileName))
                {
                    stopwatch = Stopwatch.StartNew();

                    algorythm.Execute();

                    stopwatch.Stop();

                    Print(textWriter, algorythm.Result);

                    textWriter.WriteLine("Elapsed time: {0}", stopwatch.Elapsed);
                    textWriter.WriteLine("Number of visited states: {0}", algorythm.VisitedStatesCounter);
                    System.Console.WriteLine("the end of " + a.Key);
                }
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connect Four Artificial Intelligence\n");

            Game  game  = new Game(6, 7);
            State state = game.GetInitialState();

            //AdversarialSearch<State, tictactoe.Action> minimaxSearch = new MinimaxSearch<State, tictactoe.Action, Player>(game);
            //AdversarialSearch<State, tictactoe.Action> minimaxSearch = new MinimaxSearchLimited<State, tictactoe.Action, Player>(game, 2);
            AdversarialSearch <State, connectfour.Action> minimaxSearch = new IterativeDeepening <State, connectfour.Action, Player>(game, IterativeDeepening <State, connectfour.Action, Player> .Algorithm.Minimax, 10000);



            while (game.IsTerminal(state) == false)
            {
                Console.WriteLine("\n" + state.ToString());
                Console.Write("You are Blue, select a column (starting from 0): ");
                String input = Console.ReadLine();
                int    col   = Convert.ToInt32(input.Substring(0, 1));

                //Determinare la riga sapendo la colonna
                int row = -1;
                for (int i = 0; i < state.Rows; i++)
                {
                    if (state.GetBoardValue(i, col) == State.EMPTY)
                    {
                        row = i;
                        break;
                    }
                }

                state = game.GetResult(state, new connectfour.Action(row, col));

                if (game.IsTerminal(state))
                {
                    break;
                }

                Console.WriteLine("\n" + state.ToString());

                Console.WriteLine("AI is thinking about its next move...");


                var watch = System.Diagnostics.Stopwatch.StartNew();
                connectfour.Action action = minimaxSearch.makeDecision(state);
                watch.Stop();

                Console.WriteLine($"Selected action: Col={action.Col}");
                Console.WriteLine($"Expanded nodes: {minimaxSearch.getMetrics().Get(MinimaxSearch<State, tictactoe.Action, Player>.METRICS_NODES_EXPANDED)}");
                Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms\n");


                state = game.GetResult(state, action);
            }

            Console.WriteLine("\n" + state.ToString());

            if (game.HasWon(state, Player.Blue))
            {
                Console.WriteLine("\nYOU WON, CONGRATULATIONS!!!");
            }
            else if (game.HasWon(state, Player.Red))
            {
                Console.WriteLine("\nAI won, try again!");
            }
            else
            {
                Console.WriteLine("\nIt's a tie, not bad!");
            }
        }