コード例 #1
0
    public IEnumerator StartMinimax()
    {
        yield return(new WaitUntil(() => this.legalJumps != null));

        foreach (NewTileScript tile in previousTiles)
        {
            if (legalJumps.Contains(tile))
            {
                legalJumps.Remove(tile);
            }
        }
        if (legalJumps.Count > 0)
        {
            foreach (NewTileScript jump in legalJumps)
            {
                Minimax minimax = new Minimax(npc, marble, jump, gameManager, previousTiles, true);
                yield return(new WaitUntil(() => minimax.Done));

                if (bestNode == null || bestNode.Score < minimax.bestNode.Score)
                {
                    bestNode = minimax.bestNode;
                }
            }
        }

        gameManager.StartCalculation(this);
    }
コード例 #2
0
ファイル: Program.cs プロジェクト: hoggins/codingame
    static void Main(string[] args)
    {
        string[] inputs;
        int      projectCount = int.Parse(Console.ReadLine());

        for (int i = 0; i < projectCount; i++)
        {
            var projects = Molecules.Parse(Console.ReadLine().Split(' '), 0);
        }

        // game loop
        while (true)
        {
            var gs = new GameState();

            for (int i = 0; i < 2; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                gs.Robots.Add(Robot.Parse(i, inputs));
            }

            inputs       = Console.ReadLine().Split(' ');
            gs.Available = Molecules.Parse(inputs, 0);
            int sampleCount = int.Parse(Console.ReadLine());
            for (int i = 0; i < sampleCount; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                gs.Samples.Add(Sample.Parse(inputs));
            }

            // Write an action using Console.WriteLine()
            // To debug: Console.Error.WriteLine("Debug messages...");

            var r         = gs.Robots[0];
            var robotBank = r.Storage + r.Expertise;
            foreach (var sample in r.PrioritySamples(gs))
            {
                if (robotBank.CanSubtract(sample.Cost))
                {
                    Console.Error.WriteLine($"take {sample.Cost}");
                    robotBank -= sample.Cost;
                }
                else
                {
                    var deficit = robotBank.Deficit(sample.Cost);
                    Console.Error.WriteLine($"deficit: {deficit}");
                }
            }

            var decision = Minimax.DecideMove(gs);
            if (decision == null)
            {
                Console.WriteLine("WAIT");
            }
            else
            {
                decision.Execute(gs);
            }
        }
    }
コード例 #3
0
ファイル: PlayerVsCpu.cs プロジェクト: celosama/ai-minimax
        private void checkMoves(MouseState mouseState)
        {
            MouseState currentMouseState = mouseState;
            Point      mousePosition     = new Point(currentMouseState.X, currentMouseState.Y);

            if (board.CurrentPlayer() == human)
            {
                if (lastMouseState.LeftButton == ButtonState.Pressed && currentMouseState.LeftButton == ButtonState.Released)
                {
                    foreach (KeyValuePair <Point, Rectangle> boundingBox in boundingBoxes)
                    {
                        if (boundingBox.Value.Contains(mousePosition))
                        {
                            board.MakeMove(new Move(boundingBox.Key), human);
                        }
                    }
                }
            }
            else
            {
                MinimaxResult result = Minimax.Do(board, cpu, GameSettings.Difficulty, 0);

                Move move = result.GetMove();

                board.MakeMove(move, cpu);
            }

            currentTurn = board.CurrentPlayer();
        }
コード例 #4
0
    // Threaded method that calls minimax to compute the move of the AI
    private void Calculate()
    {
        Minimax mm = new Minimax(GameOptions.Instance.Difficulty);

        _moveAI    = mm.GetMove(_pieceLookup, 0, WhiteScore + BlackScore);
        _setMoveAI = true;
    }
コード例 #5
0
        public void WinEndsTheSearchForPlayerY()
        {
            HexBoard board = new HexBoard(5);

            PlayToWinInOneMove(board, false);

            Minimax   minimax     = MakeMinimaxForBoard(board);
            const int SearchDepth = 4;

            MinimaxResult bestMove = minimax.DoMinimax(SearchDepth, false);
            Location      win      = new Location(0, 3);

            Assert.AreEqual(win, bestMove.Move, "wrong win location");

            // do: test that locations after 0, 4 aren't even looked at. A win ends the search
            IList <Location> locationsExamined = minimax.DebugDataItems
                                                 .Where(d => d.Lookahead == SearchDepth)
                                                 .Select(d => d.Location).ToList();

            Assert.IsTrue(locationsExamined.Count > 0, "No locations examined");
            Assert.IsTrue(locationsExamined.Contains(win), "Locations examined does not contain win");
            Location unexpected = new Location(4, 4);

            Assert.IsFalse(locationsExamined.Contains(unexpected), "Should not have examined location " + unexpected + " after win");
        }
