Example #1
0
 public MinMaxAlgorithm(PlayerController MaxPlayer, EvaluationFunction eval, UtilityFunction utilf, PlayerController MinPlayer)
 {
     this.MaxPlayer   = MaxPlayer;
     this.MinPlayer   = MinPlayer;
     this.evaluator   = eval;
     this.utilityfunc = utilf;
 }
Example #2
0
    public Pentago_Rules(EvaluationFunction ef = EvaluationFunction.control, NextStatesFunction nsf = NextStatesFunction.all_states, bool iapieces = IA_PIECES_WHITES, bool remove_repeated_states_on_nextStates = false, float draw_value = 0)
    {
        this.ef  = ef;
        this.nsf = nsf;
        this.remove_repeated_states_on_nextStates = remove_repeated_states_on_nextStates;
        this.draw_value = draw_value;

        IA_PIECES = iapieces;
        if (ef == EvaluationFunction.AplusDiagHack)
        {
            setUpDiagonalHack();
        }

        //create all possible plays.
        //since we are using a class, there is no need to initialize them again
        //when we are getting possible moves in a board
        //just filter the impossible ones

        if (all_possible_place_piece_moves == null)
        {
            all_possible_place_piece_moves = new Pentago_Move[36];
            int i = 0;
            for (int s2p = 0; s2p < 4; s2p++)
            {
                for (int x = 0; x < 3; x++)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        all_possible_place_piece_moves[i] = new Pentago_Move(s2p, x, y);
                        i++;
                    }
                }
            }
        }

        if (nsf == NextStatesFunction.check_symmetries)
        {
            bakeMovesAntiDiagAbove();
            bakeMovesMainDiagAbove();
            bakeMovesSquare0Triang();
            bakeMovesTopTriang();
            bakeSquare0();
            bakeSquare0n1();
            bakeSquare0n2();
        }

        if (all_possible_rotate_squares_moves == null)
        {
            all_possible_rotate_squares_moves = new Pentago_Move[8];
            int i = 0;
            for (int s2p = 0; s2p < 4; s2p++)
            {
                all_possible_rotate_squares_moves[i] = new Pentago_Move(s2p, false);
                i++;
                all_possible_rotate_squares_moves[i] = new Pentago_Move(s2p, true);
                i++;
            }
        }
    }
Example #3
0
 public override void Evaluation(EvaluationFunction evaluationFunction, Population population)
 {
     EvaluationFunction = evaluationFunction;
     Generation         = new List <List <Town> >(population.CreatGreedyGeneration());
     var query = Generation.AsParallel().Select(x => MakeGreedy(x)).ToList();
     //FinalScore = query.Select(x => evaluationFunction.EvaluateSpecimen(x)).ToList();
     //FinalScore.Sort();
 }
Example #4
0
    private void InitAI()
    {
        MoveMaker          myStrategy = null;
        EvaluationFunction eval       = null;
        UtilityFunction    ufunc      = null;

        ////////////////
        // your code here to initialize the MinMax algorithm
        // 1. Evaluation function
        // 2. Utility function
        // 3. Strategy (MinMax and MinMax Alpha Beta)
        ///////////////
        switch (evalfunc)
        {
        case EvaluatationFunc.Eval:
            eval = new EvaluationFunction();
            break;

        default:
            Debug.Log("Not an option");
            break;
        }

        switch (utilfunc)
        {
        case UtilityFunc.Util:
            ufunc = new UtilityFunction();
            break;

        default:
            Debug.Log("Not an option");
            break;
        }

        switch (strategy)
        {
        case TypeStrategy.RandomStrategy:
            myStrategy = new RandomSolution(this, GameManager.instance.GetAdversary(this));
            break;

        case TypeStrategy.MinMax:
            myStrategy = new MinMaxAlgorithm(this, eval, ufunc, GameManager.instance.GetAdversary(this));
            break;

        default:
            Debug.Log("Not an option");
            break;
        }

        moveMaker = myStrategy;
    }
