Ejemplo n.º 1
0
        private void RefreshFormData(string moveName)
        {
            BaseMove temp = MoveList.getMove(moveName);

            tbox_Name.Text        = temp.name;
            tbox_Description.Text = temp.description;
            tbox_Power.Text       = temp.power.ToString();
            tbox_Accuracy.Text    = temp.accuracy.ToString();

            for (int i = 0; i < lbox_MoveType.Items.Count; i++)
            {
                if (temp.moveType == (string)lbox_MoveType.Items[i])
                {
                    lbox_MoveType.SelectedIndex = i;
                    break;
                }
            }

            for (int i = 0; i < lbox_MoveKind.Items.Count; i++)
            {
                if (temp.moveKind == (string)lbox_MoveKind.Items[i])
                {
                    lbox_MoveKind.SelectedIndex = i;
                    break;
                }
            }

            tbox_PP.Text = temp.basePP.ToString();

            tbox_MoveScript.Text   = temp.moveScript;
            tbox_EffectScript.Text = temp.effectScript;
        }
Ejemplo n.º 2
0
 public override void GenerateSpecialMoves(MoveList list, bool capturesOnly, int ply)
 {
     if (!capturesOnly)
     {
         int king = Board.GetPieceTypeBitboard(Game.CurrentSide, kingType.TypeNumber).LSB;
         if (!IsSquareAttacked(king, Game.CurrentSide ^ 1))
         {
             for (int dir = 0; dir < 8; dir++)
             {
                 int nextSquare = Board.NextSquare(dir, king);
                 if (nextSquare >= 0 && Board[nextSquare] != null &&
                     Board[nextSquare].Player == Game.CurrentSide &&
                     Board[nextSquare].PieceType != pawnType)
                 {
                     //	The king can swap with this piece.  We won't bother
                     //	to see if the target square is attacked because the
                     //	CheckmateRule is going to verify that anyway and we
                     //	don't want to perform that operation twice.
                     list.BeginMoveAdd(MoveType.Swap, king, nextSquare);
                     Piece kingpiece  = list.AddPickup(king);
                     Piece otherpiece = list.AddPickup(nextSquare);
                     list.AddDrop(kingpiece, nextSquare);
                     list.AddDrop(otherpiece, king);
                     list.EndMoveAdd(0);
                 }
             }
         }
     }
 }
