Example #1
0
        public static bool MovePiece(ChessBoard board, byte sourceIndex, byte destinationIndex)
        {
            ChessPiece piece = board.pieces[sourceIndex];

            //Do the actual move
            ChessEngine.MoveContent(board, sourceIndex, destinationIndex, ChessPieceType.Queen);
            PieceValidMoves.GenerateValidMoves(board);

            //If there is a check in place and still check
            if (piece.PieceColor == ChessPieceColor.White)
            {
                if (board.whiteInCheck)
                {
                    //Invalid Move -> undo last move
                    ChessEngine.MoveContent(board, destinationIndex, sourceIndex, ChessPieceType.Queen);
                    PieceValidMoves.GenerateValidMoves(board);
                    return false;
                }
            }
            else if (board.blackInCheck)
                {
                    //Invalid Move -> undo last move
                    ChessEngine.MoveContent(board, destinationIndex, sourceIndex, ChessPieceType.Queen);
                    PieceValidMoves.GenerateValidMoves(board);
                    return false;
                }
            return true;
        }
Example #2
0
 /// <summary>
 /// The constructor.
 /// </summary>
 /// <param name="board">The board in which the square is located.</param>
 /// <param name="location">The location of the square.</param>
 /// <param name="color">The color of the square.</param>
 /// <param name="piece">The Chess piece that is on the square.</param>
 public Square(ChessBoard board, Location location, ChessColor color, ChessPiece piece = null)
 {
     this.Board = board;
     this.Location = location;
     this.Color = color;
     this.Piece = piece;
 }
Example #3
0
        /// <summary>
        /// Evaluates a board. The number of point is greater than 0 if white is in advantage, less than 0 if black is.
        /// </summary>
        /// <param name="pBoard">           Board.</param>
        /// <param name="piPiecesCount">    Number of each pieces</param>
        /// <param name="posInfo">          Information about pieces position</param>
        /// <param name="iWhiteKingPos">    Position of the white king</param>
        /// <param name="iBlackKingPos">    Position of the black king</param>
        /// <param name="bWhiteCastle">     White has castled</param>
        /// <param name="bBlackCastle">     Black has castled</param>
        /// <param name="iMoveCountDelta">  Number of possible white move - Number of possible black move</param>
        /// <returns>
        /// Points
        /// </returns>
        public virtual int Points(ChessBoard.PieceE[]   pBoard,
                                  int[]                 piPiecesCount,
                                  ChessBoard.PosInfoS   posInfo,
                                  int                   iWhiteKingPos,
                                  int                   iBlackKingPos,
                                  bool                  bWhiteCastle,
                                  bool                  bBlackCastle,
                                  int                   iMoveCountDelta)
        {
            int iRetVal = 0;

            for (int iIndex = 0; iIndex < piPiecesCount.Length; iIndex++) {
                iRetVal += s_piPiecePoint[iIndex] * piPiecesCount[iIndex];
            }
            if (pBoard[12] == ChessBoard.PieceE.Pawn) {
                iRetVal -= 4;
            }
            if (pBoard[52] == (ChessBoard.PieceE.Pawn | ChessBoard.PieceE.Black)) {
                iRetVal += 4;
            }
            if (bWhiteCastle) {
                iRetVal += 10;
            }
            if (bBlackCastle) {
                iRetVal -= 10;
            }
            iRetVal += iMoveCountDelta;
            iRetVal += posInfo.m_iAttackedPieces * 2;
            //iRetVal += posInfo.m_iAttackedPos + posInfo.m_iAttackedPieces * 2 + posInfo.m_iPiecesDefending * 2;
            return(iRetVal);
        }
Example #4
0
        public ChessBoard(ChessBoard board)
        {
            Score = board.Score;
            EndGamePhase = board.EndGamePhase;
            WhoseMove = board.WhoseMove;
            MoveCount = board.MoveCount;
            FiftyMove = board.FiftyMove;
            RepeatedMove = board.RepeatedMove;

            blackCastled = board.blackCastled;
            blackInCheck = board.blackInCheck;
            blackInMate = board.blackInMate;
            whiteCastled = board.whiteCastled;
            whiteInCheck = board.whiteInCheck;
            whiteInMate = board.whiteInMate;
            staleMate = board.staleMate;
            EnPassantColor = board.EnPassantColor;
            EnPassantPosition = board.EnPassantPosition;
            InsufficientMaterial = board.InsufficientMaterial;

            LastMove = new MoveContent(board.LastMove);

            pieces = new ChessPiece[64];
            for (byte x = 0; x < 64; ++x)
            {
                if (board.pieces[x] != null)
                {
                    pieces[x] = new ChessPiece(board.pieces[x]);
                }
            }
        }
        public void SearchEngine()
        {
            var board = new ChessBoard();

            ChessBoard.MovePosS bestMove;
            int iPremCount;
            int iCacheHit;
            int iMaxDepth;

            board.FindBestMove(
                new SearchEngine.SearchMode(
                    new BoardEvaluationUtil().BoardEvaluators[0],
                    new BoardEvaluationUtil().BoardEvaluators[0],
                    SrcChess2.SearchEngine.SearchMode.OptionE.UseAlphaBeta,
                    SrcChess2.SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch,
                    2,
                    15,
                    SrcChess2.SearchEngine.SearchMode.RandomModeE.Off
                    ),
                ChessBoard.PlayerColorE.Black,
                out bestMove,
                out iPremCount,
                out iCacheHit,
                out iMaxDepth);
            Console.WriteLine(bestMove.StartPos + @"   " + bestMove.EndPos);
        }