コード例 #6
0
ファイル: TicTacToeTests.cs プロジェクト: haraldq/grappr
 public void SuperSimpleWinMinimax()
 {
     Minimax m = new Minimax();
     m.Depth = 1;
     var initial = new TicTacToe(false, new[] { -1, 0, -1, -1, 1, 1, 1, 0, 1 });
     m.Find(initial);
 }
コード例 #7
0
ファイル: TicTacToeTests.cs プロジェクト: sethjuarez/numl
 public void SuperSimpleWinMinimax()
 {
     var m = new Minimax<IState, ISuccessor>();
     m.Depth = 1;
     var initial = new TicTacToe(false, new[] { -1, 0, -1, -1, 1, 1, 1, 0, 1 });
     m.Find(initial);
 }
コード例 #8
0
        public ConnectFourTree(Grid start, char turn, bool minimax, int depth = Int32.MaxValue)
        {
            if (!minimax)
            {
                root = GenerateTreeAlphaBeta(
                    new Node(0, new Grid((char[, ])start.GetState().Clone()), new int[] { 0, 0 }),
                    turn, depth, Int32.MinValue, Int32.MaxValue
                    );
            }
            else
            {
                root = GenerateTree(
                    new Node(0, new Grid((char[, ])start.GetState().Clone()), new int[] { 0, 0 }),
                    turn, depth);
                root.value = Minimax.run(root, depth, true);
            }

            int max = Int32.MinValue;

            foreach (Node child in root.children)
            {
                if (child.value > max)
                {
                    max       = child.value;
                    root.play = child.play;
                }
            }
        }
コード例 #9
0
    public IEnumerator WaitForMoves()
    {
        foreach (GameObject marble in marbles)
        {
            marblePosition = marble.GetComponent <MarbleScript>().myPosition;
            gameManagerScript.MarblePicked(marble, marblePosition, /* true,*/ false, null, this);
        }
        yield return(new WaitUntil(() => firstLegalMoves != null));

        foreach (PossibleMove move in firstLegalMoves)
        {
            Minimax node = new Minimax(this, move.Marble, move.Tile, gameManagerScript, new List <NewTileScript>()
            {
                move.Marble.myPosition.GetComponent <NewTileScript>()
            }, move.Tile.jumpPosition);
            if (bestNode == null || (node.BestNode.Score > bestNode.Score && node.BestNode.PreviousTiles != null && node.BestNode.PreviousTiles.Count > 1))
            {
                yield return(new WaitUntil(() => node.Done));

                bestNode = node.BestNode;
            }
        }


        StartCoroutine(Move());
    }
コード例 #10
0
 public void MyTurn()
 {
     moved           = false;
     activePlayer    = true;
     bestNode        = null;
     firstLegalMoves = null;
     StartCoroutine(WaitForMoves());
 }
コード例 #11
0
        public override Estado EfetuarJogada(Estado estadoAtual)
        {
            // quanto menor for a profundidade máxima de busca do algoritmo Minimax,
            // menor a chance de encontrarmos a jogada ideal

            EstadoLig4 atual = (estadoAtual as EstadoLig4);

            return(Minimax.EfetuarJogada(this, atual, estadoAtual.NumeroMaximoDeTurnos));
        }
コード例 #12
0
ファイル: TicTacToeTests.cs プロジェクト: haraldq/grappr
        public void SuperSimpleWinMinimax()
        {
            Minimax m = new Minimax();

            m.Depth = 1;
            var initial = new TicTacToe(false, new[] { -1, 0, -1, -1, 1, 1, 1, 0, 1 });

            m.Find(initial);
        }
コード例 #13
0
        public void SuperSimpleWinMinimax()
        {
            var m = new Minimax <IState, ISuccessor>();

            m.Depth = 1;
            var initial = new TicTacToe(false, new[] { -1, 0, -1, -1, 1, 1, 1, 0, 1 });

            m.Find(initial);
        }