Ejemplo n.º 3
0
        private void SaveMoveData(string moveName)
        {
            BaseMove temp = new BaseMove(
                moveName,
                tbox_Description.Text,
                Int32.Parse(tbox_Power.Text),
                Int32.Parse(tbox_Accuracy.Text),
                (string)lbox_MoveType.SelectedItem,
                (string)lbox_MoveKind.SelectedItem,
                Int32.Parse(tbox_PP.Text));

            if (MoveList.getMove(moveName) == null)
            {
                if (MessageBox.Show(moveName + "does not exist in the Move List.\nWould you like to add it to the list?", "Input Required", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    MoveList.addMove(temp);
                }
                else if (MessageBox.Show("Would you like to change the move in the MoveList, including it's name?", "Input Requred", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    MoveList.move[MoveList.getIndex((string)lbox_MoveList.SelectedItem)] = temp;
                    lbox_MoveList.Items.Add(temp);
                }
            }
            else if (MessageBox.Show("Would you like to overwrite the move in the MoveList?", "Input Required", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                MoveList.addMove(temp);
            }

            RefreshListBox();
        }
Ejemplo n.º 4
0
 public override void GenerateSpecialMoves(MoveList list, bool capturesOnly, int ply)
 {
     if (!capturesOnly)
     {
         int priv = ply == 1 ? gameHistory[Game.GameMoveNumber] : privs[ply - 1];
         if (Game.CurrentSide == 0 && (priv & 1) == 1)
         {
             foreach (int direction in directions)
             {
                 int square = Board.NextSquare(direction, kingSquare[0]);
                 if (square >= 0 && Board[square] == null)
                 {
                     list.BeginMoveAdd(MoveType.StandardMove, kingSquare[0], square);
                     Piece king = list.AddPickup(kingSquare[0]);
                     list.AddDrop(king, square);
                     list.EndMoveAdd(500);
                 }
             }
         }
         else if (Game.CurrentSide == 1 && (priv & 2) == 2)
         {
             foreach (int direction in directions)
             {
                 int square = Board.NextSquare(direction, kingSquare[1]);
                 if (square >= 0 && Board[square] == null)
                 {
                     list.BeginMoveAdd(MoveType.StandardMove, kingSquare[1], square);
                     Piece king = list.AddPickup(kingSquare[1]);
                     list.AddDrop(king, square);
                     list.EndMoveAdd(500);
                 }
             }
         }
     }
 }
Ejemplo n.º 5
0
        // *** OVERRIDES *** //

        public override void GenerateSpecialMoves(MoveList list, bool capturesOnly, int ply)
        {
            if (!capturesOnly)
            {
                BitBoard pawns = Board.GetPieceTypeBitboard(Game.CurrentSide, PawnType.TypeNumber);
                while (pawns)
                {
                    int pawnSquare = pawns.ExtractLSB();
                    int nextSquare = Board.NextSquare(PredefinedDirections.N + Game.CurrentSide, pawnSquare);
                    if (nextSquare >= 0 && Board[nextSquare] != null &&
                        Board[nextSquare].TypeNumber == PawnType.TypeNumber &&
                        Board[nextSquare].Player != Game.CurrentSide)
                    {
                        Piece enemyPawn = Board[nextSquare];
                        //	we can only perform the swap if the enemyPawn is not
                        //	currently attacking any piece of the current side
                        int attackSquare1 = Board.NextSquare(PredefinedDirections.E, pawnSquare);
                        int attackSquare2 = Board.NextSquare(PredefinedDirections.W, pawnSquare);
                        if ((attackSquare1 < 0 || Board[attackSquare1] == null || Board[attackSquare1].Player != Game.CurrentSide) &&
                            (attackSquare2 < 0 || Board[attackSquare2] == null || Board[attackSquare2].Player != Game.CurrentSide))
                        {
                            //	swap move is legal - add it now
                            list.BeginMoveAdd(MoveType.Swap, pawnSquare, nextSquare);
                            Piece myPawn = list.AddPickup(pawnSquare);
                            enemyPawn = list.AddPickup(nextSquare);
                            list.AddDrop(myPawn, nextSquare);
                            list.AddDrop(enemyPawn, pawnSquare);
                            list.EndMoveAdd(25);
                        }
                    }
                }
            }
        }
 public void UpdateKeys(MoveList moves)
 {
     Move[] moveArray = moves.GetMoveList();
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 5; j++)
         {
             if (j > moveArray[i].sequence.Length - 1)
             {
                 spriteRenderers[i * 5 + j].enabled = false;
             }
             else
             {
                 spriteRenderers[i * 5 + j].enabled = true;
                 //if (spriteLookup.ContainsKey(moveArray[i].sequence[j]))
                 //{
                 spriteRenderers[i * 5 + j].sprite = spriteLookup[moveArray[i].sequence[j]];
                 //}
                 //else
                 //    Debug.Log(moveArray[i].sequence[j]);
             }
         }
         text[i].text = moveArray[i].name;
     }
 }
Ejemplo n.º 7
0
        // *** EVENT HANDLERS *** //

        public override MoveEventResponse MoveBeingGenerated(MoveList moves, int from, int to, MoveType type)
        {
            if (Board[from].PieceType == PieceType)
            {
                int direction = Board.DirectionLookup(from, to);
                if (direction >= 0)
                {
                    int nextStep = Board.NextSquare(direction, to);
                    if (nextStep >= 0 && nextStep < Board.NumSquares)
                    {
                        Piece pieceOnNextSquare    = Board[nextStep];
                        Piece pieceOnLandingSquare = Board[to];
                        if (pieceOnNextSquare != null && pieceOnNextSquare.Player != Board[from].Player)
                        {
                            //	we can capture by advance
                            moves.BeginMoveAdd(pieceOnLandingSquare == null ? MoveType.BaroqueCapture : MoveType.ExtraCapture, from, to, nextStep);
                            Piece pieceBeingMoved    = moves.AddPickup(from);
                            Piece pieceBeingCaptured = moves.AddPickup(nextStep);
                            if (pieceOnLandingSquare != null)
                            {
                                moves.AddPickup(to);
                            }
                            moves.AddDrop(pieceBeingMoved, to);
                            moves.EndMoveAdd(pieceOnLandingSquare == null
                                                                ? (3000 + pieceBeingCaptured.PieceType.MidgameValue - (pieceBeingMoved.PieceType.MidgameValue / 16))
                                                                : (4000 + pieceBeingCaptured.PieceType.MidgameValue + pieceOnLandingSquare.PieceType.MidgameValue - (pieceBeingMoved.PieceType.MidgameValue / 16)));
                            return(MoveEventResponse.Handled);
                        }
                    }
                }
            }
            return(base.MoveBeingGenerated(moves, from, to, type));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Constructors a new player.
        /// </summary>
        public LevelPlayer(Vector2 position)
        {
            movePlayer = new MovePlayer();

            #region Moves List
            // Construct the master list of moves.
            moves = new Move[]
            {
                new Move(Enums.MoveState.Punch, Buttons.X),
                new Move(Enums.MoveState.Kick, Buttons.A),
                new Move(Enums.MoveState.SpecialCombo, Buttons.X | Buttons.A),
                new Move(Enums.MoveState.ComboKick, Direction.Down, Direction.DownRight, Direction.Right | Buttons.A),
                new Move(Enums.MoveState.ComboKick, Direction.Down, Direction.DownLeft, Direction.Left | Buttons.A),
                new Move(Enums.MoveState.FirePunch1, Direction.Down, Direction.DownRight, Direction.Right | Buttons.X),
                new Move(Enums.MoveState.FirePunch1, Direction.Down, Direction.DownLeft, Direction.Left | Buttons.X),
                new Move(Enums.MoveState.FinalCombo2, Buttons.B),
            };
            #endregion

            // Construct a move list which will store its own copy of the moves array.
            moveList = new MoveList(moves);

            // Create an InputManager for player with a sufficiently large buffer.
            inputManager = new GamePlayInput((PlayerIndex)0, moveList.LongestMoveLength);

            Alive               = true;
            Lives               = 3;
            ComboCount          = 3;
            Lv                  = 1;
            AttackStrength      = 3;
            chainMoves.Capacity = 3;
            LoadContent();
            Reset(position);
        }
Ejemplo n.º 9
0
        public virtual void SetValidInput()
        {
            inputManagers = InputManager.Managers;
            moveList      = new MoveList(new Move[]
            {
                Move.Up,
                Move.Down,
                Move.Left,
                Move.Right,
                Move.Start,
                Move.Back,
                Move.ButtonA,
                Move.ButtonB,
                Move.ButtonX,
                Move.ButtonY,
                Move.LeftShoulder,
                Move.RightShoulder,
                Move.LeftTrigger,
                Move.RightTrigger,
            });

            if (allowKeyboardOnly && this.inputManagers.Length == 0) // keyboard only
            {
                InputManager.AddInputManager(0);
            }

            // Give each player a location to store their most recent move.
            playerMoves     = new Move[inputManagers.Length];
            playerMoveTimes = new TimeSpan[inputManagers.Length];
            SetKeyboardController();
        }
 public override MoveEventResponse MoveBeingGenerated(MoveList moves, int from, int to, MoveType type)
 {
     if (pieceTypes.Contains(Board[from].PieceType))
     {
         //	follow the steps from the from-square to the to-square, checking
         //	for enemy pieces that can be optinally captured.
         int movingPlayerNumber           = Board[from].Player;
         int direction                    = Board.DirectionLookup(from, to);
         int bitPatternOfPotentialVictims = 0;
         int nSteps     = 1;
         int nextSquare = Board.NextSquare(direction, from);
         while (nextSquare != to && nSteps <= 8)
         {
             if (Board[nextSquare] != null && Board[nextSquare].Player != movingPlayerNumber)
             {
                 //	this square contains a piece we can capture.
                 //	set the appropriate bit indexed by number of steps
                 bitPatternOfPotentialVictims |= 1 << (nSteps - 1);
             }
             //	advance to the next square
             nextSquare = Board.NextSquare(direction, nextSquare);
             nSteps++;
         }
         //	if any bits are set, add additional capture moves for
         //	every possible combination of captures
         if (bitPatternOfPotentialVictims != 0)
         {
             generatePermutations(moves, from, to, bitPatternOfPotentialVictims, 0);
         }
     }
     //	Always return NotHandled, even if we did because we still want
     //	normal move generation to take place so that pieces that can
     //	capture by overtake can still move when they are not doing so.
     return(MoveEventResponse.NotHandled);
 }
Ejemplo n.º 11
0
        private void CheckAndAddValidChild(MoveList child, Boolean createdThroughCrossover, Boolean createdThroughMutation)
        {
            var childValid = Board.ApplyMoveList(child);

            if (childValid)
            {
                //Only valid solutions are applicable.
                var numEmptySpaces = Board.GetNumberOfFreeSpaces();
                child.Score = numEmptySpaces;
                if (child.Score > 0 && _nextGeneration.Count < GeneticAlgorithmOptions.PopulationSize)
                {
                    _nextGeneration.Add(child);

                    if (MovelistCreated != null)
                    {
                        var args = new MovelistCreatedEventArgs {
                            CreatedThroughMutation     = createdThroughMutation,
                            CreatedThroughCrossover    = createdThroughCrossover,
                            CreatedThroughReproduction = false,
                            //NameSolution = child.Name,
                            Score = child.Score,
                            Moves = child.ToString()
                        };
                        MovelistCreated(args);
                    }
                }
            }
            Board.Reset();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Add the current move of the board
        /// </summary>
        private void AddCurrentMove()
        {
            MoveItem moveItem;
            string   strMove;
            string   strMoveIndex;
            int      iMoveCount;
            int      iItemCount;
            int      iIndex;
            MoveExt  move;

            ChessBoard.PlayerE ePlayerToMove;
            ChessBoard         chessBoard;

            chessBoard    = m_chessCtl.Board;
            m_bIgnoreChg  = true;
            move          = chessBoard.MovePosStack.CurrentMove;
            ePlayerToMove = chessBoard.LastMovePlayer;
            chessBoard.UndoMove();
            iMoveCount = chessBoard.MovePosStack.Count;
            iItemCount = listViewMoveList.Items.Count;
            while (iItemCount >= iMoveCount)
            {
                iItemCount--;
                MoveList.RemoveAt(iItemCount);
            }
            strMove = GetMoveDesc(move);
            chessBoard.RedoMove();
            iIndex       = iItemCount;
            strMoveIndex = (m_eDisplayMode == DisplayModeE.MovePos) ? (iIndex + 1).ToString() : (iIndex / 2 + 1).ToString() + ((Char)('a' + (iIndex & 1))).ToString();
            moveItem     = new MoveItem(strMoveIndex,
                                        (ePlayerToMove == ChessBoard.PlayerE.Black) ? "Black" : "White",
                                        strMove);
            MoveList.Add(moveItem);
            m_bIgnoreChg = false;
        }
Ejemplo n.º 13
0
        public ExtractedGame(IGameExtractor extractor)
        {
            MoveList          = extractor.ExtractMoves();
            Abilities         = extractor.ExtractAbilities();
            PokemonList       = extractor.ExtractPokemon();
            GiftPokemonList   = extractor.ExtractGiftPokemon();
            ItemList          = extractor.ExtractItems();
            OverworldItemList = extractor.ExtractOverworldItems();
            Pokemarts         = extractor.ExtractPokemarts().OrderBy(m => m.FirstItemIndex).ToArray();
            TrainerPools      = extractor.ExtractPools(PokemonList, MoveList);

            ValidMoves   = MoveList.Where(m => m.MoveIndex != 0 && m.MoveIndex != 355).ToArray();
            ValidPokemon = PokemonList.Where(p => !RandomizerConstants.SpecialPokemon.Contains(p.Index)).ToArray();
            ValidItems   = ItemList.Where(i => !RandomizerConstants.InvalidItemList.Contains(i.Index)).ToArray();
            NonKeyItems  = ValidItems.Where(i => i.BagSlot != BagSlots.KeyItems && i.BagSlot != BagSlots.None).ToArray();
            TMs          = ItemList.Where(i => i is TM).Select(i => i as TM).ToArray();

            if (extractor is XDExtractor xd)
            {
                isXD       = true;
                TutorMoves = xd.ExtractTutorMoves();
            }
            else
            {
                isXD       = false;
                TutorMoves = Array.Empty <TutorMove>();
            }
        }
Ejemplo n.º 14
0
    private static IEnumerable <int> GetValidMoves(PKM pk, GameVersion version, EvolutionHistory evoChains, MoveSourceType types = MoveSourceType.Reminder, bool RemoveTransferHM = true)
    {
        var r = new List <int> {
            0
        };

        if (types.HasFlagFast(MoveSourceType.RelearnMoves) && pk.Format >= 6)
        {
            r.AddRange(pk.RelearnMoves);
        }

        int start = pk.Generation;

        if (start < 0)
        {
            start = pk.Format; // be generous instead of returning nothing
        }
        if (pk is IBattleVersion b)
        {
            start = Math.Max(0, b.GetMinGeneration());
        }

        for (int generation = start; generation <= pk.Format; generation++)
        {
            var chain = evoChains[generation];
            if (chain.Length == 0)
            {
                continue;
            }
            r.AddRange(MoveList.GetValidMoves(pk, version, chain, generation, types: types, RemoveTransferHM: RemoveTransferHM));
        }

        return(r.Distinct());
    }
Ejemplo n.º 15
0
        public override MoveList GetThreatenMoveList()
        {
            MoveList moveList = new MoveList();

            if (Color == Color.White)
            {
                // beat left
                Position newPosition = Position.GetDeltaPosition(1, -1);
                AddPosition(moveList, newPosition);


                // beat right
                newPosition = Position.GetDeltaPosition(1, 1);
                AddPosition(moveList, newPosition);
            }
            else
            {
                // beat left
                Position newPosition = Position.GetDeltaPosition(-1, -1);
                AddPosition(moveList, newPosition);

                // beat right
                newPosition = Position.GetDeltaPosition(-1, 1);
                AddPosition(moveList, newPosition);
            }

            return(moveList);
        }
Ejemplo n.º 16
0
        public void AddAMoveToMoveList()
        {
            var move     = new Move(2, 2);
            var moveList = new MoveList();

            moveList.AddMove(move);
        }
Ejemplo n.º 17
0
        public override void GenerateSpecialMoves(MoveList list, bool capturesOnly, int ply)
        {
            int epCaptureSquare = ply == 1
                                ? (Game.GameMoveNumber == 0 ? epCaptureSquares[0] : gameHistoryCaptureSquares[Game.GameMoveNumber - 1])
                                : epCaptureSquares[ply - 1];

            if (epCaptureSquare > 0)
            {
                int targetSquare = ply == 1
                                        ? (Game.GameMoveNumber == 0 ? epMoverSquares[0] : gameHistoryMoverSquares[Game.GameMoveNumber - 1])
                                        : epMoverSquares[ply - 1];
                int   victimPawnMoveDirection = Board.DirectionLookup(epCaptureSquare, targetSquare);
                Piece targetPawn = Board[targetSquare];

                while (epCaptureSquare != targetSquare)
                {
                    int   s        = Board.NextSquare(captureDirections[targetPawn.Player], epCaptureSquare);
                    Piece attacker = Board[Board.NextSquare(captureDirections[targetPawn.Player], epCaptureSquare)];
                    if (attacker.PieceType == PawnType)
                    {
                        //	this is a valid en passant attack
                        list.BeginMoveAdd(MoveType.EnPassant, attacker.Square, epCaptureSquare);
                        list.AddPickup(attacker.Square);
                        list.AddPickup(targetPawn.Square);
                        list.AddDrop(attacker, epCaptureSquare, null);
                        list.EndMoveAdd(3000);
                    }
                    epCaptureSquare = Board.NextSquare(victimPawnMoveDirection, epCaptureSquare);
                }
            }
        }
        public MoveList Solve(Board board, PiecesQueue queue)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }
            if (board == null)
            {
                throw new ArgumentNullException("board");
            }

            PiecesQueue  = queue;
            CurrentState = board;

            _maximumScore = CurrentState.MaximumNumberOfFreeSpaces;
            var piecesList = PiecesQueue.ToList();
            var headPiece  = piecesList.First();
            var tail       = piecesList.Skip(1).ToList();

            GetCurrentBest = new MoveList {
                Score = 0
            };
            var ml     = new MoveList();
            var random = new System.Random();

            Solve(random, ml, headPiece, tail, 0);

            return(GetCurrentBest);
        }
Ejemplo n.º 19
0
        public Game()
        {
            Seed = -1;
            TraceStartFinish = false;
            TraceDeals = false;
            TraceMoves = false;
            ComplexMoves = false;
            Diagnostics = false;
            Instance = -1;

            Shuffled = new Pile();
            Tableau = new Tableau();

            Candidates = new MoveList();
            SupplementaryList = new MoveList();
            RunFinder = new RunFinder();
            FaceLists = new PileList[(int)Face.King + 2];
            for (int i = 0; i < FaceLists.Length; i++)
            {
                FaceLists[i] = new PileList();
            }
            Coefficients = null;

            TableauInputOutput = new TableauInputOutput(Tableau);
            MoveProcessor = new MoveProcessor(this);

            Variation = Variation.Spider4;
            AlgorithmType = AlgorithmType.Study;
        }
Ejemplo n.º 20
0
            public void GeneratesCorrectRookMoves()
            {
                Position board = Position.FromFen("rnbqkbn1/ppp1ppp1/6r1/2Rp3p/7P/8/PPPPPPP1/RNBQKBN1 w Qq d6 0 5");

                Move[] expectedMoves =
                {
                    new Move(Position.C5, Position.B5, Position.ROOK),
                    new Move(Position.C5, Position.A5, Position.ROOK),
                    new Move(Position.C5, Position.C6, Position.ROOK),
                    new Move(Position.C5, Position.C7, Position.ROOK, Position.PAWN),
                    new Move(Position.C5, Position.D5, Position.ROOK, Position.PAWN),
                    new Move(Position.C5, Position.C4, Position.ROOK),
                    new Move(Position.C5, Position.C3, Position.ROOK)
                };

                MoveList actualMoves         = new MoveList();
                Bitboard destinationBitboard = ~board.GetPieceBitboard(Position.WHITE, Position.ALL_PIECES);

                board.GetSlidingPieceMoves(
                    actualMoves,
                    Position.ROOK,
                    Position.C5,
                    destinationBitboard);
                TestUtils.TestArrayEquality(expectedMoves, actualMoves.ToArray());
            }
Ejemplo n.º 21
0
        public Game()
        {
            Seed             = -1;
            TraceStartFinish = false;
            TraceDeals       = false;
            TraceMoves       = false;
            ComplexMoves     = false;
            Diagnostics      = false;
            Instance         = -1;

            Shuffled = new Pile();
            Tableau  = new Tableau();

            Candidates        = new MoveList();
            SupplementaryList = new MoveList();
            RunFinder         = new RunFinder();
            FaceLists         = new PileList[(int)Face.King + 2];
            for (int i = 0; i < FaceLists.Length; i++)
            {
                FaceLists[i] = new PileList();
            }
            Coefficients = null;

            TableauInputOutput = new TableauInputOutput(Tableau);
            MoveProcessor      = new MoveProcessor(this);

            Variation     = Variation.Spider4;
            AlgorithmType = AlgorithmType.Study;
        }
Ejemplo n.º 22
0
 public void PrintMoves(MoveList moves)
 {
     foreach (Move move in moves)
     {
         PrintMove(move);
     }
 }
 private void CooldownComplete()
 {
     coolingDown = false;
     buffer.Clear();
     this.moveList = GetRandomMoveList(this.moves);
     keyDisplay.UpdateKeys(moveList);
 }
Ejemplo n.º 24
0
        public void SetUp()
        {
            Initializer.AllInit();
            var dir = new DirectoryInfo(Path.GetDirectoryName(
                                            Assembly.GetExecutingAssembly().Location));

            while (dir.Name != "bin")
            {
                dir = dir.Parent;
            }

            dir = dir.Parent;

            var path = Path.Combine(dir.FullName, "perftsuite.epd");

            var file = "";

            try {
                file = File.ReadAllText(path);
            } catch (Exception e) {
                throw new FileNotFoundException("Invalid file path");
            }

            perftSuite = file.Split(
                new[] { Environment.NewLine },
                StringSplitOptions.None
                );

            perft    = new Perft();
            board    = new Board();
            moveList = new MoveList();
        }
Ejemplo n.º 25
0
        /// <summary>
        ///     Counts the amount of leafNode at the parameter input depth,
        ///     by an inorder recursive tree traversion algorithm.
        ///     It checks all legal moves with the parameter input depth,
        ///     and increments the leafNode counter when the "last" move
        ///     (the leaf) has been located.
        /// </summary>
        /// <param name="depth"> The depth to traverse </param>
        /// <param name="board"> The chess board operate on </param>
        /// <exception cref="Exception"></exception>
        public void _Perft(int depth, Board board)   // For counting the TOTAL available moves
        {
            Debug.Assert(BoardOperations.CheckBoard(board));
            // Increment leafNode and return.
            if (depth == 0)
            {
                LeafNodes++;
                return;
            }

            // Generate moves for rootposition
            MoveList list = new MoveList();

            MoveGen.GenerateAllMoves(board, list, false);

            for (int i = 0; i < list.Count; ++i)
            {
                if (!MakeMove.Make_Move(board, list.Moves[i].Move))
                {
                    continue;
                }

                _Perft(depth - 1, board);
                MakeMove.TakeMove(board);
            }
        }
Ejemplo n.º 26
0
        public override List <Move> Play()
        {
            List <Ship> shipsWithoutCommands = UndockedShips.ToList();

            for (int i = 0; i < UndockedShips.Count; i++)
            {
                Ship   ship   = shipsWithoutCommands[0];
                Planet planet = Navigation.GetClosestPlanetToShip(ship, UnownedPlanets);

                ship = Navigation.GetClosestShipToPlanet(planet, shipsWithoutCommands);

                if (ship.CanDock(planet))
                {
                    MoveList.Add(new DockMove(ship, planet));
                }
                else
                {
                    ThrustMove newThrustMove = Navigation.NavigateShipToDock(GameMap, ship, planet, Constants.MAX_SPEED);
                    if (newThrustMove != null)
                    {
                        MoveList.Add(newThrustMove);
                    }
                }

                UnownedPlanets.Remove(planet);
                shipsWithoutCommands.Remove(ship);
            }

            return(MoveList);
        }
Ejemplo n.º 27
0
    private static void ParseMovesWasEggPreRelearn(PKM pk, CheckMoveResult[] parse, IReadOnlyList <int> currentMoves, LegalInfo info, EncounterEgg e)
    {
        // Level up moves could not be inherited if Ditto is parent,
        // that means genderless species and male only species (except Nidoran-M and Volbeat; they breed with Nidoran-F and Illumise) could not have level up moves as an egg
        var pi           = pk.PersonalInfo;
        var AllowLevelUp = !pi.Genderless && !(pi.OnlyMale && Breeding.MixedGenderBreeding.Contains(e.Species));
        int BaseLevel    = AllowLevelUp ? 100 : e.LevelMin;
        var LevelUp      = MoveList.GetBaseEggMoves(pk, e.Species, e.Form, e.Version, BaseLevel);

        var TradebackPreevo      = pk.Format == 2 && e.Species > 151;
        var NonTradebackLvlMoves = TradebackPreevo
            ? MoveList.GetExclusivePreEvolutionMoves(pk, e.Species, info.EvoChainsAllGens.Gen2, 2, e.Version).Where(m => m > Legal.MaxMoveID_1).ToArray()
            : Array.Empty <int>();

        var Egg = MoveEgg.GetEggMoves(pk.PersonalInfo, e.Species, e.Form, e.Version, e.Generation);

        if (info.Generation < 3 && pk.Format >= 7 && pk.VC1)
        {
            Egg = Array.FindAll(Egg, m => m <= Legal.MaxMoveID_1);
        }

        var specialMoves = e.CanHaveVoltTackle ? new[] { (int)Move.VoltTackle } : Array.Empty <int>(); // Volt Tackle for bred Pichu line

        var source = new MoveParseSource
        {
            CurrentMoves             = currentMoves,
            SpecialSource            = specialMoves,
            NonTradeBackLevelUpMoves = NonTradebackLvlMoves,

            EggLevelUpSource = LevelUp,
            EggMoveSource    = Egg,
        };

        ParseMoves(pk, source, info, parse);
    }
Ejemplo n.º 28
0
        public void Perft_Test(int depth, Board board)   // Also prints information regarding the moves
        {
            Debug.Assert(BoardOperations.CheckBoard(board));
            var startTime = Variables.Watch.ElapsedMilliseconds;

            Console.Write("\nStarting Perft Test to Depth {0}", depth);
            BoardOperations.PrintBoard(board);

            LeafNodes = 0;

            MoveList list = new MoveList();

            MoveGen.GenerateAllMoves(board, list, false);


            for (int i = 0; i < list.Count; ++i)
            {
                int move = list.Moves[i].Move;

                if (!MakeMove.Make_Move(board, list.Moves[i].Move))
                {
                    continue;
                }

                long cumulativeNodes = LeafNodes;
                _Perft(depth - 1, board);
                MakeMove.TakeMove(board);
                long oldNodes = LeafNodes - cumulativeNodes;
                Console.Write("\nmove {0} : {1} : {2}", i + 1, Io.MoveToString(move), oldNodes);
            }

            Console.Write("\nTest Complete: {0} nodes visited in {1} miliseconds\n", LeafNodes, Variables.Watch.ElapsedMilliseconds - startTime);
        }
Ejemplo n.º 29
0
        private void AddEnPassant(int directionX, int directionY, ref MoveList moveList)
        {
            var neighbourX = _position.PhysicalX + directionX;

            if (!neighbourX.IsOnBoard())
            {
                return;
            }

            var neighbourPiece = _board.GetPieceUsingPhysicalCoordinates(directionX, _position.PhysicalY);

            if (neighbourPiece == null)
            {
                return;
            }

            if (neighbourPiece.Color == _piece.Color)
            {
                return;
            }

            var targetY = _position.PhysicalY + directionY;

            if (!targetY.IsOnBoard())
            {
                return;
            }

            //TODO
        }
Ejemplo n.º 30
0
        public override MoveList GetMoves()
        {
            var homeY = _piece.Color == Color.White
                ? 6
                : 1;

            var directionY = _piece.Color == Color.White
                ? -1
                : 1;

            var moveList = new MoveList();

            AddInitialDoubleStepMove(homeY, directionY, ref moveList);

            AddSingleStepMove(directionY, ref moveList);

            AddCapture(-1, directionY, ref moveList);

            AddCapture(1, directionY, ref moveList);

            AddEnPassant(-1, directionY, ref moveList);

            AddEnPassant(1, directionY, ref moveList);

            return(moveList);
        }
Ejemplo n.º 31
0
    private static int[] GetSuggestedMoves(PKM pk, EvolutionHistory evoChains, MoveSourceType types, IEncounterTemplate enc)
    {
        if (pk.IsEgg && pk.Format <= 5) // pre relearn
        {
            return(MoveList.GetBaseEggMoves(pk, pk.Species, 0, (GameVersion)pk.Version, pk.CurrentLevel));
        }

        if (types != MoveSourceType.None)
        {
            return(GetValidMoves(pk, evoChains, types).Skip(1).ToArray()); // skip move 0
        }
        // try to give current moves
        if (enc.Generation <= 2)
        {
            var lvl = pk.Format >= 7 ? pk.Met_Level : pk.CurrentLevel;
            var ver = enc.Version;
            return(MoveLevelUp.GetEncounterMoves(enc.Species, 0, lvl, ver));
        }

        if (pk.Species == enc.Species)
        {
            return(MoveLevelUp.GetEncounterMoves(pk.Species, pk.Form, pk.CurrentLevel, (GameVersion)pk.Version));
        }

        return(GetValidMoves(pk, evoChains, types).Skip(1).ToArray()); // skip move 0
    }
Ejemplo n.º 32
0
 public static MoveList MoveList(string solution)
 {
     MoveList moveList = new MoveList();
     bool isPull = false;
     string digits = "";
     string moves = null;
     for (int i = 0; i < solution.Length; i++)
     {
         char c = solution[i];
         if (Char.IsWhiteSpace(c))
         {
             continue;
         }
         if (c == '-')
         {
             isPull = true;
             continue;
         }
         if (Char.IsDigit(c))
         {
             digits += c;
             continue;
         }
         if (c == '(')
         {
             moves = "";
             continue;
         }
         if (moves != null && c != ')')
         {
             moves += c;
             continue;
         }
         if (c != ')')
         {
             moves = c.ToString();
         }
         int count = String.IsNullOrEmpty(digits) ? 1 : Int32.Parse(digits);
         for (int j = 0; j < count; j++)
         {
             for (int k = 0; k < moves.Length; k++)
             {
                 c = moves[k];
                 Operation operation = DecodeOperation(c);
                 Direction direction = DecodeDirection(c);
                 if (isPull && operation == Operation.Push)
                 {
                     operation = Operation.Pull;
                 }
                 moveList.Add(new OperationDirectionPair(operation, direction));
             }
         }
         digits = "";
         moves = null;
         isPull = false;
     }
     return moveList;
 }
Ejemplo n.º 33
0
 public static string EncodedSolution(MoveList moveList)
 {
     StringBuilder builder = new StringBuilder(moveList.Count);
     for (int i = 0; i < moveList.Count; i++)
     {
         builder.Append(EncodeMove(moveList[i]));
     }
     return builder.ToString();
 }
Ejemplo n.º 34
0
        public void sizeTests()
        {
            PSQT.init();
            Bitboards.init();
            Position.init();

            var pos = new Position("rnbqkbnr/1ppppppp/p7/7Q/4P3/8/PPPP1PPP/RNB1KBNR b KQkq - 1 2", false, null);
            var ml = new MoveList(GenType.LEGAL, pos);
            Assert.AreEqual(16, ml.size());
        }
 public CompositeSinglePileMoveFinder(Game game)
     : base(game)
 {
     UncoveringMoves = new MoveList();
     OneRunPiles = new PileList();
     Used = new PileList();
     Roots = new PileList();
     WorkingTableau = new Tableau();
     HoldingStack = new HoldingStack();
     SupplementaryMoves = new MoveList();
     MoveStack = new FastList<Move>();
 }
Ejemplo n.º 36
0
 public SearchMoveFinder(Game game)
     : base(game)
 {
     UseDepthFirst = false;
     WorkingTableau = new Tableau();
     TranspositionTable = new HashSet<int>();
     MoveStack = new MoveList();
     Moves = new MoveList();
     MaxDepth = 20;
     MaxNodes = 10000;
     MoveAllocator = new ListAllocator<Move>(false);
     NodeAllocator = new ListAllocator<Node>(true);
 }
Ejemplo n.º 37
0
 public ComplexMove(int index, MoveList moves, MoveList supplementaryList)
 {
     Move scoreMove = moves[index];
     ScoreMove = scoreMove;
     SupplementaryMoves = new MoveList();
     for (int next = scoreMove.Next; next != -1; next = supplementaryList[next].Next)
     {
         SupplementaryMoves.Add(supplementaryList[next]);
     }
     HoldingList = new MoveList();
     for (int next = scoreMove.HoldingNext; next != -1; next = supplementaryList[next].Next)
     {
         HoldingList.Add(supplementaryList[next]);
     }
 }
Ejemplo n.º 38
0
 public int AddSupplementary(MoveList supplementaryMoves)
 {
     return game.AddSupplementary(supplementaryMoves);
 }
Ejemplo n.º 39
0
    // ThreadPool::start_thinking() wakes up the main thread sleeping in
    // MainThread::idle_loop() and starts a new search, then returns immediately.

    internal static void start_thinking(Position pos, LimitsType limits, StateInfoWrapper states)
    {
        main().join();
        Search.Signals.stopOnPonderhit = Search.Signals.firstRootMove = false;
        Search.Signals.stop = Search.Signals.failedLowAtRoot = false;

        Search.RootMoves.Clear();
        Search.RootPos = new Position(pos);
        Search.Limits = limits;

        var current = states[states.current];
        if (current != null) // If we don't set a new position, preserve current state
        {
            Search.SetupStates = states; // Ownership transfer here
            Debug.Assert(current != null);
        }

        var ml = new MoveList(GenType.LEGAL, pos);
        for (var index = ml.begin(); index < ml.end(); index++)
        {
            var m = ml.moveList.table[index];
            if (limits.searchmoves.Count == 0 || limits.searchmoves.FindAll(move => move == m.Move).Count > 0)
            {
                Search.RootMoves.Add(new RootMove(m));
            }
        }

        main().thinking = true;
        main().notify_one(); // Wake up main thread: 'thinking' must be already set
    }
Ejemplo n.º 40
0
        private void AddLevel(State state, Level level, MoveList moveList)
        {
            // Optionally reject levels with dead-ends.
            if (rejectDeadEnds && LevelUtils.HasDeadEnds(level))
            {
                Reject(state, level, "level with dead ends");
                return;
            }

            // Optionally reject levels with captured targets.
            if (rejectCapturedTargets && LevelUtils.HasCapturedTargets(level))
            {
                Reject(state, level, "level with captured targets");
                return;
            }

            // Optionally move the sokoban away from the first box it pushes.
            MoveList finalMoveList = moveList;
            if (moveSokoban)
            {
                // Record old sokoban coordinate.
                Coordinate2D oldSokobanCoord = level.SokobanCoordinate;

                // Find accessible coordinates.
                PathFinder finder = PathFinder.CreateInstance(level);
                finder.Find();

                if (rejectSokobanOnTarget)
                {
                    // Move sokoban to first accessible non-target square.
                    foreach (Coordinate2D coord in finder.AccessibleCoordinates)
                    {
                        if (!level.IsTarget(coord))
                        {
                            level.MoveSokoban(coord);
                            break;
                        }
                    }
                    if (level.IsTarget(level.SokobanCoordinate))
                    {
                        Reject(state, level, "level with sokoban on target");
                        return;
                    }
                }
                else
                {
                    // Move sokoban to first accessible square.
                    foreach (Coordinate2D coord in finder.AccessibleCoordinates)
                    {
                        level.MoveSokoban(coord);
                        break;
                    }
                }

                // Solve one last time if the sokoban moved.
                if (oldSokobanCoord != level.SokobanCoordinate)
                {
                    finalMoveList = FinalSolve(state, level);
                    if (finalMoveList == null)
                    {
                        Reject(state, level, "final solver failed");
                        return;
                    }
                }
            }

            int moves = finalMoveList.Count;
            int pushes = LevelUtils.SolutionPushes(finalMoveList);
            int changes = LevelUtils.SolutionChanges(level, finalMoveList);
            int minBoxMoves = LevelUtils.MinimumBoxMoves(level, finalMoveList);

            // Add level to results.
            LevelInfo info = new LevelInfo();
            info.Level = level;
            info.Moves = moves;
            info.Pushes = pushes;
            info.Changes = changes;
            info.InsideSquares = level.InsideSquares;
            info.MinimumBoxMoves = minBoxMoves;
            info.MoveList = finalMoveList;

            AddResult(state, info);
        }
Ejemplo n.º 41
0
        private void AddSmallestLevel(State state, Level level, MoveList moveList)
        {
            // Clean it up.
            Level finalLevel = LevelUtils.NormalizeLevel(LevelUtils.CleanLevel(level, moveList));
            if (verbose >= 2)
            {
                state.Log.DebugPrint("Prior to square removal:");
                state.Log.DebugPrint(finalLevel.AsText);
            }

            // Check for duplicates including possible chiral pair.
            Level chiralLevel = LevelUtils.NormalizeLevel(LevelUtils.GetMirroredLevel(finalLevel));
            if (set.Contains(finalLevel) || set.Contains(chiralLevel))
            {
                Reject(state, level, "duplicate level");
                return;
            }
            set.Add(finalLevel, state.Index);
            set.Add(chiralLevel, state.Index);

            // Re-solve with new level.
            MoveList finalMoveList = FinalSolve(state, finalLevel);

            // Fail if the solver failed.
            if (finalMoveList == null)
            {
                Reject(state, level, "final solver failed");
                return;
            }

            // We can check moves and changes now that we've used the optimizing solver.
            if (finalMoveList.Count < moveLimit)
            {
                Reject(state, level, "less than move limit");
                return;
            }
            if (LevelUtils.SolutionChanges(finalLevel, finalMoveList) < changeLimit)
            {
                Reject(state, level, "less than change limit");
                return;
            }

            // Ensure that all boxes must move enough.
            if (LevelUtils.MinimumBoxMoves(finalLevel, finalMoveList) < boxMoveLimit)
            {
                Reject(state, level, "less than box move limit");
                return;
            }

            // Check whether any squares can be removed.
            CheckRemove(state, finalLevel, finalMoveList);
        }
Ejemplo n.º 42
0
        private void CheckRemove(State state, Level level, MoveList moveList)
        {
            int pushes = LevelUtils.SolutionPushes(moveList);

            bool removedASquare = false;
            foreach (Coordinate2D coord in level.InsideCoordinates)
            {
                if (level.IsJustFloor(coord))
                {
                    // Remove the square.
                    Level subLevel = new Level(level);
                    subLevel[coord] = Cell.Wall;

                    // Ensure that this does not corrupt the level.
                    if (!LevelUtils.AllBoxesAndTargetsAreAccessible(level))
                    {
                        continue;
                    }

                    // See if the level is still soluble.
                    MoveList subMoveList = FastSolve(state, subLevel);
                    if (subMoveList != null)
                    {
                        removedASquare = true;

                        if (verbose >= 2)
                        {
                            state.Log.DebugPrint("Removing square {0}", coord);
                        }
                        if (verbose >= 3)
                        {
                            state.Log.DebugPrint("Checking for more square removal:");
                            state.Log.DebugPrint(subLevel.AsText);
                        }

                        // Recursively check for more squares than can be removed.
                        AddSmallestLevel(state, subLevel, subMoveList);
                    }
                }
            }

            // At least one smaller level was soluble with the same boxes and targets.
            if (!removedASquare)
            {
                AddLevel(state, level, moveList);
            }
        }
Ejemplo n.º 43
0
    /// Search::perft() is our utility to verify move generation. All the leaf nodes
    /// up to the given depth are generated and counted and the sum returned.
    internal static long perft(bool Root, Position pos, Depth depth)
    {
        var st = new StateInfo();
        long nodes = 0;
        var ci = new CheckInfo(pos);
        var leaf = (depth == 2*Depth.ONE_PLY);

        var ml = new MoveList(GenType.LEGAL, pos);
        for (var index = ml.begin(); index < ml.end(); index++)
        {
            var m = ml.moveList.table[index];
            long cnt;
            if (Root && depth <= Depth.ONE_PLY_C)
            {
                cnt = 1;
                nodes++;
            }
            else
            {
                pos.do_move(m, st, pos.gives_check(m, ci));
                cnt = leaf ? new MoveList(GenType.LEGAL, pos).size() : perft(false, pos, depth - Depth.ONE_PLY);
                nodes += cnt;
                pos.undo_move(m);
            }
            if (Root)
            {
                Output.WriteLine($"{UCI.move(m, pos.is_chess960())}: {cnt}");
            }
        }
        return nodes;
    }
Ejemplo n.º 44
0
 public int AddSupplementary(MoveList supplementaryMoves)
 {
     if (supplementaryMoves.Count == 0)
     {
         return -1;
     }
     int first = SupplementaryList.Count;
     int count = supplementaryMoves.Count;
     for (int i = 0; i < count; i++)
     {
         Move move = supplementaryMoves[i];
         move.Next = i < count - 1 ? first + i + 1 : -1;
         SupplementaryList.Add(move);
     }
     return first;
 }
Ejemplo n.º 45
0
    /// UCI::to_move() converts a string representing a move in coordinate notation
    /// (g1f3, a7a8q) to the corresponding legal Move, if any.
    private static MoveT to_move(Position pos, string str)
    {
        if (str.Length == 5) // Junior could send promotion piece in uppercase
        {
            var chars = str.ToCharArray();
            chars[4] = Position.tolower(str[4]);
            str = new string(chars);
        }

        var ml = new MoveList(GenType.LEGAL, pos);
        for (var index = ml.begin(); index < ml.end(); index++)
        {
            var extMove = ml.moveList.table[index];
            if (str == move(extMove, pos.is_chess960()))
            {
                return extMove;
            }
        }

        return Move.MOVE_NONE;
    }
Ejemplo n.º 46
0
 public void PrintMoves(MoveList moves)
 {
     foreach (Move move in moves)
     {
         PrintMove(move);
     }
 }
Ejemplo n.º 47
0
        private void CleanupDialog()
        {
            while (!solverThread.Join(10))
            {
                Application.DoEvents();
            }
            timer1.Enabled = false;
            if (solver != null)
            {
                textBoxSolverInfo.Text = solver.CancelInfo.Info;
                solution = solver.Solution;
                solver = null;
                GC.Collect();
            }
            solving = false;

            ShowMemory("after");
        }
Ejemplo n.º 48
0
 public void PrintMoves(MoveList moves)
 {
     game.PrintMoves(moves);
 }
    public static void Main(string[] args)
    {
        MoveList ml = new MoveList ();

        ml.Add (1, 2);
        ml.Add (3, 4);
        WriteMoveList ("test.moves", ml);

        MoveList ml2 = ReadMoveList ("test.moves");
        foreach (MoveList.Move move in ml2.moves)
            Console.WriteLine ("move: {0}, {1}", move.x, move.y);
    }
Ejemplo n.º 50
0
 private static void addPawnDoubleMovesByMask(MoveList moveList, Position pos,
                                                ulong mask, int delta)
 {
     while (mask != 0) {
     int sq = BitBoard.numberOfTrailingZeros(mask);
     setMove(moveList, sq + delta, sq, Piece.EMPTY);
     mask &= (mask - 1);
     }
 }
Ejemplo n.º 51
0
 private void Validate(Level level, Level finalLevel, MoveList finalMoveList)
 {
     if (!normalizeLevels)
     {
         return;
     }
     if (!validateNormalization)
     {
         return;
     }
     if (level == finalLevel)
     {
         return;
     }
     bool printLevels = false;
     MoveList moveList = FinalSolve(level);
     if (moveList == null)
     {
         return;
     }
     if (finalMoveList == null)
     {
         Console.WriteLine();
         Console.WriteLine("Normalization made level unsolvable");
         printLevels = true;
     }
     else if (LevelUtils.SolutionChanges(level, moveList) != LevelUtils.SolutionChanges(finalLevel, finalMoveList))
     {
         Console.WriteLine();
         Console.WriteLine("Normalization changed the solution");
         printLevels = true;
     }
     if (printLevels)
     {
         Console.WriteLine();
         Console.WriteLine("Before normalization:");
         Console.WriteLine(level.AsText);
         Console.WriteLine("After normalization:");
         Console.WriteLine(finalLevel.AsText);
         Console.WriteLine();
     }
 }
Ejemplo n.º 52
0
 private static bool addPawnMovesByMask(MoveList moveList, Position pos, ulong mask,
                                             int delta, bool allPromotions)
 {
     if (mask == 0)
     return false;
     ulong oKingMask = pos.pieceTypeBB[pos.whiteMove ? Piece.BKING : Piece.WKING];
     if ((mask & oKingMask) != 0) {
     int sq = BitBoard.numberOfTrailingZeros(mask & oKingMask);
     moveList.size = 0;
     setMove(moveList, sq + delta, sq, Piece.EMPTY);
     return true;
     }
     ulong promMask = mask & BitBoard.maskRow1Row8;
     mask &= ~promMask;
     while (promMask != 0) {
     int sq = BitBoard.numberOfTrailingZeros(promMask);
     int sq0 = sq + delta;
     if (sq >= 56) { // White promotion
         setMove(moveList, sq0, sq, Piece.WQUEEN);
         setMove(moveList, sq0, sq, Piece.WKNIGHT);
         if (allPromotions) {
             setMove(moveList, sq0, sq, Piece.WROOK);
             setMove(moveList, sq0, sq, Piece.WBISHOP);
         }
     } else { // Black promotion
         setMove(moveList, sq0, sq, Piece.BQUEEN);
         setMove(moveList, sq0, sq, Piece.BKNIGHT);
         if (allPromotions) {
             setMove(moveList, sq0, sq, Piece.BROOK);
             setMove(moveList, sq0, sq, Piece.BBISHOP);
         }
     }
     promMask &= (promMask - 1);
     }
     while (mask != 0) {
     int sq = BitBoard.numberOfTrailingZeros(mask);
     setMove(moveList, sq + delta, sq, Piece.EMPTY);
     mask &= (mask - 1);
     }
     return false;
 }
Ejemplo n.º 53
0
 /**
  * Remove all illegal moves from moveList.
  * "moveList" is assumed to be a list of pseudo-legal moves.
  * This function removes the moves that don't defend from check threats.
  */
 public static void RemoveIllegal(Position pos, MoveList moveList)
 {
     int length = 0;
     UndoInfo ui = new UndoInfo();
     for (int mi = 0; mi < moveList.size; mi++) {
     Move m = moveList.m[mi];
     pos.makeMove(m, ui);
     pos.setWhiteMove(!pos.whiteMove);
     if (!inCheck(pos))
         moveList.m[length++].copyFrom(m);
     pos.setWhiteMove(!pos.whiteMove);
     pos.unMakeMove(m, ui);
     }
     moveList.size = length;
 }
Ejemplo n.º 54
0
 /** Return all move objects in moveList to the move cache. */
 public void returnMoveList(MoveList moveList)
 {
     if (moveListsInCache < moveListCache.Length) {
     moveListCache[moveListsInCache++] = moveList;
     }
 }
Ejemplo n.º 55
0
        private void SolverDialog_Load(object sender, EventArgs e)
        {
            ShowMemory("before");

            textBoxSolverInfo.Text = "";
            buttonOK.Text = "Solve";
            buttonOK.Enabled = true;

            solution = null;
            solving = false;
        }
Ejemplo n.º 56
0
 private static bool addMovesByMask(MoveList moveList, Position pos, int sq0, ulong mask)
 {
     ulong oKingMask = pos.pieceTypeBB[pos.whiteMove ? Piece.BKING : Piece.WKING];
     if ((mask & oKingMask) != 0) {
     int sq = BitBoard.numberOfTrailingZeros(mask & oKingMask);
     moveList.size = 0;
     setMove(moveList, sq0, sq, Piece.EMPTY);
     return true;
     }
     while (mask != 0) {
     int sq = BitBoard.numberOfTrailingZeros(mask);
     setMove(moveList, sq0, sq, Piece.EMPTY);
     mask &= (mask - 1);
     }
     return false;
 }
Ejemplo n.º 57
0
 private static void setMove(MoveList moveList, int from, int to, int promoteTo)
 {
     Move m = moveList.m[moveList.size++];
     m.from = from;
     m.to = to;
     m.promoteTo = promoteTo;
     m.score = 0;
 }
 public static void WriteMoveList(string filename, MoveList ml)
 {
     XmlSerializer xs = new XmlSerializer (typeof (MoveList));
     TextWriter writer = new StreamWriter (filename);
     xs.Serialize (writer, ml);
     writer.Close ();
 }
Ejemplo n.º 59
0
 private MoveList getMoveListObj()
 {
     MoveList ml;
     if (moveListsInCache > 0) {
     ml = (MoveList)moveListCache[--moveListsInCache];
     ml.size = 0;
     } else {
     ml = new MoveList();
     for (int i = 0; i < MAX_MOVES; i++)
         ml.m[i] = new Move(0, 0, Piece.EMPTY);
     }
     return ml;
 }
Ejemplo n.º 60
0
 public static int SolutionPushes(MoveList solution)
 {
     if (solution == null)
     {
         return -1;
     }
     int pushes = 0;
     foreach (OperationDirectionPair pair in solution)
     {
         if (pair.Operation == Operation.Push)
         {
             pushes++;
         }
     }
     return pushes;
 }