Example #6
0
        static void Main(string[] args)
        {
            Board = new ChessBoard();
            Board.GameEnded += (b, w) => { Winner = w; };

            while (!Board.GameOver)
            {
                Draw();
                Console.SetCursorPosition(40, 22);
                Console.Write("From: ");
                string from = Console.ReadLine();
                Console.SetCursorPosition(40, 23);
                Console.Write("To:   ");
                string to = Console.ReadLine();

                Console.SetCursorPosition(40, 21);

                try
                {
                    if (!Board[from].To(Board[to]))
                    {
                        Console.Write("Invalid move.");
                        Console.ReadLine();
                    }
                }
                catch { Console.Write("Invalid move."); Console.ReadLine(); }
            }

            Draw();
            Console.SetCursorPosition(40, 22);
            Console.Write("Game Over: ");
            Console.Write((Winner == ChessWinner.StaleMate ? "Stalemate" : Winner.ToString() + " won") + "!");
            Console.ReadLine();
        }
        protected override Int32 Evaluate(ChessBoard myBoard, ChessPiece turn, Int16 depth)
        {
            IncrementSearchCount();
            var materialValue = (turn == ChessPiece.White ? 1 : -1) * myBoard.GetMaterialValue(this.ChessPieceRelativeValues, depth);
            var positionalValue = (turn == ChessPiece.White ? 1 : -1) * myBoard.GetPositionalValue();

            return MaterialFactor * materialValue + PositionalFactor * positionalValue;
        }
        public void Stage(ChessBoard b)
        {
            b.Set("a2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a5", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("b4", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
        }
        public void Stage(ChessBoard b)
        {
            b.Set("d5", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Queen });


            b.Set("g7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("h7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
        }
Example #10
0
        public void Stage(ChessBoard b)
        {
            b.Set("a7", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h7", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });
        }
Example #11
0
        public void Stage(ChessBoard b)
        {
            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("c1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("d1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("g1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("c2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("d2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("g2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("c3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("d3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("g3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h3", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("c4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("d4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("g4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });


            b.Set("a7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("b7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("c7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("d7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("e7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("f7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("g7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("h7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            b.Set("a8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });
            b.Set("b8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Knight });
            b.Set("c8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Bishop });
            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });
            b.Set("d8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Queen });
            b.Set("f8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Bishop });
            b.Set("g8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Knight });
            b.Set("h8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });
        }
        public void Stage(ChessBoard b)
        {
            b.Set("d4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Bishop });
            b.Set("e5", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });

            b.Set("h8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });
        }
 public void TurnColor()
 {
     var board = new ChessBoard();
     Console.WriteLine(board.CurrentMoveColor);
     board.DoMove(new ChessBoard.MovePosS()
     {
         EndPos = 17,
         StartPos = 9
     });
     Console.WriteLine(board.CurrentMoveColor);
 }
Example #14
0
        internal static bool CheckForMate(ChessPieceColor whosTurn, ChessBoard chessBoard)
        {
            SearchMove.SearchForMate(whosTurn, chessBoard, ref chessBoard.blackInMate,
                  ref chessBoard.whiteInMate, ref chessBoard.staleMate);

            if (chessBoard.blackInMate || chessBoard.whiteInMate || chessBoard.staleMate)
            {
                return true;
            }

            return false;
        }
 public void Turn()
 {
     var board = new ChessBoard();
     var piece = board[17];
     Console.WriteLine(piece.ToString());
     board.DoMove(new ChessBoard.MovePosS()
     {
         EndPos = 17,
         StartPos = 9
     });
     piece = board[17];
     Console.WriteLine(piece.ToString());
 }
Example #16
0
 public static int rateMaterial(bool isWhite, ChessBoard c)
 {
     int counter = 0;
     int numBishops = 0;
     BitboardLayer[] dict = c.getDict(isWhite);
     for (int j = 0; j <= pieceIndex.KING; j++)
     {
         foreach (int i in dict[j].getTrueIndicies()) {
             if (j != pieceIndex.BISHOP) counter += pieceVals[j];
             else numBishops++;
         }
     }
     if (numBishops >= 2) counter += 300 * numBishops;
     else counter += 250 * numBishops;
     return (int)(counter * 1.75);
 }
Example #17
0
    public static bool GetBishopMoveList( ChessBoard board, ChessBoardSquare selSquare, List<sMove> listRetBoardPos )
    {
        // left-up - diagonal
        GetStraightMoveList( board, selSquare, listRetBoardPos, MoveDirectionType.eDirection_Move_LeftUp_Diagonal );
        // left-down - diagonal
        GetStraightMoveList( board, selSquare, listRetBoardPos, MoveDirectionType.eDirection_Move_LeftDown_Diagonal );
        // right-up - diagonal
        GetStraightMoveList( board, selSquare, listRetBoardPos, MoveDirectionType.eDirection_Move_RightUp_Diagonal );
        // right-down - diagonal
        GetStraightMoveList( board, selSquare, listRetBoardPos, MoveDirectionType.eDirection_Move_RightDown_Diagonal );

        if( listRetBoardPos.Count > 0 )
            return true;

        return false;
    }
Example #18
0
        public static int quickRating(bool isWhite, ChessBoard c, int possibleMoves, int depth)
        {
            //designed for sorting for alphabeta
            //for these purposes, we care less about moves that increase moveability or attack
            //hopefully
            int counter = 0;
            int material = rateMaterial(isWhite, c);
            counter += material;
            counter += ratePositional(isWhite, c, material);

            isWhite = !isWhite;

            material = rateMaterial(isWhite, c);
            counter -= material;
            counter -= ratePositional(isWhite, c, material);
            return counter;
        }
        public void Stage(ChessBoard b)
        {
            b.Set("b1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Knight });
            b.Set("g1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Knight });

            b.Set("a2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("c2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("d2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("g2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("b8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Knight });
            b.Set("g8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Knight });
        }
Example #20
0
        public static void EngineMove(ChessBoard board)
        {
            if (CheckForMate(board.WhoseMove, board))
            {
                return;
            }

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            //If there is no playbook move search for the best move
            MoveContent bestMove = SearchMove.AlphaBetaRoot(board, Constants.ply);
            ChessEngine.MoveContent(board, bestMove.MovingPiecePrimary.SrcPosition, bestMove.MovingPiecePrimary.DstPosition, ChessPieceType.Queen);

            PieceValidMoves.GenerateValidMoves(board);
            Evaluation.EvaluateBoardScore(board);

            System.Diagnostics.Debug.WriteLine("Engine Move Time: " + watch.ElapsedTicks);
        }
Example #21
0
 public static bool IsValidMove(ChessBoard board, byte sourceIndex, byte destinationIndex)
 {
     ChessPiece piece = board.pieces[sourceIndex];
     if (piece == null)
     {
         return false;
     }
     foreach (byte bs in piece.ValidMoves)
     {
         if (bs == destinationIndex)
         {
             return true;
         }
     }
     if (destinationIndex == board.EnPassantPosition)
     {
         return true;
     }
     return false;
 }
        public void Stage(ChessBoard b)
        {
            b.Set("a2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("b2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("g2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });

            b.Set("h1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });

            b.Set("a7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("b7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            b.Set("g7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("h7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            b.Set("a8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });

            b.Set("h8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });
        }
Example #23
0
 public static int rateAttack(bool isWhite, ChessBoard c)
 {
     BitboardLayer[] dict = c.getDict(isWhite);
     BitboardLayer attackedSqs = c.getAllAttackedSq(isWhite);
     int counter = 0;
     for (int j = 0; j <= pieceIndex.KING; j++) //don't include king
     {
         foreach (int i in dict[j].getTrueIndicies())
         {
             if (attackedSqs.trueAtIndex(i))
             {
                 switch (j)
                 {
                     case pieceIndex.PAWN:
                         counter -= 64;
                         break;
                     case pieceIndex.ROOK:
                         counter -= 500;
                         break;
                     case pieceIndex.KNIGHT:
                         counter -= 300;
                         break;
                     case pieceIndex.BISHOP:
                         counter -= 300;
                         break;
                     case pieceIndex.QUEEN:
                         counter -= 900;
                         break;
                     case pieceIndex.KING:
                         counter -= 200;
                         break;
                 }
             }
         }
     }
     return (int)(counter * .5);
 }
Example #24
0
        protected override Int32 Evaluate(ChessBoard myBoard, ChessPiece turn, Int16 depth)
        {
            //bool canMove;
            IncrementSearchCount();
            var materialValue = myBoard.GetMaterialValue(this.ChessPieceRelativeValues, depth);
            var positionalValue = myBoard.GetPositionalValue();

            /*  TBD!!
            if (!canMove)
            {
                if (turn == this.MySuit)
                {
                    // I am mated or stale mated
                    return myBoard.InCheck(turn) ? -WonScore : StaleMateScore;
                }
                else
                {
                    // Opponent is mated or stale mated
                    return myBoard.InCheck(turn) ? WonScore : StaleMateScore;
                }
            }*/

            return MaterialFactor * materialValue + PositionalFactor * positionalValue;
        }
        /// <summary>
        /// Find the best move for a player using alpha-beta in a secondary thread
        /// </summary>
        /// <param name="board">            Chess board</param>
        /// <param name="searchMode">       Search mode</param>
        /// <param name="ePlayer">          Color doing the move</param>
        /// <param name="iThreadId">        Thread Id (0-n)</param>
        /// <param name="moveList">         List of move to try</param>
        /// <param name="posInfoWhite">     Information about pieces attacks for the white</param>
        /// <param name="posInfoBlack">     Information about pieces attacks for the black</param>
        /// <param name="iTotalMoveCount">  Total number of moves</param>
        /// <param name="iAlpha">           Alpha bound</param>
        /// <param name="iBeta">            Beta bound</param>
        /// <returns>
        /// Points
        /// </returns>
        private AlphaBetaResult FindBestMoveUsingAlphaBetaAsync(ChessBoard board,
                                                                SearchMode searchMode,
                                                                ChessBoard.PlayerE ePlayer,
                                                                int iThreadId,
                                                                List <Move> moveList,
                                                                ChessBoard.PosInfoS posInfoWhite,
                                                                ChessBoard.PosInfoS posInfoBlack,
                                                                int iTotalMoveCount,
                                                                int iAlpha,
                                                                int iBeta)
        {
            AlphaBetaResult resRetVal;
            DateTime        dtTimeOut;
            int             iDepth;
            int             iPermCountAtLevel;
            int             iPoint;
            int             iBestMoveIndex;
            int             iDepthLimit;

            int[] arrPoints;
            System.Threading.ThreadPriority eThreadPriority;
            TransTable transTable;
            bool       bTimeOut;
            bool       bIterativeDepthFirst;

            resRetVal       = new AlphaBetaResult();
            eThreadPriority = System.Threading.Thread.CurrentThread.Priority;
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;
            if ((searchMode.m_eOption & SearchMode.OptionE.UseTransTable) != 0)
            {
                transTable = TransTable.GetTransTable(iThreadId);
                transTable.Reset();
            }
            else
            {
                transTable = null;
            }
            bIterativeDepthFirst                = (searchMode.m_eOption.HasFlag(SearchMode.OptionE.UseIterativeDepthSearch));
            resRetVal.movePosBest.StartPos      = 255;
            resRetVal.movePosBest.EndPos        = 255;
            resRetVal.movePosBest.OriginalPiece = ChessBoard.PieceE.None;
            resRetVal.movePosBest.Type          = Move.TypeE.Normal;
            try {
                resRetVal.iPermCount = 0;
                if (searchMode.m_iSearchDepth == 0 || bIterativeDepthFirst)
                {
                    dtTimeOut      = (bIterativeDepthFirst) ? DateTime.MaxValue : DateTime.Now + TimeSpan.FromSeconds(searchMode.m_iTimeOutInSec);
                    iDepthLimit    = (bIterativeDepthFirst) ? searchMode.m_iSearchDepth : 999;
                    iDepth         = 1;
                    resRetVal.iPts = FindBestMoveUsingAlphaBetaAtDepth(board,
                                                                       searchMode,
                                                                       ePlayer,
                                                                       moveList,
                                                                       posInfoWhite,
                                                                       posInfoBlack,
                                                                       iTotalMoveCount,
                                                                       iDepth,
                                                                       iAlpha,
                                                                       iBeta,
                                                                       transTable,
                                                                       DateTime.MaxValue,
                                                                       out iPermCountAtLevel,
                                                                       out iBestMoveIndex,
                                                                       out bTimeOut,
                                                                       out arrPoints);
                    if (iBestMoveIndex != -1)
                    {
                        resRetVal.movePosBest = moveList[iBestMoveIndex];
                    }
                    resRetVal.iPermCount += iPermCountAtLevel;
                    resRetVal.iMaxDepth   = iDepth;
                    while (DateTime.Now < dtTimeOut && !m_bCancelSearch && !bTimeOut && iDepth < iDepthLimit)
                    {
                        moveList = SortMoveList(moveList, arrPoints);
                        iDepth++;
                        iPoint = FindBestMoveUsingAlphaBetaAtDepth(board,
                                                                   searchMode,
                                                                   ePlayer,
                                                                   moveList,
                                                                   posInfoWhite,
                                                                   posInfoBlack,
                                                                   iTotalMoveCount,
                                                                   iDepth,
                                                                   iAlpha,
                                                                   iBeta,
                                                                   transTable,
                                                                   dtTimeOut,
                                                                   out iPermCountAtLevel,
                                                                   out iBestMoveIndex,
                                                                   out bTimeOut,
                                                                   out arrPoints);
                        if (!bTimeOut)
                        {
                            if (iBestMoveIndex != -1)
                            {
                                resRetVal.movePosBest = moveList[iBestMoveIndex];
                            }
                            resRetVal.iPermCount += iPermCountAtLevel;
                            resRetVal.iMaxDepth   = iDepth;
                            resRetVal.iPts        = iPoint;
                        }
                    }
                }
                else
                {
                    resRetVal.iMaxDepth = searchMode.m_iSearchDepth;
                    resRetVal.iPts      = FindBestMoveUsingAlphaBetaAtDepth(board,
                                                                            searchMode,
                                                                            ePlayer,
                                                                            moveList,
                                                                            posInfoWhite,
                                                                            posInfoBlack,
                                                                            iTotalMoveCount,
                                                                            resRetVal.iMaxDepth,
                                                                            iAlpha,
                                                                            iBeta,
                                                                            transTable,
                                                                            DateTime.MaxValue,
                                                                            out resRetVal.iPermCount,
                                                                            out iBestMoveIndex,
                                                                            out bTimeOut,
                                                                            out arrPoints);
                    if (iBestMoveIndex != -1)
                    {
                        resRetVal.movePosBest = moveList[iBestMoveIndex];
                    }
                }
            } finally {
                System.Threading.Thread.CurrentThread.Priority = eThreadPriority;
            }
            return(resRetVal);
        }
Example #26
0
        public ChessMove GetNextMove(ChessBoard currentBoard)
        {
            _isGetNextMoveCall = true;

            _currentBoard = currentBoard.Clone();

            if (this.IsHuman)
            {
                _waitForPlayerEvent.Reset();
                _waitForPlayerEvent.WaitOne();
            }
            else
            {
                StartAiInTimedThread(UvsChess.Gui.Preferences.Time);
            }

            return _moveToReturn;
        }
Example #27
0
 internal static int Sort(ChessBoard s2, ChessBoard s1)
 {
     return (s1.Score).CompareTo(s2.Score);
 }
Example #28
0
 void Start()
 {
     CB = GameObject.Find("棋盘").GetComponent <ChessBoard>();
 }
Example #29
0
        public static int CalculateOthers(ChessBoard cb)
        {
            var  score = 0;
            long piece;

            var whites           = cb.Pieces[White][All];
            var whitePawns       = cb.Pieces[White][Pawn];
            var blacks           = cb.Pieces[Black][All];
            var blackPawns       = cb.Pieces[Black][Pawn];
            var whitePawnAttacks = cb.Attacks[White][Pawn];
            var blackPawnAttacks = cb.Attacks[Black][Pawn];

            // side to move
            score += ColorFactor[cb.ColorToMove] * EvalConstants.SideToMoveBonus;

            // WHITE ROOK
            if (cb.Pieces[White][Rook] != 0)
            {
                piece = cb.Pieces[White][Rook];

                // rook battery (same file)
                if (BitOperations.PopCount((ulong)piece) == 2)
                {
                    if ((BitOperations.TrailingZeroCount(piece) & 7) ==
                        ((63 - BitOperations.LeadingZeroCount((ulong)piece)) & 7))
                    {
                        score += EvalConstants.OtherScores[EvalConstants.IxRookBattery];
                    }
                }

                // rook on 7th, king on 8th
                if (cb.KingIndex[Black] >= 56 && (piece & Bitboard.Rank7) != 0)
                {
                    score += BitOperations.PopCount((ulong)(piece & Bitboard.Rank7)) *
                             EvalConstants.OtherScores[EvalConstants.IxRook7ThRank];
                }

                // prison
                if ((piece & Bitboard.Rank1) != 0)
                {
                    var trapped = piece & EvalConstants.RookPrison[cb.KingIndex[White]];
                    if (trapped != 0)
                    {
                        if ((((trapped << 8) | (trapped << 16)) & whitePawns) != 0)
                        {
                            score += EvalConstants.OtherScores[EvalConstants.IxRookTrapped];
                        }
                    }
                }

                // rook on open-file (no pawns) and semi-open-file (no friendly pawns)
                while (piece != 0)
                {
                    if ((whitePawns & Bitboard.GetFile(piece)) == 0)
                    {
                        if ((blackPawns & Bitboard.GetFile(piece)) == 0)
                        {
                            score += EvalConstants.OtherScores[EvalConstants.IxRookFileOpen];
                        }
                        else if ((blackPawns & blackPawnAttacks & Bitboard.GetFile(piece)) == 0)
                        {
                            score += EvalConstants.OtherScores[EvalConstants.IxRookFileSemiOpenIsolated];
                        }
                        else
                        {
                            score += EvalConstants.OtherScores[EvalConstants.IxRookFileSemiOpen];
                        }
                    }

                    piece &= piece - 1;
                }
            }

            // BLACK ROOK
            if (cb.Pieces[Black][Rook] != 0)
            {
                piece = cb.Pieces[Black][Rook];

                // rook battery (same file)
                if (BitOperations.PopCount((ulong)piece) == 2)
                {
                    if ((BitOperations.TrailingZeroCount(piece) & 7) ==
                        ((63 - BitOperations.LeadingZeroCount((ulong)piece)) & 7))
                    {
                        score -= EvalConstants.OtherScores[EvalConstants.IxRookBattery];
                    }
                }

                // rook on 2nd, king on 1st
                if (cb.KingIndex[White] <= 7 && (piece & Bitboard.Rank2) != 0)
                {
                    score -= BitOperations.PopCount((ulong)(piece & Bitboard.Rank2)) *
                             EvalConstants.OtherScores[EvalConstants.IxRook7ThRank];
                }

                // prison
                if ((piece & Bitboard.Rank8) != 0)
                {
                    var trapped = piece & EvalConstants.RookPrison[cb.KingIndex[Black]];
                    if (trapped != 0)
                    {
                        if (((Util.RightTripleShift(trapped, 8) | Util.RightTripleShift(trapped, 16)) & blackPawns) !=
                            0)
                        {
                            score -= EvalConstants.OtherScores[EvalConstants.IxRookTrapped];
                        }
                    }
                }

                // rook on open-file (no pawns) and semi-open-file (no friendly pawns)
                while (piece != 0)
                {
                    // TODO JITWatch unpredictable branch
                    if ((blackPawns & Bitboard.GetFile(piece)) == 0)
                    {
                        if ((whitePawns & Bitboard.GetFile(piece)) == 0)
                        {
                            score -= EvalConstants.OtherScores[EvalConstants.IxRookFileOpen];
                        }
                        else if ((whitePawns & whitePawnAttacks & Bitboard.GetFile(piece)) == 0)
                        {
                            score -= EvalConstants.OtherScores[EvalConstants.IxRookFileSemiOpenIsolated];
                        }
                        else
                        {
                            score -= EvalConstants.OtherScores[EvalConstants.IxRookFileSemiOpen];
                        }
                    }

                    piece &= piece - 1;
                }
            }

            // WHITE BISHOP
            if (cb.Pieces[White][Bishop] != 0)
            {
                // bishop outpost: protected by a pawn, cannot be attacked by enemy pawns
                piece = cb.Pieces[White][Bishop] & cb.PassedPawnsAndOutposts & whitePawnAttacks;
                if (piece != 0)
                {
                    score += BitOperations.PopCount((ulong)piece) * EvalConstants.OtherScores[EvalConstants.IxOutpost];
                }

                piece = cb.Pieces[White][Bishop];
                if ((piece & Bitboard.WhiteSquares) != 0)
                {
                    // pawns on same color as bishop
                    score += EvalConstants.BishopPawn[
                        BitOperations.PopCount((ulong)(whitePawns & Bitboard.WhiteSquares))];

                    // attacking center squares
                    if (BitOperations.PopCount((ulong)(cb.Attacks[White][Bishop] & Bitboard.E4D5)) == 2)
                    {
                        score += EvalConstants.OtherScores[EvalConstants.IxBishopLong];
                    }
                }

                if ((piece & Bitboard.BlackSquares) != 0)
                {
                    // pawns on same color as bishop
                    score += EvalConstants.BishopPawn[
                        BitOperations.PopCount((ulong)(whitePawns & Bitboard.BlackSquares))];

                    // attacking center squares
                    if (BitOperations.PopCount((ulong)(cb.Attacks[White][Bishop] & Bitboard.D4E5)) == 2)
                    {
                        score += EvalConstants.OtherScores[EvalConstants.IxBishopLong];
                    }
                }

                // prison
                piece &= Bitboard.Rank2;
                while (piece != 0)
                {
                    if (BitOperations.PopCount(
                            (ulong)(EvalConstants.BishopPrison[BitOperations.TrailingZeroCount(piece)] & blackPawns)) == 2)
                    {
                        score += EvalConstants.OtherScores[EvalConstants.IxBishopPrison];
                    }

                    piece &= piece - 1;
                }
            }

            // BLACK BISHOP
            if (cb.Pieces[Black][Bishop] != 0)
            {
                // bishop outpost: protected by a pawn, cannot be attacked by enemy pawns
                piece = cb.Pieces[Black][Bishop] & cb.PassedPawnsAndOutposts & blackPawnAttacks;
                if (piece != 0)
                {
                    score -= BitOperations.PopCount((ulong)piece) * EvalConstants.OtherScores[EvalConstants.IxOutpost];
                }

                piece = cb.Pieces[Black][Bishop];
                if ((piece & Bitboard.WhiteSquares) != 0)
                {
                    // penalty for many pawns on same color as bishop
                    score -= EvalConstants.BishopPawn[
                        BitOperations.PopCount((ulong)(blackPawns & Bitboard.WhiteSquares))];

                    // bonus for attacking center squares
                    if (BitOperations.PopCount((ulong)(cb.Attacks[Black][Bishop] & Bitboard.E4D5)) == 2)
                    {
                        score -= EvalConstants.OtherScores[EvalConstants.IxBishopLong];
                    }
                }

                if ((piece & Bitboard.BlackSquares) != 0)
                {
                    // penalty for many pawns on same color as bishop
                    score -= EvalConstants.BishopPawn[
                        BitOperations.PopCount((ulong)(blackPawns & Bitboard.BlackSquares))];

                    // bonus for attacking center squares
                    if (BitOperations.PopCount((ulong)(cb.Attacks[Black][Bishop] & Bitboard.D4E5)) == 2)
                    {
                        score -= EvalConstants.OtherScores[EvalConstants.IxBishopLong];
                    }
                }

                // prison
                piece &= Bitboard.Rank7;
                while (piece != 0)
                {
                    if (BitOperations.PopCount(
                            (ulong)(EvalConstants.BishopPrison[BitOperations.TrailingZeroCount(piece)] & whitePawns)) == 2)
                    {
                        score -= EvalConstants.OtherScores[EvalConstants.IxBishopPrison];
                    }

                    piece &= piece - 1;
                }
            }

            // pieces supporting our pawns
            piece = (whitePawns << 8) & whites;
            while (piece != 0)
            {
                score += EvalConstants.PawnBlockage[Util.RightTripleShift(BitOperations.TrailingZeroCount(piece), 3)];
                piece &= piece - 1;
            }

            piece = Util.RightTripleShift(blackPawns, 8) & blacks;
            while (piece != 0)
            {
                score -= EvalConstants.PawnBlockage[7 - BitOperations.TrailingZeroCount(piece) / 8];
                piece &= piece - 1;
            }

            // knight outpost: protected by a pawn, cannot be attacked by enemy pawns
            piece = cb.Pieces[White][Knight] & cb.PassedPawnsAndOutposts & whitePawnAttacks;
            if (piece != 0)
            {
                score += BitOperations.PopCount((ulong)piece) * EvalConstants.OtherScores[EvalConstants.IxOutpost];
            }

            piece = cb.Pieces[Black][Knight] & cb.PassedPawnsAndOutposts & blackPawnAttacks;
            if (piece != 0)
            {
                score -= BitOperations.PopCount((ulong)piece) * EvalConstants.OtherScores[EvalConstants.IxOutpost];
            }

            // pinned-pieces
            if (cb.PinnedPieces != 0)
            {
                piece = cb.PinnedPieces & whites;
                while (piece != 0)
                {
                    score += EvalConstants.Pinned[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                    piece &= piece - 1;
                }

                piece = cb.PinnedPieces & blacks;
                while (piece != 0)
                {
                    score -= EvalConstants.Pinned[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                    piece &= piece - 1;
                }
            }

            // discovered-pieces
            if (cb.DiscoveredPieces != 0)
            {
                piece = cb.DiscoveredPieces & whites;
                while (piece != 0)
                {
                    score += EvalConstants.Discovered[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                    piece &= piece - 1;
                }

                piece = cb.DiscoveredPieces & blacks;
                while (piece != 0)
                {
                    score -= EvalConstants.Discovered[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                    piece &= piece - 1;
                }
            }

            if (cb.CastlingRights == 0)
            {
                return(score);
            }
            score += BitOperations.PopCount((ulong)(cb.CastlingRights & 12)) *
                     EvalConstants.OtherScores[EvalConstants.IxCastling];
            score -= BitOperations.PopCount((ulong)(cb.CastlingRights & 3)) *
                     EvalConstants.OtherScores[EvalConstants.IxCastling];

            return(score);
        }
Example #30
0
 public void OnEachMoveStart(ChessBoard chessBoard)
 {
     moveTimeRecorder = new TimeRecorder();
 }
        /// <summary>
        /// Alpha Beta pruning function.
        /// </summary>
        /// <param name="board">            Chess board</param>
        /// <param name="ePlayer">          Color doing the move</param>
        /// <param name="iDepth">           Actual search depth</param>
        /// <param name="iAlpha">           Alpha limit</param>
        /// <param name="iBeta">            Beta limit</param>
        /// <param name="iWhiteMoveCount">  Number of moves white can do</param>
        /// <param name="iBlackMoveCount">  Number of moves black can do</param>
        /// <param name="abInfo">           Supplemental information</param>
        /// <returns>
        /// Points to give for this move or Int32.MinValue for timed out
        /// </returns>
        private int AlphaBeta(ChessBoard board,
                              ChessBoard.PlayerE ePlayer,
                              int iDepth,
                              int iAlpha,
                              int iBeta,
                              int iWhiteMoveCount,
                              int iBlackMoveCount,
                              AlphaBetaInfo abInfo)
        {
            int         iRetVal;
            List <Move> moveList;
            int         iPts;
            int         iMoveCount;

            ChessBoard.PosInfoS posInfo;
            TransEntryTypeE     eType = TransEntryTypeE.Alpha;

            ChessBoard.BoardStateMaskE eBoardExtraInfo;
            ChessBoard.RepeatResultE   eResult;

            if (abInfo.m_dtTimeOut != DateTime.MaxValue && DateTime.Now >= abInfo.m_dtTimeOut)
            {
                iRetVal = Int32.MinValue;   // Time out!
            }
            else if (board.IsEnoughPieceForCheckMate())
            {
                eBoardExtraInfo = board.ComputeBoardExtraInfo(ePlayer, true);
                iRetVal         = (abInfo.m_transTable != null) ? abInfo.m_transTable.ProbeEntry(board.CurrentZobristKey, eBoardExtraInfo, iDepth, iAlpha, iBeta) : Int32.MaxValue;
                if (iRetVal == Int32.MaxValue)
                {
                    if (iDepth == 0 || m_bCancelSearch)
                    {
                        iRetVal = board.Points(abInfo.m_searchMode, ePlayer, abInfo.m_iMaxDepth - iDepth, iWhiteMoveCount - iBlackMoveCount, abInfo.m_posInfoWhite, abInfo.m_posInfoBlack);
                        if (ePlayer == ChessBoard.PlayerE.Black)
                        {
                            iRetVal = -iRetVal;
                        }
                        abInfo.m_iPermCount++;
                        if (abInfo.m_transTable != null)
                        {
                            abInfo.m_transTable.RecordEntry(board.CurrentZobristKey, eBoardExtraInfo, iDepth, iRetVal, TransEntryTypeE.Exact);
                        }
                    }
                    else
                    {
                        moveList   = board.EnumMoveList(ePlayer, true, out posInfo);
                        iMoveCount = moveList.Count;
                        if (ePlayer == ChessBoard.PlayerE.White)
                        {
                            iWhiteMoveCount       = iMoveCount;
                            abInfo.m_posInfoWhite = posInfo;
                        }
                        else
                        {
                            iBlackMoveCount       = iMoveCount;
                            abInfo.m_posInfoBlack = posInfo;
                        }
                        if (iMoveCount == 0)
                        {
                            if (board.IsCheck(ePlayer))
                            {
                                iRetVal = -1000000 - iDepth;
                            }
                            else
                            {
                                iRetVal = 0;    // Draw
                            }
                            if (abInfo.m_transTable != null)
                            {
                                abInfo.m_transTable.RecordEntry(board.CurrentZobristKey, eBoardExtraInfo, iDepth, iRetVal, TransEntryTypeE.Exact);
                            }
                        }
                        else
                        {
                            iRetVal = iAlpha;
                            foreach (Move move in moveList)
                            {
                                eResult = board.DoMoveNoLog(move);
                                abInfo.m_arrMove[iDepth - 1] = move;
                                if (eResult == ChessBoard.RepeatResultE.NoRepeat)
                                {
                                    iPts = -AlphaBeta(board,
                                                      (ePlayer == ChessBoard.PlayerE.Black) ? ChessBoard.PlayerE.White : ChessBoard.PlayerE.Black,
                                                      iDepth - 1,
                                                      -iBeta,
                                                      -iRetVal,
                                                      iWhiteMoveCount,
                                                      iBlackMoveCount,
                                                      abInfo);
                                }
                                else
                                {
                                    iPts = 0;
                                }
                                board.UndoMoveNoLog(move);
                                if (iPts == Int32.MinValue)
                                {
                                    iRetVal = iPts;
                                    break;
                                }
                                else
                                {
                                    if (iPts > iRetVal)
                                    {
                                        iRetVal = iPts;
                                        eType   = TransEntryTypeE.Exact;
                                    }
                                    if (iRetVal >= iBeta)
                                    {
                                        iRetVal = iBeta;
                                        eType   = TransEntryTypeE.Beta;
                                        break;
                                    }
                                }
                            }
                            if (abInfo.m_transTable != null && iRetVal != Int32.MinValue)
                            {
                                abInfo.m_transTable.RecordEntry(board.CurrentZobristKey, eBoardExtraInfo, iDepth, iRetVal, eType);
                            }
                        }
                    }
                }
            }
            else
            {
                iRetVal = 0;
            }
            return(iRetVal);
        }
Example #32
0
 public void update(unitControler self, Environment env)
 {
     if (((BasicControler)self).traget == null)
     {
         Debug.Log("basic ai 的 upate");
         ChessBoard map      = (ChessBoard)env;
         int[]      position = map.getPosFor(self);//拿到自己的坐標
         int        posx     = position[0];
         int        posy     = position[1];
         bool       solve    = false;
         if (((BasicControler)self).data.Remote)
         {
             if (((BasicControler)self).playerNo % 2 == 0)
             {
                 Debug.Log("path1");
                 for (int y = 4; y < 8; y++)//先判斷和自己同一行的角色
                 {
                     if (map.board[y, posx] != null && ((BasicControler)map.board[y, posx]).playerNo != 0)
                     {
                         ((BasicControler)self).traget = map.board[y, posx];
                         solve = true;
                         break;
                     }
                 }
                 //不行的話再從前到後依次掃描
                 for (int y = 4; y < 8; y++)
                 {
                     for (int x = 0; x < 5; x++)
                     {
                         if (map.board[y, x] != null && ((BasicControler)map.board[y, x]).playerNo != 0)
                         {
                             ((BasicControler)self).traget = map.board[y, x];
                             solve = true;
                             break;
                         }
                     }
                     if (solve)
                     {
                         break;
                     }
                 }
             }
             else if (((BasicControler)self).playerNo % 2 == 1)
             {
                 Debug.Log("path2");
                 for (int y = 3; y >= 0; y--)//先判斷和自己同一行的角色
                 {
                     if (map.board[y, posx] != null && ((BasicControler)map.board[y, posx]).playerNo != 1)
                     {
                         ((BasicControler)self).traget = map.board[y, posx];
                         solve = true;
                         break;
                     }
                 }
                 //不行的話再從前到後依次掃描
                 for (int y = 3; y >= 0; y--)
                 {
                     for (int x = 0; x < 5; x++)
                     {
                         if (map.board[y, x] != null && ((BasicControler)map.board[y, x]).playerNo != 1)
                         {
                             ((BasicControler)self).traget = map.board[y, x];
                             solve = true;
                             break;
                         }
                     }
                     if (solve)
                     {
                         break;
                     }
                 }
             }
         }
         else
         {
             if (((BasicControler)self).playerNo % 2 == 0)
             {
                 Debug.Log("path3");
                 for (int y = 4; y < 8; y++)
                 {
                     if (map.board[y, posx] != null && ((BasicControler)map.board[y, posx]).playerNo != 0)
                     {
                         ((BasicControler)self).traget = map.board[y, posx];
                         solve = true;
                         break;
                     }
                     for (int x = 0; x < 5; x++)
                     {
                         if (map.board[y, x] != null && ((BasicControler)map.board[y, x]).playerNo != 0)
                         {
                             ((BasicControler)self).traget = map.board[y, x];
                             solve = true;
                             break;
                         }
                     }
                     if (solve)
                     {
                         break;
                     }
                 }
             }
             else if (((BasicControler)self).playerNo % 2 == 1)
             {
                 Debug.Log("path4 objname:" + ((BasicControler)self).gameObject.name);
                 for (int y = 3; y >= 0; y--)
                 {
                     if (map.board[y, posx] != null && ((BasicControler)map.board[y, posx]).playerNo != 1)
                     {
                         ((BasicControler)self).traget = map.board[y, posx];
                         solve = true;
                         break;
                     }
                     for (int x = 0; x < 5; x++)
                     {
                         if (map.board[y, x] != null && ((BasicControler)map.board[y, x]).playerNo != 1)
                         {
                             ((BasicControler)self).traget = map.board[y, x];
                             solve = true;
                             break;
                         }
                     }
                     if (solve)
                     {
                         break;
                     }
                 }
             }
         }
     }
 }
Example #33
0
 public IEnumerable <ChessPiece> GetChecking(ChessBoard board, ChessPosition pos)
 {
     return(board.ProtectedBy(pos, Owner == PlayerColor.White ? PlayerColor.Black : PlayerColor.White));
 }
Example #34
0
 public King(Color color, ChessBoard board, Match match) : base(color, board)
 {
     _match = match;
 }
 private void IntializeChessBoard()
 {
     _chessBoard        = new ChessBoard();
     _chessBoard.Pieces = new List <ChessPiece>();
     //first set
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 1, Position = 1, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.ROOK
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 2, Position = 2, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.KNIGHT
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 3, Position = 3, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.BISHOP
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 4, Position = 4, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.KING
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 5, Position = 5, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.QUEEN
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 6, Position = 6, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.BISHOP
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 7, Position = 7, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.KNIGHT
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 8, Position = 8, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.ROOK
     });
     for (int soliderId = 9; soliderId < 17; soliderId++)
     {
         _chessBoard.Pieces.Add(new ChessPiece {
             Id = soliderId, Position = soliderId, SetType = PIECE_TYPE.BLACK, Name = PIECE_NAME.SOLDIER
         });
     }
     //second set
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 57, Position = 57, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.ROOK
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 58, Position = 58, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.KNIGHT
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 59, Position = 59, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.BISHOP
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 60, Position = 60, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.KING
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 61, Position = 61, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.QUEEN
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 62, Position = 62, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.BISHOP
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 63, Position = 63, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.KNIGHT
     });
     _chessBoard.Pieces.Add(new ChessPiece {
         Id = 64, Position = 64, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.ROOK
     });
     for (int soliderId = 56; soliderId > 48; soliderId--)
     {
         _chessBoard.Pieces.Add(new ChessPiece {
             Id = soliderId, Position = soliderId, SetType = PIECE_TYPE.WHITE, Name = PIECE_NAME.SOLDIER
         });
     }
 }
Example #36
0
 public Tower(ChessBoard chessBoard, Color color)
     : base(chessBoard, color)
 {
 }
Example #37
0
        public void InitialBoardState2()
        {
            ChessBoard b = new ChessBoard();

            var currentPlayer = b.CurrentPlayer;

            currentPlayer.Should().Be(1, "Player 1 should be the first to make a move");
            var stalemate = b.IsStalemate;

            stalemate.Should().BeFalse("there should not be a stalement at the beginning of the game");
            var checkmate = b.IsCheckmate;

            checkmate.Should().BeFalse("there should not be a checkmate at the beginning of the game");
            var check = b.IsCheck;

            check.Should().BeFalse("there should not be a check at the beginning of the game");
            var drawCounter = b.DrawCounter;

            drawCounter.Should().Be(0, "draws should not have happened at the beginning of the game");
            var moveHistory = b.MoveHistory;

            moveHistory.Should().BeEmpty("no moves should have been made yet");
            var isFinished = b.IsFinished;

            isFinished.Should().BeFalse("the game should not be finished at the beginning");
            var currentAdvantage = b.CurrentAdvantage;

            currentAdvantage.Player.Should().Be(0, "no player should have an advantage at the beginning of the game");
            currentAdvantage.Advantage.Should().Be(0, "no player should have an advantage at the beginning of the game");
            char[] columns = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
            foreach (var column in columns)
            {
                var pawnWhite = b.GetPieceAtPosition(Pos(string.Format("{0}2", column)));
                var pawnBlack = b.GetPieceAtPosition(Pos(string.Format("{0}7", column)));
                pawnWhite.PieceType.Should().Be(ChessPieceType.Pawn, "pieces in row 2 should be pawns at the beginning of the game");
                pawnBlack.PieceType.Should().Be(ChessPieceType.Pawn, "pieces in row 7 should be pawns at the beginning of the game");
                if (column == 'a')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Rook, string.Format("piece at ({0},1) should be a rook at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Rook, string.Format("piece at ({0},8) should be a rook at the beginning of the game", column));
                }
                else if (column == 'b')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Knight, string.Format("piece at ({0},1) should be a knight at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Knight, string.Format("piece at ({0},8) should be a knight at the beginning of the game", column));
                }
                else if (column == 'c')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Bishop, string.Format("piece at ({0},1) should be a bishop at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Bishop, string.Format("piece at ({0},8) should be a bishop at the beginning of the game", column));
                }
                else if (column == 'd')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Queen, string.Format("piece at ({0},1) should be a queen at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Queen, string.Format("piece at ({0},8) should be a queen at the beginning of the game", column));
                }
                else if (column == 'e')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.King, string.Format("piece at ({0},1) should be a King at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.King, string.Format("piece at ({0},8) should be a King at the beginning of the game", column));
                }
                else if (column == 'f')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Bishop, string.Format("piece at ({0},1) should be a Bishop at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Bishop, string.Format("piece at ({0},8) should be a Bishop at the beginning of the game", column));
                }
                else if (column == 'g')
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Knight, string.Format("piece at ({0},1) should be a knight at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Knight, string.Format("piece at ({0},8) should be a knight at the beginning of the game", column));
                }
                else
                {
                    var pieceWhite = b.GetPieceAtPosition(Pos(string.Format("{0}1", column)));
                    var pieceBlack = b.GetPieceAtPosition(Pos(string.Format("{0}8", column)));
                    pieceWhite.PieceType.Should().Be(ChessPieceType.Rook, string.Format("piece at ({0},1) should be a rook at the beginning of the game", column));
                    pieceBlack.PieceType.Should().Be(ChessPieceType.Rook, string.Format("piece at ({0},8) should be a rook at the beginning of the game", column));
                }
            }
        }
Example #38
0
 public void SetUp()
 {
     _chessBoard = new ChessBoard();
     _queen      = new Queen(PieceColor.Black, _chessBoard);
     _chessBoard.ResetBoard();
 }
Example #39
0
        public void InitialBoardState()
        {
            ChessBoard b = new ChessBoard();

            // Check row 1
            b.GetPieceAtPosition(Pos("a1")).PieceType.Should().Be(ChessPieceType.Rook, "piece is a Rook");
            b.GetPieceAtPosition(Pos("a1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("b1")).PieceType.Should().Be(ChessPieceType.Knight, "piece is a Knight");
            b.GetPieceAtPosition(Pos("b1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("c1")).PieceType.Should().Be(ChessPieceType.Bishop, "piece is a Bishop");
            b.GetPieceAtPosition(Pos("c1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("d1")).PieceType.Should().Be(ChessPieceType.Queen, "piece is a Queen");
            b.GetPieceAtPosition(Pos("d1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("e1")).PieceType.Should().Be(ChessPieceType.King, "piece is a King");
            b.GetPieceAtPosition(Pos("e1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("f1")).PieceType.Should().Be(ChessPieceType.Bishop, "piece is a Bishop");
            b.GetPieceAtPosition(Pos("f1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("g1")).PieceType.Should().Be(ChessPieceType.Knight, "piece is a Knight");
            b.GetPieceAtPosition(Pos("g1")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("h1")).PieceType.Should().Be(ChessPieceType.Rook, "piece is a Rook");
            b.GetPieceAtPosition(Pos("h1")).Player.Should().Be(1, "piece is white");

            // Check row 2
            b.GetPieceAtPosition(Pos("a2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("a2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("b2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("b2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("c2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("c2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("d2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("d2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("e2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("e2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("f2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("f2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("g2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("g2")).Player.Should().Be(1, "piece is white");

            b.GetPieceAtPosition(Pos("h2")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("h2")).Player.Should().Be(1, "piece is white");

            // Check row 3
            b.GetPieceAtPosition(Pos("a3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("b3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("c3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("d3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("e3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("f3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("g3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("h3")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            // Check row 4
            b.GetPieceAtPosition(Pos("a4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("b4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("c4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("d4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("e4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("f4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("g4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("h4")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            // Check row 5
            b.GetPieceAtPosition(Pos("a5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("b5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("c5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("d5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("e5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("f5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("g5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("h5")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            // Check row 6
            b.GetPieceAtPosition(Pos("a6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("b6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("c6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("d6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("e6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("f6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("g6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            b.GetPieceAtPosition(Pos("h6")).PieceType.Should().Be(ChessPieceType.Empty, "space is Empty");

            // Check row 7
            b.GetPieceAtPosition(Pos("a7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("a7")).Player.Should().Be(2);

            b.GetPieceAtPosition(Pos("b7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("b7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("c7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("c7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("d7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("d7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("e7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("e7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("f7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("f7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("g7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("g7")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("h7")).PieceType.Should().Be(ChessPieceType.Pawn, "piece is a Pawn");
            b.GetPieceAtPosition(Pos("h7")).Player.Should().Be(2, "piece is black");

            // Check row 8
            b.GetPieceAtPosition(Pos("a8")).PieceType.Should().Be(ChessPieceType.Rook, "piece is a Rook");
            b.GetPieceAtPosition(Pos("a8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("b8")).PieceType.Should().Be(ChessPieceType.Knight, "piece is a Knight");
            b.GetPieceAtPosition(Pos("b8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("c8")).PieceType.Should().Be(ChessPieceType.Bishop, "piece is a Bishop");
            b.GetPieceAtPosition(Pos("c8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("d8")).PieceType.Should().Be(ChessPieceType.Queen, "piece is a Queen");
            b.GetPieceAtPosition(Pos("d8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("e8")).PieceType.Should().Be(ChessPieceType.King, "piece is a King");
            b.GetPieceAtPosition(Pos("e8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("f8")).PieceType.Should().Be(ChessPieceType.Bishop, "piece is a Bishop");
            b.GetPieceAtPosition(Pos("f8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("g8")).PieceType.Should().Be(ChessPieceType.Knight, "piece is a Knight");
            b.GetPieceAtPosition(Pos("g8")).Player.Should().Be(2, "piece is black");

            b.GetPieceAtPosition(Pos("h8")).PieceType.Should().Be(ChessPieceType.Rook, "piece is a Rook");
            b.GetPieceAtPosition(Pos("h8")).Player.Should().Be(2, "piece is black");

            // Player 1 moves first
            b.CurrentPlayer.Should().Be(1, "Player 1 moves first");

            // Score should be 0 - 0
            b.CurrentAdvantage.Should().Be(Advantage(0, 0), "score should be tied at 0");
        }
        /// <summary>
        /// Find the best move for a player using alpha-beta
        /// </summary>
        /// <param name="board">        Chess board</param>
        /// <param name="searchMode">   Search mode</param>
        /// <param name="ePlayer">      Player doing the move</param>
        /// <param name="moveList">     Move list</param>
        /// <param name="arrIndex">     Order of evaluation of the moves</param>
        /// <param name="posInfo">      Information about pieces attacks</param>
        /// <param name="moveBest">     Best move found</param>
        /// <param name="iPermCount">   Total permutation evaluated</param>
        /// <param name="iCacheHit">    Number of moves found in the translation table cache</param>
        /// <param name="iMaxDepth">    Maximum depth to use</param>
        /// <returns>
        /// true if a move has been found
        /// </returns>
        protected override bool FindBestMove(ChessBoard board,
                                             SearchMode searchMode,
                                             ChessBoard.PlayerE ePlayer,
                                             List <Move> moveList,
                                             int[]                  arrIndex,
                                             ChessBoard.PosInfoS posInfo,
                                             ref Move moveBest,
                                             out int iPermCount,
                                             out int iCacheHit,
                                             out int iMaxDepth)
        {
            bool bRetVal = false;
            bool bMultipleThread;
            bool bUseTransTable;

            ChessBoard[]             arrBoard;
            Task <AlphaBetaResult>[] taskArray;
            List <Move>[]            arrMoveList;
            AlphaBetaResult          alphaBetaRes;

            ChessBoard.PosInfoS posInfoWhite;
            ChessBoard.PosInfoS posInfoBlack;
            int iAlpha;
            int iBeta;
            int iThreadCount;

            //TODO Enable transposition table when bug on 3 repetition move draw will be found.
            if (ePlayer == ChessBoard.PlayerE.White)
            {
                posInfoWhite = posInfo;
                posInfoBlack = ChessBoard.s_posInfoNull;
            }
            else
            {
                posInfoWhite = ChessBoard.s_posInfoNull;
                posInfoBlack = posInfo;
            }
            searchMode.m_eOption &= ~SearchMode.OptionE.UseTransTable;
            bUseTransTable        = (searchMode.m_eOption.HasFlag(SearchMode.OptionE.UseTransTable));
            iCacheHit             = 0;
            iMaxDepth             = 0;
            iPermCount            = 0;
            iAlpha          = -10000000;
            iBeta           = +10000000;
            bMultipleThread = (searchMode.m_eThreadingMode == SearchMode.ThreadingModeE.OnePerProcessorForSearch);
            iThreadCount    = System.Environment.ProcessorCount;
            if (bMultipleThread && iThreadCount < 2)
            {
                bMultipleThread = false;    // No reason to go with multi-threading if only one processor
            }
            if (bMultipleThread)
            {
                arrBoard    = new ChessBoard[iThreadCount];
                arrMoveList = new List <Move> [iThreadCount];
                taskArray   = new Task <AlphaBetaResult> [iThreadCount];
                for (int iIndex = 0; iIndex < iThreadCount; iIndex++)
                {
                    arrBoard[iIndex]    = board.Clone();
                    arrMoveList[iIndex] = new List <Move>(moveList.Count / iThreadCount + 1);
                    for (int iStep = iIndex; iStep < moveList.Count; iStep += iThreadCount)
                    {
                        arrMoveList[iIndex].Add(moveList[arrIndex[iStep]]);
                    }
                }
                for (int iIndex = 0; iIndex < iThreadCount; iIndex++)
                {
                    taskArray[iIndex] = Task <AlphaBetaResult> .Factory.StartNew((param) => {
                        int iStep = (int)param;
                        return(FindBestMoveUsingAlphaBetaAsync(arrBoard[iStep],
                                                               searchMode,
                                                               ePlayer,
                                                               iStep,
                                                               arrMoveList[iStep],
                                                               posInfoWhite,
                                                               posInfoBlack,
                                                               moveList.Count,
                                                               iAlpha,
                                                               iBeta));
                    }, iIndex);
                }
                iMaxDepth = 999;
                for (int iStep = 0; iStep < iThreadCount; iStep++)
                {
                    alphaBetaRes = taskArray[iStep].Result;
                    if (alphaBetaRes.movePosBest.StartPos != 255)
                    {
                        iPermCount += alphaBetaRes.iPermCount;
                        iMaxDepth   = Math.Min(iMaxDepth, alphaBetaRes.iMaxDepth);
                        if (bUseTransTable)
                        {
                            iCacheHit += TransTable.GetTransTable(iStep).CacheHit;
                        }
                        if (alphaBetaRes.iPts > iAlpha)
                        {
                            iAlpha   = alphaBetaRes.iPts;
                            moveBest = alphaBetaRes.movePosBest;
                            bRetVal  = true;
                        }
                    }
                }
                if (iMaxDepth == 999)
                {
                    iMaxDepth = -1;
                }
            }
            else
            {
                ChessBoard  chessBoardTmp;
                List <Move> moveListTmp;

                chessBoardTmp = board.Clone();
                moveListTmp   = new List <Move>(moveList.Count);
                for (int iIndex = 0; iIndex < moveList.Count; iIndex++)
                {
                    moveListTmp.Add(moveList[arrIndex[iIndex]]);
                }
                alphaBetaRes = FindBestMoveUsingAlphaBetaAsync(chessBoardTmp,
                                                               searchMode,
                                                               ePlayer,
                                                               0,  // ThreadId
                                                               moveListTmp,
                                                               posInfoWhite,
                                                               posInfoBlack,
                                                               moveList.Count,
                                                               iAlpha,
                                                               iBeta);
                iPermCount = alphaBetaRes.iPermCount;
                iMaxDepth  = alphaBetaRes.iMaxDepth;
                if (alphaBetaRes.movePosBest.StartPos != 255)
                {
                    if (bUseTransTable)
                    {
                        iCacheHit += TransTable.GetTransTable(0).CacheHit;
                    }
                    moveBest = alphaBetaRes.movePosBest;
                    bRetVal  = true;
                }
            }
            return(bRetVal);
        }
Example #41
0
 private void InputChessPiece(Piece piece, char colum, int line)
 {
     ChessBoard.InputPiece(piece, new ChessPosition(colum, line).toPosition());
     Pieces.Add(piece);
 }
Example #42
0
        public void MakePlay(Position origin, Position destiny)
        {
            Piece p        = Move(origin, destiny);
            bool  promo    = false;
            Piece promoAux = null;

            //Special Move - Promotion
            if (ChessBoard.Piece(destiny) is Pawn && (destiny.Line == 0 || destiny.Line == 7))
            {
                Console.WriteLine("Chose your Promotion:\nb\tn\tq\tt");
                char  chose      = char.Parse(Console.ReadLine());
                Piece promoPiece = null;
                switch (chose)
                {
                case 'b':
                    promoPiece = new Bishop(ChessBoard, ChessBoard.Piece(destiny).Color);
                    break;

                case 'n':
                    promoPiece = new Knight(ChessBoard, ChessBoard.Piece(destiny).Color);
                    break;

                case 'q':
                    promoPiece = new Queen(ChessBoard, ChessBoard.Piece(destiny).Color);
                    break;

                case 't':
                    promoPiece = new Tower(ChessBoard, ChessBoard.Piece(destiny).Color);
                    break;
                }
                Pieces.Remove(ChessBoard.Piece(destiny));
                ChessBoard.OutputPiece(destiny);
                ChessBoard.InputPiece(promoPiece, destiny);
                Pieces.Add(promoPiece);
                promo = true;
            }
            if (InCheck(PlayerColor))
            {
                if (!promo)
                {
                    ReverseMove(origin, destiny, p);
                }
                else
                {
                    ReverseMove(origin, destiny, p, promoAux);
                }
                throw new BoardException("You can't move this piece, you in xeque");
            }
            if (InCheck(Adversary(PlayerColor)))
            {
                Check = true;
            }
            else
            {
                Check = false;
            }
            if (CheckMate(Adversary(PlayerColor)))
            {
                Finish = true;
            }
            else
            {
                Turn++;
                ChangePlayer();
                Piece Passant = ChessBoard.Piece(destiny);
                if (Passant is Pawn && (destiny.Line == origin.Line + 2 || destiny.Line == origin.Line - 2))
                {
                    EnPassant = Passant;
                }
                else
                {
                    EnPassant = null;
                }
            }
        }
Example #43
0
        public void KingPossibleStartAndPlay_543479()
        {
            ChessBoard board = new ChessBoard();

            board.GetPieceAtPosition(Pos(7, 4)).PieceType.Should().Be(ChessPieceType.King, "White's king at position (7,4)");
            board.GetPieceAtPosition(Pos(0, 4)).PieceType.Should().Be(ChessPieceType.King, "Black's king at position (0,4)");

            var whiteKingPossMoves = GetMovesAtPosition(board.GetPossibleMoves(), Pos(7, 4));
            var blackKingPossMoves = GetMovesAtPosition(board.GetPossibleMoves(), Pos(0, 4));

            // Game State Check of all False
            void StateCheck1()
            {
                board.IsFinished.Should().BeFalse();
                board.IsStalemate.Should().BeFalse();
                board.IsCheck.Should().BeFalse();
                board.IsCheckmate.Should().BeFalse();
            }

            // Check if the King's possible moves from the very start are nothing. They should be able to ignore their own pieces within possible moves

            whiteKingPossMoves.Should().BeEmpty();
            blackKingPossMoves.Should().BeEmpty();


            // Because they do not have possible moves, but it is the intiial start of the game, there shouldn't be any flags triggered
            StateCheck1();


            // Do a similar test above, but pawns that are not within the movement range of the king's directions
            // Check that the king's possible moves is still empty
            Apply(board, "b2,b3");
            StateCheck1();
            Apply(board, "h7,h5");
            StateCheck1();

            // King shouldn't be able to move and double check the position of the King
            whiteKingPossMoves.Should().BeEmpty();
            blackKingPossMoves.Should().BeEmpty();
            board.GetPieceAtPosition(Pos("e1")).PieceType.Should().Be(ChessPieceType.King, "King should be at position e1");
            board.GetPieceAtPosition(Pos("e8")).PieceType.Should().Be(ChessPieceType.King, "King should be at position e8");

            // Move a white pawn that's in front of the King that's within its range of movement
            Apply(board, "e2,e3");
            // Move a black pawn that's in front of the King that's within its range of movement
            Apply(board, "e7,e6");

            // Check white king's possible moves, there should be "something" and apply it
            var wkMove = GetMovesAtPosition(board.GetPossibleMoves(), Pos("e1"));

            wkMove.Should().NotBeNullOrEmpty();
            Apply(board, "e1,e2");

            // Check black king's possible moves, there should be "something" and apply it
            var bkMove = GetMovesAtPosition(board.GetPossibleMoves(), Pos("e8"));

            bkMove.Should().NotBeNullOrEmpty();
            Apply(board, "e8,e7");

            board.GetPieceAtPosition(Pos("e2")).PieceType.Should().Be(ChessPieceType.King, "King should be at position e2");
            board.GetPieceAtPosition(Pos("e7")).PieceType.Should().Be(ChessPieceType.King, "King should be at position e7");

            // Move pawns in front of queen up to allow the queens to move for both sides
            Apply(board, "d2,d4");
            Apply(board, "d7,d5");
            Apply(board, "d1,d2");
            Apply(board, "d8,d7");

            // Move white Queen to check White King
            Apply(board, "d2,b4");

            // Check what the Black King can do
            bkMove = GetMovesAtPosition(board.GetPossibleMoves(), Pos("e7"));
            board.IsCheck.Should().BeTrue();
            bkMove.Should().Contain(Move("e7,e8"), "The king can move back to its starting position")
            .And.Contain(Move("e7,d8"), "The king can move to a back row")
            .And.Contain(Move("e7,f6"), "The king can move forward diagonally");

            // Move black King back to start
            Apply(board, "e7,e8");
            // Move some white pawn to get to black's turn
            Apply(board, "h2,h4");
            // Move black Queen to check White King
            Apply(board, "d7,b5");

            // Check what the White King can do
            wkMove = GetMovesAtPosition(board.GetPossibleMoves(), Pos("e2"));
            board.IsCheck.Should().BeTrue();
            wkMove.Should().Contain(Move("e2,e1"), "The king can move back to its starting position")
            .And.Contain(Move("e2,d1"), "The king can move to a back row")
            .And.Contain(Move("e2,f3"), "The king can move forward diagonally");

            // Move white King forward
            Apply(board, "e2,f3");

            // Black Queen gets White Queen
            Apply(board, "b5,b4");

            Apply(board, "c2,c3");
            Apply(board, "b4,c3");
            Apply(board, "c1,d2");
            Apply(board, "c3,d2");
            Apply(board, "b1,d2");

            Apply(board, "e6,e5");
            Apply(board, "d4,e5");
            Apply(board, "d5,d4");
            Apply(board, "e3,d4");
            Apply(board, "f7,f5");

            // Apply an EnPassat Move
            Apply(board, "e5,f6");

            Apply(board, "g7,g5");
            Apply(board, "f6,f7");

            // Move King out of Pawn's check
            board.IsCheck.Should().BeTrue();
            bkMove = GetMovesAtPosition(board.GetPossibleMoves(), Pos("e8"));
            board.IsCheck.Should().BeTrue();
            bkMove.Should().Contain(Move("e8,d8"), "The king can move back to its starting position");
            Apply(board, "e8,d8");

            // Move Pawn to Promote to Queen
            Apply(board, "f7, g8, Queen");
            board.GetPieceAtPosition(Pos("g8")).PieceType.Should().Be(ChessPieceType.Queen, "Pawn should've promoted to a Queen");

            Apply(board, "c7,c5");
            Apply(board, "h4,g5");
            Apply(board, "h5,h4");
            Apply(board, "h1,h4");

            // Black bishop check's White King
            Apply(board, "c8,g4");

            // Check if Check flag is triggered and eliminate Black Bishop on White King
            board.IsCheck.Should().BeTrue();
            var protectWK = board.GetPossibleMoves();

            protectWK.Should().Contain(Move("h4,g4"), "Rook should be able to capture enemy bishop checking White King");
            Apply(board, "h4,g4");

            // Eliminate Black Rook with White Rook
            Apply(board, "h8,h7");
            Apply(board, "g4,h4");
            Apply(board, "c5,d4");
            Apply(board, "h4,h7");

            // Play a dummy move
            Apply(board, "b8,a6");
            // White Queen takes Black Bishop
            Apply(board, "g8,f8");
            board.IsCheckmate.Should().BeTrue();
        }
Example #44
0
        private static int CalculatePawnScores(ChessBoard cb)
        {
            var score = 0;

            // penalty for doubled pawns
            for (var i = 0; i < 8; i++)
            {
                if (BitOperations.PopCount((ulong)(cb.Pieces[White][Pawn] & Bitboard.Files[i])) > 1)
                {
                    score -= EvalConstants.PawnScores[EvalConstants.IxPawnDouble];
                }

                if (BitOperations.PopCount((ulong)(cb.Pieces[Black][Pawn] & Bitboard.Files[i])) > 1)
                {
                    score += EvalConstants.PawnScores[EvalConstants.IxPawnDouble];
                }
            }

            // bonus for connected pawns
            var pawns = Bitboard.GetWhitePawnAttacks(cb.Pieces[White][Pawn]) & cb.Pieces[White][Pawn];

            while (pawns != 0)
            {
                score += EvalConstants.PawnConnected[BitOperations.TrailingZeroCount(pawns) / 8];
                pawns &= pawns - 1;
            }

            pawns = Bitboard.GetBlackPawnAttacks(cb.Pieces[Black][Pawn]) & cb.Pieces[Black][Pawn];
            while (pawns != 0)
            {
                score -= EvalConstants.PawnConnected[7 - BitOperations.TrailingZeroCount(pawns) / 8];
                pawns &= pawns - 1;
            }

            // bonus for neighbour pawns
            pawns = Bitboard.GetPawnNeighbours(cb.Pieces[White][Pawn]) & cb.Pieces[White][Pawn];
            while (pawns != 0)
            {
                score += EvalConstants.PawnNeighbour[BitOperations.TrailingZeroCount(pawns) / 8];
                pawns &= pawns - 1;
            }

            pawns = Bitboard.GetPawnNeighbours(cb.Pieces[Black][Pawn]) & cb.Pieces[Black][Pawn];
            while (pawns != 0)
            {
                score -= EvalConstants.PawnNeighbour[7 - BitOperations.TrailingZeroCount(pawns) / 8];
                pawns &= pawns - 1;
            }

            // set outposts
            cb.PassedPawnsAndOutposts = 0;
            pawns = Bitboard.GetWhitePawnAttacks(cb.Pieces[White][Pawn]) & ~cb.Pieces[White][Pawn] &
                    ~cb.Pieces[Black][Pawn];
            while (pawns != 0)
            {
                if ((Bitboard.GetWhiteAdjacentMask(BitOperations.TrailingZeroCount(pawns)) & cb.Pieces[Black][Pawn]) ==
                    0)
                {
                    cb.PassedPawnsAndOutposts |= pawns & -pawns;
                }

                pawns &= pawns - 1;
            }

            pawns = Bitboard.GetBlackPawnAttacks(cb.Pieces[Black][Pawn]) & ~cb.Pieces[White][Pawn] &
                    ~cb.Pieces[Black][Pawn];
            while (pawns != 0)
            {
                if ((Bitboard.GetBlackAdjacentMask(BitOperations.TrailingZeroCount(pawns)) & cb.Pieces[White][Pawn]) ==
                    0)
                {
                    cb.PassedPawnsAndOutposts |= pawns & -pawns;
                }

                pawns &= pawns - 1;
            }

            int index;

            // white
            pawns = cb.Pieces[White][Pawn];
            while (pawns != 0)
            {
                index = BitOperations.TrailingZeroCount(pawns);

                // isolated pawns
                if ((Bitboard.FilesAdjacent[index & 7] & cb.Pieces[White][Pawn]) == 0)
                {
                    score -= EvalConstants.PawnScores[EvalConstants.IxPawnIsolated];
                }

                // backward pawns
                else if ((Bitboard.GetBlackAdjacentMask(index + 8) & cb.Pieces[White][Pawn]) == 0)
                {
                    if ((StaticMoves.PawnAttacks[White][index + 8] & cb.Pieces[Black][Pawn]) != 0)
                    {
                        if ((Bitboard.Files[index & 7] & cb.Pieces[Black][Pawn]) == 0)
                        {
                            score -= EvalConstants.PawnScores[EvalConstants.IxPawnBackward];
                        }
                    }
                }

                // pawn defending 2 pawns
                if (BitOperations.PopCount((ulong)(StaticMoves.PawnAttacks[White][index] & cb.Pieces[White][Pawn])) ==
                    2)
                {
                    score -= EvalConstants.PawnScores[EvalConstants.IxPawnInverse];
                }

                // set passed pawns
                if ((Bitboard.GetWhitePassedPawnMask(index) & cb.Pieces[Black][Pawn]) == 0)
                {
                    cb.PassedPawnsAndOutposts |= pawns & -pawns;
                }

                // candidate passed pawns (no pawns in front, more friendly pawns behind and adjacent than enemy pawns)
                else if (63 - BitOperations.LeadingZeroCount(
                             (ulong)((cb.Pieces[White][Pawn] | cb.Pieces[Black][Pawn]) &
                                     Bitboard.Files[index & 7])) == index)
                {
                    if (BitOperations.PopCount((ulong)(cb.Pieces[White][Pawn] &
                                                       Bitboard.GetBlackPassedPawnMask(index + 8))) >=
                        BitOperations.PopCount(
                            (ulong)(cb.Pieces[Black][Pawn] & Bitboard.GetWhitePassedPawnMask(index))))
                    {
                        score += EvalConstants.PassedCandidate[index / 8];
                    }
                }

                pawns &= pawns - 1;
            }

            // black
            pawns = cb.Pieces[Black][Pawn];
            while (pawns != 0)
            {
                index = BitOperations.TrailingZeroCount(pawns);

                // isolated pawns
                if ((Bitboard.FilesAdjacent[index & 7] & cb.Pieces[Black][Pawn]) == 0)
                {
                    score += EvalConstants.PawnScores[EvalConstants.IxPawnIsolated];
                }

                // backward pawns
                else if ((Bitboard.GetWhiteAdjacentMask(index - 8) & cb.Pieces[Black][Pawn]) == 0)
                {
                    if ((StaticMoves.PawnAttacks[Black][index - 8] & cb.Pieces[White][Pawn]) != 0)
                    {
                        if ((Bitboard.Files[index & 7] & cb.Pieces[White][Pawn]) == 0)
                        {
                            score += EvalConstants.PawnScores[EvalConstants.IxPawnBackward];
                        }
                    }
                }

                // pawn defending 2 pawns
                if (BitOperations.PopCount((ulong)(StaticMoves.PawnAttacks[Black][index] & cb.Pieces[Black][Pawn])) ==
                    2)
                {
                    score += EvalConstants.PawnScores[EvalConstants.IxPawnInverse];
                }

                // set passed pawns
                if ((Bitboard.GetBlackPassedPawnMask(index) & cb.Pieces[White][Pawn]) == 0)
                {
                    cb.PassedPawnsAndOutposts |= pawns & -pawns;
                }

                // candidate passers
                else if (BitOperations.TrailingZeroCount((cb.Pieces[White][Pawn] | cb.Pieces[Black][Pawn]) &
                                                         Bitboard.Files[index & 7]) == index)
                {
                    if (BitOperations.PopCount((ulong)(cb.Pieces[Black][Pawn] &
                                                       Bitboard.GetWhitePassedPawnMask(index - 8))) >=
                        BitOperations.PopCount(
                            (ulong)(cb.Pieces[White][Pawn] & Bitboard.GetBlackPassedPawnMask(index))))
                    {
                        score -= EvalConstants.PassedCandidate[7 - index / 8];
                    }
                }

                pawns &= pawns - 1;
            }

            return(score);
        }
Example #45
0
        public static int CalculateMobilityScoresAndSetAttacks(ChessBoard cb)
        {
            cb.ClearEvalAttacks();

            for (var color = White; color <= Black; color++)
            {
                var kingArea = KingArea[cb.KingIndex[1 - color]];
                var piece    = cb.Pieces[color][Pawn] & ~cb.PinnedPieces;
                while (piece != 0)
                {
                    cb.UpdatePawnAttacks(StaticMoves.PawnAttacks[color][BitOperations.TrailingZeroCount(piece)], color);
                    piece &= piece - 1;
                }

                cb.UpdatePawnAttacks(color, kingArea);

                piece = cb.Pieces[color][Pawn] & cb.PinnedPieces;
                while (piece != 0)
                {
                    cb.UpdateAttacks(StaticMoves.PawnAttacks[color][BitOperations.TrailingZeroCount(piece)]
                                     & PinnedMovement[BitOperations.TrailingZeroCount(piece)][cb.KingIndex[color]],
                                     Pawn,
                                     color, kingArea);
                    piece &= piece - 1;
                }
            }

            var  score = 0;
            long moves;

            for (var color = White; color <= Black; color++)
            {
                var tempScore = 0;

                var kingArea  = KingArea[cb.KingIndex[1 - color]];
                var safeMoves = ~cb.Pieces[color][All] & ~cb.Attacks[1 - color][Pawn];

                // knights
                var piece = cb.Pieces[color][Knight] & ~cb.PinnedPieces;
                while (piece != 0)
                {
                    moves = StaticMoves.KnightMoves[BitOperations.TrailingZeroCount(piece)];
                    cb.UpdateAttacks(moves, Knight, color, kingArea);
                    tempScore += EvalConstants.MobilityKnight[BitOperations.PopCount((ulong)(moves & safeMoves))];
                    piece     &= piece - 1;
                }

                // bishops
                piece = cb.Pieces[color][Bishop];
                while (piece != 0)
                {
                    moves = MagicUtil.GetBishopMoves(BitOperations.TrailingZeroCount(piece),
                                                     cb.AllPieces ^ cb.Pieces[color][Queen]);
                    cb.UpdateAttacks(moves, Bishop, color, kingArea);
                    tempScore += EvalConstants.MobilityBishop[BitOperations.PopCount((ulong)(moves & safeMoves))];
                    piece     &= piece - 1;
                }

                // rooks
                piece = cb.Pieces[color][Rook];
                while (piece != 0)
                {
                    moves = MagicUtil.GetRookMoves(BitOperations.TrailingZeroCount(piece),
                                                   cb.AllPieces ^ cb.Pieces[color][Rook] ^ cb.Pieces[color][Queen]);
                    cb.UpdateAttacks(moves, Rook, color, kingArea);
                    tempScore += EvalConstants.MobilityRook[BitOperations.PopCount((ulong)(moves & safeMoves))];
                    piece     &= piece - 1;
                }

                // queens
                piece = cb.Pieces[color][Queen];
                while (piece != 0)
                {
                    moves = MagicUtil.GetQueenMoves(BitOperations.TrailingZeroCount(piece), cb.AllPieces);
                    cb.UpdateAttacks(moves, Queen, color, kingArea);
                    tempScore += EvalConstants.MobilityQueen[BitOperations.PopCount((ulong)(moves & safeMoves))];
                    piece     &= piece - 1;
                }

                score += tempScore * ColorFactor[color];
            }

            // TODO king-attacks with or without enemy attacks?
            // WHITE king
            moves = StaticMoves.KingMoves[cb.KingIndex[White]] & ~StaticMoves.KingMoves[cb.KingIndex[Black]];
            cb.Attacks[White][King]  = moves;
            cb.DoubleAttacks[White] |= cb.Attacks[White][All] & moves;
            cb.Attacks[White][All]  |= moves;
            score += EvalConstants.MobilityKing[
                BitOperations.PopCount((ulong)(moves & ~cb.Pieces[White][All] & ~cb.Attacks[Black][All]))];

            // BLACK king
            moves = StaticMoves.KingMoves[cb.KingIndex[Black]] & ~StaticMoves.KingMoves[cb.KingIndex[White]];
            cb.Attacks[Black][King]  = moves;
            cb.DoubleAttacks[Black] |= cb.Attacks[Black][All] & moves;
            cb.Attacks[Black][All]  |= moves;
            score -= EvalConstants.MobilityKing[
                BitOperations.PopCount((ulong)(moves & ~cb.Pieces[Black][All] & ~cb.Attacks[White][All]))];

            return(score);
        }
Example #46
0
        public void WhenThereIsCapture_MovingPieceAndReversingTheMoveWillReaddRemovedPieceToAvailablePieces()
        {
            var whiteKingMock     = new Mock <IChessPiece>(MockBehavior.Strict);
            var blackKingMock     = new Mock <IChessPiece>(MockBehavior.Strict);
            var pawnMock          = new Mock <IChessPiece>(MockBehavior.Strict);
            var pieceMoverMock    = new Mock <IPieceMover>(MockBehavior.Strict);
            var piecesFactoryMock = new Mock <IPiecesFactory>(MockBehavior.Strict);

            var whiteKingPosition = new Position(4, 0);
            var blackKingPosition = new Position(4, 7);
            var pawnPosition      = new Position(4, 1);

            var chessMove = new ChessMove(whiteKingPosition, new Position(4, 1), true);

            whiteKingMock
            .SetupGet(k => k.Color)
            .Returns(ChessColor.White);
            whiteKingMock
            .SetupGet(k => k.PieceType)
            .Returns(ChessPieceType.King);
            whiteKingMock
            .SetupGet(k => k.Position)
            .Returns(whiteKingPosition);

            blackKingMock
            .SetupGet(k => k.Color)
            .Returns(ChessColor.Black);
            blackKingMock
            .SetupGet(k => k.PieceType)
            .Returns(ChessPieceType.King);
            blackKingMock
            .SetupGet(k => k.Position)
            .Returns(blackKingPosition);

            pawnMock
            .SetupGet(k => k.Color)
            .Returns(ChessColor.Black);
            pawnMock
            .SetupGet(k => k.PieceType)
            .Returns(ChessPieceType.Pawn);
            pawnMock
            .SetupGet(k => k.Position)
            .Returns(pawnPosition);

            pieceMoverMock
            .Setup(p => p.Move(chessMove, It.IsAny <IEnumerable <IChessPiece> >()))
            .Returns(pawnMock.Object);
            pieceMoverMock
            .Setup(p => p.ReverseLastMove(It.IsAny <IEnumerable <IChessPiece> >()))
            .Returns(chessMove.IsCapture);

            var pieces = new HashSet <IChessPiece>();

            pieces.Add(whiteKingMock.Object);
            pieces.Add(blackKingMock.Object);
            pieces.Add(pawnMock.Object);

            piecesFactoryMock
            .Setup(f => f.Create())
            .Returns(pieces);

            var chessBoard = new ChessBoard(piecesFactoryMock.Object, pieceMoverMock.Object);

            chessBoard.Move(chessMove);
            chessBoard.ReverseLastMove();

            Assert.AreEqual(3, chessBoard.Pieces.Count());
            Assert.Contains(whiteKingMock.Object, chessBoard.Pieces.ToList());
            Assert.Contains(blackKingMock.Object, chessBoard.Pieces.ToList());
            Assert.Contains(pawnMock.Object, chessBoard.Pieces.ToList());
        }
 public void Initialize(string input)
 {
     this.rawInput = input;
     this.game     = new ChessGame();
     this.board    = new ChessBoard();
 }
Example #48
0
 public void OnEachMoveEnd(ChessBoard chessBoard)
 {
     ++moveCount;
     totalMoveMilliSeconds += moveTimeRecorder.GetTotalMilliSeconds();
 }
Example #49
0
        /// <summary>
        /// Validates a move. The framework uses this to validate the opponents move.
        /// </summary>
        /// <param name="currentBoard">The board as it currently is.</param>
        /// <param name="moveToCheck">This is the move that needs to be checked to see if it's valid.</param>
        /// <param name="colorOfPlayerMoving">This is the color of the player who's making the move.</param>
        /// <returns>Returns true if the move was valid</returns>
        public bool? IsValidMove(ChessBoard currentBoard, ChessMove moveToCheck)
        {
            _moveToReturn = null;
            _isGetNextMoveCall = false;
            _isValidMove = false;

            if (this.IsHuman)
            {
                // Humans don't check the AI's moves, so just always return true
                return true;
            }

            _currentBoard = currentBoard.Clone();
            _moveToCheck = moveToCheck.Clone();
            StartAiInTimedThread(UvsChess.Gui.Preferences.CheckMoveTimeout);
            if ((_moveToReturn != null) && (_moveToReturn.Flag == ChessFlag.AIWentOverTime))
            {
                // The AI Went over time while validating the move. Signal ChessGame of this.
                return null;
            }

            return _isValidMove;
        }
Example #50
0
 private void UpdateChessBoardComponent(ChessWebApiResult result)
 {
     ChessBoard.Update(result.Board, result.AvailableMoves, result.WhoseTurn.ToLower().Contains("white"));
 }
Example #51
0
        public static int CalculateThreats(ChessBoard cb)
        {
            var score             = 0;
            var whites            = cb.Pieces[White][All];
            var whitePawns        = cb.Pieces[White][Pawn];
            var blacks            = cb.Pieces[Black][All];
            var blackPawns        = cb.Pieces[Black][Pawn];
            var whiteAttacks      = cb.Attacks[White][All];
            var whitePawnAttacks  = cb.Attacks[White][Pawn];
            var whiteMinorAttacks = cb.Attacks[White][Knight] | cb.Attacks[White][Bishop];
            var blackAttacks      = cb.Attacks[Black][All];
            var blackPawnAttacks  = cb.Attacks[Black][Pawn];
            var blackMinorAttacks = cb.Attacks[Black][Knight] | cb.Attacks[Black][Bishop];

            // double attacked pieces
            var piece = cb.DoubleAttacks[White] & blacks;

            while (piece != 0)
            {
                score += EvalConstants.DoubleAttacked[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                piece &= piece - 1;
            }

            piece = cb.DoubleAttacks[Black] & whites;
            while (piece != 0)
            {
                score -= EvalConstants.DoubleAttacked[cb.PieceIndexes[BitOperations.TrailingZeroCount(piece)]];
                piece &= piece - 1;
            }

            if (MaterialUtil.HasPawns(cb.MaterialKey))
            {
                // unused outposts
                score += BitOperations.PopCount((ulong)(cb.PassedPawnsAndOutposts & cb.EmptySpaces &
                                                        whiteMinorAttacks & whitePawnAttacks))
                         * EvalConstants.Threats[EvalConstants.IxUnusedOutpost];
                score -= BitOperations.PopCount((ulong)(cb.PassedPawnsAndOutposts & cb.EmptySpaces &
                                                        blackMinorAttacks & blackPawnAttacks))
                         * EvalConstants.Threats[EvalConstants.IxUnusedOutpost];

                // pawn push threat
                piece  = (whitePawns << 8) & cb.EmptySpaces & ~blackAttacks;
                score += BitOperations.PopCount((ulong)(Bitboard.GetWhitePawnAttacks(piece) & blacks)) *
                         EvalConstants.Threats[EvalConstants.IxPawnPushThreat];
                piece  = Util.RightTripleShift(blackPawns, 8) & cb.EmptySpaces & ~whiteAttacks;
                score -= BitOperations.PopCount((ulong)(Bitboard.GetBlackPawnAttacks(piece) & whites)) *
                         EvalConstants.Threats[EvalConstants.IxPawnPushThreat];

                // piece attacked by pawn
                score += BitOperations.PopCount((ulong)(whitePawnAttacks & blacks & ~blackPawns)) *
                         EvalConstants.Threats[EvalConstants.IxPawnAttacks];
                score -= BitOperations.PopCount((ulong)(blackPawnAttacks & whites & ~whitePawns)) *
                         EvalConstants.Threats[EvalConstants.IxPawnAttacks];

                // multiple pawn attacks possible
                if (BitOperations.PopCount((ulong)(whitePawnAttacks & blacks)) > 1)
                {
                    score += EvalConstants.Threats[EvalConstants.IxMultiplePawnAttacks];
                }

                if (BitOperations.PopCount((ulong)(blackPawnAttacks & whites)) > 1)
                {
                    score -= EvalConstants.Threats[EvalConstants.IxMultiplePawnAttacks];
                }

                // pawn attacked
                score += BitOperations.PopCount((ulong)(whiteAttacks & blackPawns)) *
                         EvalConstants.Threats[EvalConstants.IxPawnAttacked];
                score -= BitOperations.PopCount((ulong)(blackAttacks & whitePawns)) *
                         EvalConstants.Threats[EvalConstants.IxPawnAttacked];
            }

            // minors attacked and not defended by a pawn
            score += BitOperations.PopCount((ulong)(whiteAttacks &
                                                    (cb.Pieces[Black][Knight] |
                                                     (cb.Pieces[Black][Bishop] & ~blackAttacks))))
                     * EvalConstants.Threats[EvalConstants.IxMajorAttacked];
            score -= BitOperations.PopCount((ulong)(blackAttacks &
                                                    (cb.Pieces[White][Knight] |
                                                     (cb.Pieces[White][Bishop] & ~whiteAttacks))))
                     * EvalConstants.Threats[EvalConstants.IxMajorAttacked];

            if (cb.Pieces[Black][Queen] != 0)
            {
                // queen attacked by rook
                score += BitOperations.PopCount((ulong)(cb.Attacks[White][Rook] & cb.Pieces[Black][Queen])) *
                         EvalConstants.Threats[EvalConstants.IxQueenAttacked];
                // queen attacked by minors
                score += BitOperations.PopCount((ulong)(whiteMinorAttacks & cb.Pieces[Black][Queen])) *
                         EvalConstants.Threats[EvalConstants.IxQueenAttackedMinor];
            }

            if (cb.Pieces[White][Queen] != 0)
            {
                // queen attacked by rook
                score -= BitOperations.PopCount((ulong)(cb.Attacks[Black][Rook] & cb.Pieces[White][Queen])) *
                         EvalConstants.Threats[EvalConstants.IxQueenAttacked];
                // queen attacked by minors
                score -= BitOperations.PopCount((ulong)(blackMinorAttacks & cb.Pieces[White][Queen])) *
                         EvalConstants.Threats[EvalConstants.IxQueenAttackedMinor];
            }

            // rook attacked by minors
            score += BitOperations.PopCount((ulong)(whiteMinorAttacks & cb.Pieces[Black][Rook])) *
                     EvalConstants.Threats[EvalConstants.IxRookAttacked];
            score -= BitOperations.PopCount((ulong)(blackMinorAttacks & cb.Pieces[White][Rook])) *
                     EvalConstants.Threats[EvalConstants.IxRookAttacked];

            return(score);
        }
        /// <summary>
        /// Find the best move for a player using alpha-beta for a given depth
        /// </summary>
        /// <param name="board">            Chess board</param>
        /// <param name="searchMode">       Search mode</param>
        /// <param name="ePlayer">          Color doing the move</param>
        /// <param name="moveList">         List of move to try</param>
        /// <param name="posInfoWhite">     Information about pieces attacks for the white</param>
        /// <param name="posInfoBlack">     Information about pieces attacks for the black</param>
        /// <param name="iTotalMoveCount">  Total list of moves</param>
        /// <param name="iDepth">           Maximum depth</param>
        /// <param name="iAlpha">           Alpha bound</param>
        /// <param name="iBeta">            Beta bound</param>
        /// <param name="transTable">       Transposition table or null if not using one</param>
        /// <param name="dtTimeOut">        Time limit (DateTime.MaxValue for no time limit)</param>
        /// <param name="iPermCount">       Total permutation evaluated</param>
        /// <param name="iBestMoveIndex">   Index of the best move</param>
        /// <param name="bTimeOut">         Return true if time out</param>
        /// <param name="arrPoints">        Returns point of each move in move list</param>
        /// <returns>
        /// Points
        /// </returns>
        private int FindBestMoveUsingAlphaBetaAtDepth(ChessBoard board,
                                                      SearchMode searchMode,
                                                      ChessBoard.PlayerE ePlayer,
                                                      List <Move> moveList,
                                                      ChessBoard.PosInfoS posInfoWhite,
                                                      ChessBoard.PosInfoS posInfoBlack,
                                                      int iTotalMoveCount,
                                                      int iDepth,
                                                      int iAlpha,
                                                      int iBeta,
                                                      TransTable transTable,
                                                      DateTime dtTimeOut,
                                                      out int iPermCount,
                                                      out int iBestMoveIndex,
                                                      out bool bTimeOut,
                                                      out int[]             arrPoints)
        {
            int           iRetVal = -10000000;
            int           iWhiteMoveCount;
            int           iBlackMoveCount;
            int           iMoveCount;
            int           iIndex;
            int           iPts;
            Move          move;
            AlphaBetaInfo abInfo;

            ChessBoard.RepeatResultE eResult;

            bTimeOut              = false;
            abInfo                = new AlphaBetaInfo();
            abInfo.m_arrMove      = new Move[iDepth];
            abInfo.m_iPermCount   = 0;
            abInfo.m_dtTimeOut    = dtTimeOut;
            abInfo.m_transTable   = transTable;
            abInfo.m_iMaxDepth    = iDepth;
            abInfo.m_searchMode   = searchMode;
            abInfo.m_posInfoWhite = posInfoWhite;
            abInfo.m_posInfoBlack = posInfoBlack;
            iBestMoveIndex        = -1;
            arrPoints             = new int[moveList.Count];
            if (ePlayer == ChessBoard.PlayerE.White)
            {
                iWhiteMoveCount = iTotalMoveCount;
                iBlackMoveCount = 0;
            }
            else
            {
                iWhiteMoveCount = 0;
                iBlackMoveCount = iTotalMoveCount;
            }
            iMoveCount = moveList.Count;
            iIndex     = 0;
            iRetVal    = iAlpha;
            while (iIndex < iMoveCount && !bTimeOut)
            {
                move    = moveList[iIndex];
                eResult = board.DoMoveNoLog(move);
                abInfo.m_arrMove[iDepth - 1] = move;
                if (eResult == ChessBoard.RepeatResultE.NoRepeat)
                {
                    iPts = -AlphaBeta(board,
                                      (ePlayer == ChessBoard.PlayerE.Black) ? ChessBoard.PlayerE.White : ChessBoard.PlayerE.Black,
                                      iDepth - 1,
                                      -iBeta,
                                      -iRetVal,
                                      iWhiteMoveCount,
                                      iBlackMoveCount,
                                      abInfo);
                }
                else
                {
                    iPts = 0;
                }
                arrPoints[iIndex] = iPts;
                board.UndoMoveNoLog(move);
                if (iPts == Int32.MinValue)
                {
                    iRetVal  = iPts;
                    bTimeOut = true;
                }
                else
                {
                    if (iPts > iRetVal)
                    {
                        TraceSearch(iDepth, ePlayer, move, iPts);
                        iRetVal        = iPts;
                        iBestMoveIndex = iIndex;
                    }
                }
                iIndex++;
            }
            iPermCount = abInfo.m_iPermCount;
            return(iRetVal);
        }
Example #53
0
        /// <summary>
        /// Sets the chess state as described in the FEN board. 
        /// See: http://en.wikipedia.org/wiki/Forsyth-Edwards_Notation
        /// </summary>
        /// <param name="fenBoard"></param>
        public void FromFenBoard(string fenBoard)
        {
            string[] lines = fenBoard.Split(' ');

            CurrentBoard = new ChessBoard(fenBoard);

            if (lines[1] == "w")
            {
                CurrentPlayerColor = ChessColor.White;
            }
            else if (lines[1] == "b")
            {
                CurrentPlayerColor = ChessColor.Black;
            }
            else
            {
                throw new Exception("Missing active color in FEN board");
            }

            //casting is lines[2]
            CastlingFromFen(lines[2]);

            //en passant is lines[3]
            EnPassant = EnPassantFromFen(lines[3].ToLower());

            HalfMoves = Convert.ToInt32(lines[4]);
            FullMoves = Convert.ToInt32(lines[5]);
        }
Example #54
0
 /// <summary>
 /// Constructor for a new <see cref="Bishop"/>.
 /// </summary>
 /// <inheritdoc/>
 public Bishop(ChessBoard board, BoardSide side, Team team)
     : base(board, side, team)
 {
 }
 public void BoardCreation()
 {
     var board = new ChessBoard();
     var piece = board[0];
     Console.WriteLine(piece.ToString());
 }
Example #56
0
 public void SaveAsBitmap(string fileName)
 {
     ChessBoard.SaveAsBitmap(fileName);
 }
Example #57
0
 public override bool Move(int srcX, int srcY, int destX, int destY, ChessBoard chess)
 {
     throw new System.NotImplementedException();
 }
Example #58
0
 private void get2DProjection_OpenCv(ChessBoard b, out PointF[] projected)
 {
     double[,] jabobian;
     projected = CVI.ProjectPoints(b.boardWorldCoordinated_Cv, Camera.Rvecs, Camera.Tvecs, Camera.Intrinsics.cvmat, Camera.Cv_DistCoeffs4);
 }
Example #59
0
 /// <summary>
 /// The constructor.
 /// </summary>
 /// <param name="board">The board where the Chess piece is located.</param>
 /// <param name="color">The color of the Chess piece.</param>
 /// <param name="square">The square where the Chess piece is located.</param>
 public Bishop(ChessBoard board, ChessColor color, Square square = null)
     : base(board, color, square)
 {
     this.Movement = new RowMovement(this, MovementDirection.Diagonal);
 }
Example #60
0
        public void initBoard()
        {
            this.Width = 2 * ChessBoard.BoardPaddingLeft +
                         ChessBoard.ChessSize * ChessBoard.BoardColumns;

            this.Height = 2 * ChessBoard.BoardPaddingTop +
                          ChessBoard.ChessSize * ChessBoard.BoardRows;

            _ChessBoard = Presenter.CreateNewGame();

            Label turnLabel = new Label();

            turnLabel.Name      = "lblTurn";
            turnLabel.Text      = "Đến lượt X đi";
            turnLabel.Font      = new Font("Arial", 16, FontStyle.Bold);
            turnLabel.ForeColor = Color.Blue;
            turnLabel.TextAlign = ContentAlignment.MiddleCenter;
            turnLabel.Width     = this.Width;
            turnLabel.Height    = 30;
            turnLabel.Location  = new Point(0,
                                            ChessBoard.BoardPaddingTop - ChessBoard.ChessSize * 3);
            Controls.Add(turnLabel);

            Label timeLabel = new Label();

            timeLabel.Name      = "lblTime";
            timeLabel.Text      = ChessBoard.MoveTime.ToString();
            timeLabel.Font      = new Font("Arial", 16, FontStyle.Bold);
            timeLabel.ForeColor = Color.Green;
            timeLabel.TextAlign = ContentAlignment.MiddleCenter;
            timeLabel.Width     = 40;
            timeLabel.Height    = 30;
            timeLabel.Location  = new Point(ChessBoard.BoardPaddingLeft,
                                            ChessBoard.BoardPaddingTop - ChessBoard.ChessSize * 2);
            Controls.Add(timeLabel);

            ProgressBar progressBar = new ProgressBar();

            progressBar.Name     = "prgTime";
            progressBar.Location = new Point(ChessBoard.BoardPaddingLeft + timeLabel.Width,
                                             ChessBoard.BoardPaddingTop - ChessBoard.ChessSize * 2);
            progressBar.Width = ChessBoard.BoardColumns * ChessBoard.ChessSize - timeLabel.Width;
            progressBar.Value = 100;
            Controls.Add(progressBar);

            for (int i = 0; i < ChessBoard.BoardRows; i++)
            {
                Label label = new Label();
                label.Text      = ((char)('A' + i)).ToString();
                label.Font      = new Font("Arial", 12, FontStyle.Bold);
                label.TextAlign = ContentAlignment.MiddleCenter;
                label.Height    = ChessBoard.ChessSize;
                label.Width     = ChessBoard.ChessSize;
                label.Location  = new Point(ChessBoard.BoardPaddingLeft + ChessBoard.ChessSize * i,
                                            ChessBoard.BoardPaddingTop - ChessBoard.ChessSize);
                Controls.Add(label);
            }

            for (int i = 0; i < ChessBoard.BoardColumns; i++)
            {
                Label label = new Label();
                label.Text      = (i + 1).ToString();
                label.Font      = new Font("Arial", 12, FontStyle.Bold);
                label.TextAlign = ContentAlignment.MiddleCenter;
                label.Height    = ChessBoard.ChessSize;
                label.Width     = ChessBoard.ChessSize;
                label.Location  = new Point(ChessBoard.BoardPaddingLeft - ChessBoard.ChessSize,
                                            ChessBoard.BoardPaddingTop + ChessBoard.ChessSize * i);
                Controls.Add(label);
            }

            for (int i = 1; i <= ChessBoard.BoardRows; i++)
            {
                for (int j = 1; j <= ChessBoard.BoardColumns; j++)
                {
                    Button button = new Button();
                    button.Name     = "Chess_" + i.ToString() + "_" + j.ToString();
                    button.Width    = ChessBoard.ChessSize;
                    button.Height   = ChessBoard.ChessSize;
                    button.Location = new Point(ChessBoard.BoardPaddingLeft + ChessBoard.ChessSize * (j - 1),
                                                ChessBoard.BoardPaddingTop + ChessBoard.ChessSize * (i - 1));
                    button.Click += btnChess_Click;
                    button.BackgroundImageLayout = ImageLayout.Stretch;
                    Controls.Add(button);

                    _ChessBoard.Chesses[i, j] = new Chess(j, i, 0);
                }
            }

            _ChessBoard.StartTime = DateTime.Now;
            timerTurn.Start();
            timerGameDuration.Start();
        }