コード例 #14
0
        static void Main(string[] args)
        {
            Minimax <Board> minimax       = new Minimax <Board>(new Connect4GameRules());
            Board           currentBoard  = new Board();
            char            me            = '0';
            int             remainingTime = 1000;

            // Set the size of the standard input:
            Console.OpenStandardInput(512);
            String cmd = "";

            while ((cmd = Console.ReadLine()) != null)
            {
                String[] cmds = cmd.Split(' ');
                switch (cmds[0])
                {
                case "settings":
                    // The only settings we really care about is our ID in the board:
                    if (cmds[1] == "your_botid")
                    {
                        me = char.Parse(cmds[2]);
                    }
                    break;

                case "update":
                    // The only update we care about is the current state of the board:
                    if (cmds[1] == "game" && cmds[2] == "field")
                    {
                        currentBoard = getBoardFromInput(cmds[3], me);
                    }
                    break;

                case "action":
                    if (cmds[1] == "move")
                    {
                        remainingTime = int.Parse(cmds[2]);
                        // The engine is requesting a move:
                        int[] boardBefore = currentBoard.LastPiece;

                        // Play the next move with search depth of 6, but we could use the remainingTime variable to
                        // improve the depth with something like (remainingTime > [value] ? 8 : 6)
                        currentBoard = minimax.PlayNextMove(currentBoard, 6);

                        // We have to figure out what position changed =/
                        for (int i = 0; i < boardBefore.Length; i++)
                        {
                            if (boardBefore[i] != currentBoard.LastPiece[i])
                            {
                                Console.WriteLine("place_disc " + i);
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
コード例 #15
0
        private static void DoTestTestNoLingering2Win(Minimax minimax, int depth)
        {
            MinimaxResult bestMove = minimax.DoMinimax(depth, true);

            // play here to win
            Location expectedMove = new Location(2, 2);

            Assert.AreEqual(expectedMove, bestMove.Move, "Wrong best move at depth " + depth);
            AssertWinner(bestMove.Score, Occupied.PlayerX);
        }
コード例 #16
0
        private void DoMove()
        {
            Minimax       hexPlayer     = new Minimax(this.hexGame.Board, this.hexGame.GoodMoves, this.MakeCandiateMovesFinder());
            MinimaxResult minimaxResult = hexPlayer.DoMinimax(4, this.MoveIsPlayerX());

            this.PlayLocation = this.GetBestMove(minimaxResult);
            this.MoveTime     = hexPlayer.MoveTime;

            this.CallCompletedAction();
        }
コード例 #17
0
        public void CheckEmptyBoardForInitailOptimalMove()
        {
            Board   board   = new Board(3);
            Player  player  = new Player('X');
            Minimax minimax = new Minimax('X', 'O');;
            int     actual  = minimax.FindBestMove(board, player);
            //get available move on board
            int expected = 1;

            Assert.Equal(expected, actual);
        }
コード例 #18
0
    void Awake()
    {
        minimax = GameObject.FindObjectOfType <Minimax>();
        SetGameControllerReferenceOnButtons();
        playerSide = "X";
        gameOverPanel.SetActive(false);
        //moveCount = 0;
        Button btn = Restart.GetComponent <Button>();

        btn.onClick.AddListener(RestartGame);
    }
コード例 #19
0
        private static Minimax MakeMinimaxForBoard(HexBoard board)
        {
            GoodMoves       goodMoves            = new GoodMoves();
            ICandidateMoves candidateMovesFinder = new CandidateMovesAll();

            Minimax result = new Minimax(board, goodMoves, candidateMovesFinder);

            result.GenerateDebugData = true;

            return(result);
        }
コード例 #20
0
        public ComputerPlayer(bool isMax, int algorithmDepth, int row, int col)
        {
            this.isMax          = isMax;
            this.algorithmDepth = algorithmDepth;

            //AI
            this.generator = new MyGenerate();
            this.evaluator = new MyEvaluateV2(new int[row, col]);

            this.ai = new Minimax(generator, evaluator);
        }
 public OthelloGui(OthelloBoard othelloBoard)
 {
     InitializeComponent();
     _othelloBoard       = othelloBoard;
     _n                  = _othelloBoard.N;
     _m                  = _othelloBoard.M;
     _availableMoves     = _othelloBoard.AvailableMoves(_othelloBoard.Turn);
     turnBox.BackColor   = _othelloBoard.Turn == 1 ? Color.Black : Color.White;
     _minimax            = new Minimax(3, false);
     aiPlayTimer.Enabled = true;
 }
コード例 #22
0
    private Minimax makeDescisionTree(CheckerBoard board, GameObject b, GameObject w)
    {
        Minimax mainTree = gameObject.AddComponent <Minimax>();

        mainTree.NewMinimax(null, score(board));
        List <Move> moves = new List <Move>();

        // get alls move for AI
        moves = getAllLegalMovesFor(false, board);

        foreach (Move move in moves)
        {
            // Make second row
            CheckerBoard secondstate = gameObject.AddComponent <CheckerBoard>();
            copyBoardToBoard(board, secondstate, b, w);
            secondstate.Moving(move.currRow, move.currCol, move.movRow, move.movCol);
            Minimax firstLayer = gameObject.AddComponent <Minimax>();
            firstLayer.NewMinimax(move, score(secondstate));
            // get alls move for human
            List <Move> secondMoves = getAllLegalMovesFor(true, secondstate);
            //deleteFunction(secondstate);
            foreach (Move sMove in secondMoves)
            {
                // Make third row
                CheckerBoard thirdstate = gameObject.AddComponent <CheckerBoard>();
                copyBoardToBoard(secondstate, thirdstate, b, w);

                thirdstate.Moving(sMove.currRow, sMove.currCol, sMove.movRow, sMove.movCol);
                Minimax secondLayer = gameObject.AddComponent <Minimax>();
                secondLayer.NewMinimax(sMove, score(secondstate));
                // get alls move for AI
                List <Move> thirdMoves = getAllLegalMovesFor(false, thirdstate);
                //deleteFunction(thirdstate);
                foreach (Move tMove in thirdMoves)
                {
                    // Make fourth row
                    CheckerBoard fourthstate = gameObject.AddComponent <CheckerBoard>();
                    // fourthstate.gameObject.SetActive(false);
                    copyBoardToBoard(thirdstate, fourthstate, b, w);
                    fourthstate.Moving(tMove.currRow, tMove.currCol, tMove.movRow, tMove.movCol);
                    Minimax thirdLayer = gameObject.AddComponent <Minimax>();
                    thirdLayer.NewMinimax(tMove, score(fourthstate));
                    //deleteFunction(fourthstate);

                    secondLayer.addChild(thirdLayer);
                }

                firstLayer.addChild(secondLayer);
            }
            mainTree.addChild(firstLayer);
        }

        return(mainTree);
    }
コード例 #23
0
        public void GoodMoveAtLevel3()
        {
            HexBoard board = new HexBoard(6);

            PlayToWinInThreeMoves(board);

            Minimax minimax = MakeMinimaxForBoard(board);

            MinimaxResult bestMove = minimax.DoMinimax(3, true);
            Location      win      = new Location(1, 3);

            Assert.AreEqual(win, bestMove.Move, "Wrong play location");
        }
コード例 #24
0
        private static void TestBestMove(HexGame game, int level, Location expectedBestMove)
        {
            Minimax       hexPlayer = new Minimax(game.Board, game.GoodMoves, new CandidateMovesAll());
            MinimaxResult bestMove  = hexPlayer.DoMinimax(level, true);

            // test the location of the move
            Assert.AreEqual(expectedBestMove, bestMove.Move, "Wrong move at level " + level);

            // test the expected score
            if (level >= 3)
            {
                Assert.AreEqual(Occupied.PlayerX, MoveScoreConverter.Winner(bestMove.Score));
            }
        }
コード例 #25
0
        public void TestCalculateMove3PlayerX()
        {
            HexBoard board = new HexBoard(5);

            PlayFourMoves(board);

            Minimax minimax = MakeMinimaxForBoard(board);

            MinimaxResult firstPlayerResult = minimax.DoMinimax(4, true);

            Location firstPlayerExpectedMove = new Location(2, 1);

            Assert.AreEqual(firstPlayerExpectedMove, firstPlayerResult.Move, "Wrong first player location");
        }
コード例 #26
0
        public void TestCalculateMove2MinimaxPlayerY()
        {
            HexBoard board = new HexBoard(3);

            PlayTwoMoves(board);

            Minimax       minimax            = MakeMinimaxForBoard(board);
            MinimaxResult secondPlayerResult = minimax.DoMinimax(2, false);

            Location expectedPlay = new Location(0, 2);

            Assert.AreEqual(expectedPlay, secondPlayerResult.Move, "Wrong play location");
            Assert.IsFalse(MoveScoreConverter.IsWin(secondPlayerResult.Score));
        }
コード例 #27
0
        public void CheckBoardForBestWinningMoveIndex3()
        {
            Board   board   = new Board(3);
            Player  player  = new Player('X');
            Minimax minimax = new Minimax('X', 'O');

            int[]  positions = { 1, 2, 4, 5, 6, 7, 8, 9 };
            char[] symbols   = { 'X', 'X', 'O', 'X', 'X', 'X', 'O', 'O' };
            Helper.FillBoard(board, positions, symbols);
            int actual   = minimax.FindBestMove(board, player);
            int expected = 3;

            Assert.Equal(expected, actual);
        }
コード例 #28
0
        public void CheckThatWinningPlayerEvaluatesForPlayer_X()
        {
            Board board = new Board(3);

            int[]   positions = { 1, 5, 9 };
            char[]  symbols   = { 'X', 'X', 'X' };
            Minimax minimax   = new Minimax('X', 'O');

            Helper.FillBoard(board, positions, symbols);
            board.WinningPlayer();
            int actual = minimax.Evaluate(board);

            Assert.Equal(10, actual);
        }
コード例 #29
0
        public void CheckBoardForWinInMultipleOptions()
        {
            Board   board   = new Board(3);
            Player  player  = new Player('X');
            Minimax minimax = new Minimax('X', 'O');

            int[]  positions = { 1, 3, 4, 6, 7, 8, 9 };
            char[] symbols   = { 'O', 'X', 'X', 'X', 'X', 'O', 'O' };
            Helper.FillBoard(board, positions, symbols);
            int actual   = minimax.FindBestMove(board, player);
            int expected = 5;

            Assert.Equal(expected, actual);
        }
コード例 #30
0
        public void TestCalculateMoveLookahead1Player1()
        {
            HexBoard board = new HexBoard(3);

            PlayFourMoves(board);

            Minimax       minimax           = MakeMinimaxForBoard(board);
            MinimaxResult firstPlayerResult = minimax.DoMinimax(1, true);

            Location expectedMove = new Location(1, 1);

            Assert.AreEqual(expectedMove, firstPlayerResult.Move, "playerOneBestMove");
            AssertWinner(firstPlayerResult.Score, Occupied.PlayerX);
        }
コード例 #31
0
        public void CheckBoardForToBlockOpponentsWinningOption()
        {
            Board   board   = new Board(3);
            Player  player  = new Player('X');
            Minimax minimax = new Minimax('X', 'O');

            int[]  positions = { 1, 3, 4, 5, 6, 7, 9 };
            char[] symbols   = { 'O', 'O', 'O', 'X', 'X', 'X', 'O' };
            Helper.FillBoard(board, positions, symbols);
            int actual   = minimax.FindBestMove(board, player);
            int expected = 2;

            Assert.Equal(expected, actual);
        }
コード例 #32
0
        public void TestCalculateMoveLookahead1Player2()
        {
            HexBoard board = new HexBoard(3);

            PlayFourMoves(board);

            Minimax       minimax            = MakeMinimaxForBoard(board);
            MinimaxResult secondPlayerResult = minimax.DoMinimax(1, false);

            Location expectedMove = new Location(1, 1);

            Assert.AreEqual(expectedMove, secondPlayerResult.Move, "playerTwoBestMove");
            AssertWinner(secondPlayerResult.Score, Occupied.PlayerY);
        }
コード例 #33
0
ファイル: GameEngine.cs プロジェクト: kstrandby/2048-Helper
    // called at initialization
    void Start()
    {
        // create AI agents
        expectimax = new Expectimax(this);
        minimax = new Minimax(this);
        mcts = new MCTS(this);

        // get ready to setup GUI elements
        defaultSkin = Resources.Load("GUIskin") as GUISkin;
        dropdown = GameObject.Find("Dropdown").GetComponent<Dropdown>();
        slider = GameObject.Find("Slider").GetComponent<Slider>();
        activeTiles = new List<GameObject>();
        LoadSprites();
        LoadPositions();

        // start game
        scoreController = new ScoreController();
        NewGame();
    }