Example #5
0
        public static IEnumerable <T> Sequence <T>(
            this IExpressionEvaluator <T> evaluator,
            T seed,
            EvaluationFunction <T> function,
            EvaluationPredicate <T>?predicate = null
            ) where T : struct, IComparable <T>, IEquatable <T>
        {
            var index   = 0;
            var current = seed;

            while (predicate?.Invoke(evaluator, current, index) ?? true)
            {
                yield return(current);

                current = function(evaluator, current, index);
                index++;
            }
        }
Example #6
0
    public Pentago_Rules(EvaluationFunction ef = EvaluationFunction.func1, NextStatesFunction nsf = NextStatesFunction.all_states, bool iapieces = IA_PIECES_WHITES, bool remove_repeated_states_on_nextStates = false)
    {
        this.ef  = ef;
        this.nsf = nsf;
        this.remove_repeated_states_on_nextStates = remove_repeated_states_on_nextStates;

        IA_PIECES = iapieces;

        //create all possible plays.
        //since we are using a class, there is no need to initialize them again
        //when we are getting possible moves in a board
        //just filter the impossible ones

        if (all_possible_place_piece_moves == null)
        {
            all_possible_place_piece_moves = new Pentago_Move[36];
            int i = 0;
            for (int s2p = 0; s2p < 4; s2p++)
            {
                for (int x = 0; x < 3; x++)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        all_possible_place_piece_moves[i] = new Pentago_Move(s2p, x, y);
                        i++;
                    }
                }
            }
        }
        if (all_possible_rotate_squares_moves == null)
        {
            all_possible_rotate_squares_moves = new Pentago_Move[8];
            int i = 0;
            for (int s2p = 0; s2p < 4; s2p++)
            {
                all_possible_rotate_squares_moves[i] = new Pentago_Move(s2p, false);
                i++;
                all_possible_rotate_squares_moves[i] = new Pentago_Move(s2p, true);
                i++;
            }
        }
    }
Example #7
0
        private List <Town> MakeGreedy(List <Town> specimen)
        {
            var startingTown = specimen[0];
            var visitedTowns = new HashSet <Town>
            {
                startingTown
            };
            var currentTown = startingTown;

            while (visitedTowns.Count < specimen.Count)
            {
                var minDistance = Double.MaxValue;
                var minTown     = new Town();

                foreach (var town in specimen)
                {
                    if (visitedTowns.Contains(town))
                    {
                        continue;
                    }

                    var distance = EvaluationFunction.CountDistance(currentTown, town);
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        minTown     = town;
                    }
                }

                if (minTown.Numer == 0)
                {
                    throw new Exception("Haven't found the closest town");
                }

                visitedTowns.Add(minTown);
                currentTown = minTown;
            }

            return(visitedTowns.ToList());
        }
        public void FindBestMove_BoardIsCleanAndThereAre2ValidMoves_ReturnsMoveAfterWhichKnightCanMakeTheLeastNumberOfMoves()
        {
            var evaluationFunction = new EvaluationFunction();
            var cleanBoard         = CleanBoardGenerator.CreateCleanBoardOfSize(Constants.BoardSize);
            var actualBestMove     = new Move()
            {
                X = 0, Y = 0
            };
            // После хода в клетку (0, 0) у коня есть только 1 возможный ход, а после хода в клетку (4, 3) - 7
            var validMoves = new List <Move>
            {
                actualBestMove,
                new Move()
                {
                    X = 4, Y = 3
                }
            };

            var result = evaluationFunction.FindBestMove(cleanBoard, validMoves);

            Assert.That(result, Is.EqualTo(actualBestMove));
        }
Example #9
0
        static void Main(string[] args)
        {
            var random        = new Random();
            var startPosition = new Point(random.Next(0, 8), random.Next(0, 8));
            var knight        = new Knight(startPosition);
            var consoleUi     = new UserInterface();

            IBestMoveFinder algorithm = new EvaluationFunction();
            var             game      = new ChessGame(knight, algorithm);

            consoleUi.PlayAndShow(game);
            Console.WriteLine("Это был алгоритм, использующий функцию оценки.");
            Console.WriteLine("Нажмите на любую клавишу 2 раза, чтобы запустить следующий алгоритм.");

            Console.ReadKey();
            Console.ReadKey();

            algorithm = new RandomMoveTaker();
            knight.CurrentPosition = startPosition;
            game = new ChessGame(knight, algorithm);
            consoleUi.PlayAndShow(game);
            Console.WriteLine("Это был алгоритм, выбирающий случайный ход.");
        }
Example #10
0
        public override List <Town> Selection(List <List <Town> > list)
        {
            var participants = new List <(List <Town> Specimen, double Score)>();

            List <Town> bestParticipant = new List <Town>(list[0]);
            var         score           = Double.MaxValue;

            for (int i = 0; i < ParticipantsNumber; i++)
            {
                var randomNumber = Extensions.GenereteRandom() * list.Count;
                var parseHelper  = (int)Math.Floor(randomNumber);
                var scoreHelper  = EvaluationFunction.EvaluateSpecimen(list[parseHelper]);
                if (scoreHelper < score)
                {
                    bestParticipant = new List <Town>(list[parseHelper]);
                    score           = scoreHelper;
                }
            }



            return(bestParticipant);
        }
 public RecursiveBestFirstSearch(EvaluationFunction ef)
 {
     evaluationFunction = ef;
 }
Example #12
0
 public BestFirstSearch(QueueSearch search, EvaluationFunction ef)
 {
     this.search = search;
     evaluationFunction = ef;
 }
Example #13
0
 private void evaluationFunction_ComboBox_SelectionChangeCommitted(object sender, EventArgs e)
 {
     evaluationFunction = (EvaluationFunction)evaluationFunction_ComboBox.SelectedValue;
 }
Example #14
0
        private void InitializeReversi()
        {
            if (thread != null)
            {
                thread.Abort();
                thread = null;
            }

            if (thread2 != null)
            {
                thread2.Abort();
                thread2 = null;
            }

            size = int.Parse(size_ComboBox.Text);
            pattern = (Pattern)pattern_ComboBox.SelectedItem;
            phase = 0;
            turn = State.Black;
            board = new Board(size, pattern);
            boardForResize = board.Clone();
            players = new Dictionary<State, Player>();
            players[State.Black] = (Player)blackPlayer_ComboBox.SelectedValue;
            players[State.White] = (Player)whitePlayer_ComboBox.SelectedValue;
            linkedPosition = LinkedPosition.Out;
            linkedPositionByHuman = LinkedPosition.Out;
            seed_ComboBox.Items[0] = Environment.TickCount;
            seed = int.Parse(seed_ComboBox.Text);
            random = new Random(seed);
            start_CheckBox.Checked = false;
            history_ComboBox.Items.Clear();
            history_ComboBox.Items.Add(phase);
            iteration = int.Parse(iteration_ComboBox.Text);
            alphaBetaDepth = int.Parse(alphaBetaDepth_ComboBox.Text);
            evaluationFunction = (EvaluationFunction)evaluationFunction_ComboBox.SelectedValue;
            iterativeDeepeningDepth = int.Parse(iterativeDeepeningDepth_ComboBox.Text);
            basePlayer = (Player)basePlayer_ComboBox.SelectedValue;
            movablePositions = board.MovablePositions(turn);

            board_PictureBox.Image = BoardImage(board);
            information_PictureBox.Image = InformationImage(board, turn);
            phase_ExtendedLabel.Text = PhaseText();
            text_ExtendedLabel.Text = StartText();
            _ProgressBar.Value = 0;
            _ProgressBar.Style = ProgressBarStyle.Blocks;
            log_TextBox.Text = StartText() + Environment.NewLine + Environment.NewLine;

            start_CheckBox.Enabled = true;
        }
Example #15
0
 public BestFirstSearch(QueueSearch search, EvaluationFunction ef)
 {
     this.search        = search;
     evaluationFunction = ef;
 }
	public RecursiveBestFirstSearch(EvaluationFunction ef) {
		evaluationFunction = ef;
	}