protected override void OnInit()
        {
            RectID          = "rect" + CompID;
            PlayerTimerID   = "PlayerTimer" + CompID;
            OppositeTimerID = "OppositeTimer" + CompID;


            ChessEngine1 = new ChessEngine(PlayerOrOpposite);


            if (PlayerOrOpposite)
            {
                BoardBoorderColor = "Red";
            }
            else
            {
                BoardBoorderColor = "#FFA500";
            }


            if (ChessEngine1.compSettings.Curr_comp == null)
            {
                ChessEngine1.compSettings.Curr_comp = this;
            }


            ChessEngine1.MyCell.width  = ChessEngine1.compSettings.CompHeight / 9;
            ChessEngine1.MyCell.height = ChessEngine1.compSettings.CompHeight / 9;


            ChessEngine1.MyCell_Moklulebi.width  = 350 / 10.0;
            ChessEngine1.MyCell_Moklulebi.height = 150 / 4.4;
        }
예제 #2
0
 public static void LoadFEN(ChessEngine engine,IBoard board, string fen)
 {
     var fields = fen.Split(' ');
     GetPositions(board, fields[0]);
     engine.ToMove = fields[1] == "w" ? Color.White : Color.Black;
     DetermineCastling(board, fields[2]);
 }
예제 #3
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);
        }
예제 #4
0
파일: Program.cs 프로젝트: stevehjohn/Chess
        public static void Main()
        {
            for (var i = 1; i < Depth; i++)
            {
                Console.WriteLine($"\nDepth: {i}\n");

                var board  = BoardBuilder.Build();
                var engine = new ChessEngine(board, i);

                var stopwatch = Stopwatch.StartNew();

                engine.GetMove(Side.White);

                stopwatch.Stop();

                Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds / 1000.0}");

                for (var k = 0; k < i; k++)
                {
                    var max   = engine.Depths[k].Max(m => m.TotalValue);
                    var count = engine.Depths[k].Count(m => m.TotalValue == max);

                    Console.WriteLine($"Depth {k}, Max Score {max}, Count of Max Score Nodes {count}, Total Nodes: {engine.Depths[k].Count}");
                }
            }

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }
        }
예제 #5
0
        public void ChessEngine_Publish_List_Of_Both_Players_Pieces()
        {
            // Arrange:
            Mock<IPlayer> whitePlayerMock = new Mock<IPlayer>();
            Mock<IPlayer> blackPlayerMock = new Mock<IPlayer>();
            chess = new ChessEngine( new Board(), whitePlayerMock.Object, blackPlayerMock.Object, new ConfigChess() );

            ArrayList whitePieces = new ArrayList();
            whitePieces.Add( "White_Piece_A_Info" );
            whitePieces.Add( "White_Piece_B_Info" );
            whitePlayerMock.Setup( x => x.ListPieces() ).Returns( whitePieces );

            ArrayList blackPieces = new ArrayList();
            blackPieces.Add( "Black_Piece_A_Info" );
            blackPieces.Add( "Black_Piece_B_Info" );
            blackPlayerMock.Setup( x => x.ListPieces() ).Returns( blackPieces );

            // Act:
            ArrayList setPieces = chess.GetChessPieces();

            // Assert:
            ArrayList expectedList = new ArrayList( whitePieces );
            expectedList.AddRange( blackPieces );
            Assert.AreEqual( setPieces, expectedList, "Both player pieces are returned" );
        }
예제 #6
0
        /// <summary>
        /// Undoes the last played move.
        /// </summary>
        /// <returns>An instance of the last move or null if there is no moves in the MoveHistory.</returns>
        public ChessMove UndoMove()
        {
            var undoneMove = ChessEngine.UndoMove();

            Invalidate();

            return(undoneMove);
        }
예제 #7
0
        /// <summary>
        /// Initilize chess board and chess engine by default
        /// </summary>
        /// <param name="colorFlag">color flag</param>
        private void SetChessboardByComputerMode(bool colorFlag)
        {
            _firstPlayerColor  = colorFlag ? ColorEnum.White : ColorEnum.Black;
            _secondPlayerColor = colorFlag ? ColorEnum.Black : ColorEnum.White;

            _chessEngine = new ChessEngine(_secondPlayerColor);
            ChessBoard   = new ChessBoard();
        }
예제 #8
0
        public void ChessEngine_Publish_List_Of_Board_Tiles()
        {
            Mock<IBoard> boardMock = new Mock<IBoard>();
            chess = new ChessEngine( boardMock.Object, new Player( Player.PlayerColor.White ), new Player( Player.PlayerColor.Black ), new ConfigChess() );
            chess.GetBoardTiles();

            boardMock.Verify( x => x.ListBoardTiles() );
        }
예제 #9
0
        public void TestRookMovement()
        {
            var engine = new ChessEngine(
                new JsonSource(),
                new JsonParser(),
                new MovementValidator(new XYConverter()));

            Assert.False(engine.ValidateMove(2));
        }
예제 #10
0
    // Start is called before the first frame update
    void Start()
    {
        _BoardHighlights = gameObject.GetComponent <BoardHighlights>();

        _ChessEngine = gameObject.GetComponent <ChessEngine>();
        SpawnAllPieces();
        SpawnAllSnapzones();
        InitTurn();
    }
예제 #11
0
 public Main()
 {
     InitializeComponent();
     _control = new GuiControl(this, BoardControl);
     _game = new ChessEngine(new SimpleEvaluator());
     _game.LoadFEN("rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1");
     //_game.LoadFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
     BoardControl.SetGame(_game, _control);
 }
예제 #12
0
 public void Initialized_Chess_Has_Linked_Pieces_To_Each_Player()
 {
     Mock<IPlayer> whitePlayerMock = new Mock<IPlayer>();
     Mock<IPlayer> blackPlayerMock = new Mock<IPlayer>();
     chess = new ChessEngine( new Board(), whitePlayerMock.Object, blackPlayerMock.Object, new ConfigChess() );
     chess.Initialize();
     whitePlayerMock.VerifySet( x => x.Pieces = It.IsAny<Dictionary<Piece, string>>() );
     blackPlayerMock.VerifySet( x => x.Pieces = It.IsAny<Dictionary<Piece, string>>() );
 }
예제 #13
0
        public void CheckEngineByFen()
        {
            var set   = new SettingsStore();
            var sf    = new ChessEngine(set.EnginePath);
            var board = new ChessBoard();
            var turn  = sf.Query(board.GetFen());

            Assert.Equal("e2e4", turn + "");
            sf.Dispose();
        }
예제 #14
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Validating moves...");
            var engine = new ChessEngine(
                new JsonSource(),
                new JsonParser(),
                new MovementValidator(new XYConverter()));

            engine.ValidateMoves();
        }
예제 #15
0
        public void CalculateOpeningMove()
        {
            ChessEngine chessEngine = new ChessEngine();

            chessEngine.New();

            Move move = chessEngine.CalculateMove();

            Assert.IsNotNull(move);
        }
예제 #16
0
        public void MoveChessPieceThrows_GivenTargetPositionOffTheBoard()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(-1, 0);

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "The target position (Row: -1, Col: 0) is not on the board"),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #17
0
        public void MoveChessPieceThrows_GivenNoPieceInStartPosition()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(1, 0);

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "There is no piece in the starting position (Row: 0, Col: 0)"),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #18
0
        public void Initialized_Chess_Has_A_Board_Initialized()
        {
            ConfigChess config = new ConfigChess();
            var boardMock = new Mock<IBoard>();
            boardMock.Setup( x => x.Initialize( config.ListHorizontalBoardCoordinates(), config.ListVerticalBoardCoordinates() ) );

            chess = new ChessEngine( boardMock.Object, new Player( Player.PlayerColor.White ), new Player( Player.PlayerColor.Black ), new ConfigChess() );
            chess.Initialize();

            boardMock.Verify();
        }
예제 #19
0
        public void MoveChessPieceThrows_GivenMatchingStartAndTargetPositions()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(0, 0);

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "The starting position (Row: 0, Col: 0) was the same as the target position (Row: 0, Col: 0)"),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #20
0
        public void MoveChessPieceThrows_GivenInvalidMovement()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(7, 7);

            _emptyChessBoard.SetPosition(startingPosition, new Pawn(Player.Black));

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 7, Cols: 7) is not valid for this piece (Black Pawn)."),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #21
0
        public void CalculateOneMoveMate1()
        {
            ChessEngine chessEngine = new ChessEngine
            {
                ["G6"] = new King(Color.White, MoveType.Normal),
                ["H8"] = new King(Color.Black, MoveType.Normal),
                ["A1"] = new Rook(Color.White)
            };

            Move move = chessEngine.CalculateMove();

            Assert.IsTrue(move.End.AreEqual(new Position("A8")));
        }
예제 #22
0
        public void MoveChessPieceThrows_GivenCastlingMove_WhenRookPositionIsEmpty()
        {
            var engine = new ChessEngine();
            var kingStartingPosition = new Position(0, 4);
            var kingTargetPosition   = new Position(0, 2);

            _emptyChessBoard.SetPosition(kingStartingPosition, new King(Player.Black));

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 0, Cols: -2) is not valid for this piece (Black King)."),
                () => engine.MoveChessPiece(_chessGame, kingStartingPosition, kingTargetPosition));
        }
예제 #23
0
 private void DrawVisualHints(Graphics g)
 {
     if (ShowVisualHints && DragDropOperation.Origin != null)
     {
         List <ChessMove> legalMoves = ChessEngine.GetLegalMoves(DragDropOperation.Origin);
         foreach (ChessMove chessMove in legalMoves)
         {
             g.FillEllipse(new SolidBrush(Color.FromArgb(150, 92, 214, 92)),
                           BoardDirection == BoardDirection.BlackOnTop ?
                           GetHintRectangle((int)chessMove.To.File, 7 - (int)chessMove.To.Rank) :
                           GetHintRectangle(7 - (int)chessMove.To.File, (int)chessMove.To.Rank));
         }
     }
 }
예제 #24
0
        public void CheckEngineByMoves()
        {
            var set   = new SettingsStore();
            var sf    = new ChessEngine(set.EnginePath);
            var board = new ChessBoard();
            var turn  = sf.Query(board.GetMoves());

            Assert.True("e2e4" == turn + "" || "g1f3" == turn + "");
            turn.ApplySide(new Side(true));
            Assert.True(board.TurnIn(turn));
            turn = sf.Query(board.GetMoves());
            Assert.True("e7e5" == turn + "" || "c7c5" == turn + "");
            sf.Dispose();
        }
예제 #25
0
        public void CheckBoardRatingBlackMate()
        {
            ChessEngine chessEngine = new ChessEngine
            {
                ["G6"] = new King(Color.White, MoveType.Normal),
                ["A8"] = new Rook(Color.White),
                ["G8"] = new King(Color.Black, MoveType.Normal)
            };


            BoardRating boardRating = chessEngine.GetRating(Color.Black);

            Assert.AreEqual(boardRating.Situation, Situation.WhiteVictory);
        }
예제 #26
0
        public void MoveChessPieceThrows_GivenPawnSpecialMove_WhenPawnHasAlreadyMoved()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(2, 0);

            _emptyChessBoard.SetPosition(startingPosition, new Pawn(Player.Black));
            _emptyChessBoard.GetPiece(startingPosition).MarkAsMoved();

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 2, Cols: 0) is not valid for this piece (Black Pawn)."),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #27
0
        /// <summary>
        /// Moves a piece from one square to another one.
        /// </summary>
        /// <returns>Returns the captured piece if any.</returns>
        /// <param name="move">An instance of a validated move. Use <see cref="CheckMoveValidity(ChessSquare, ChessSquare)"/> to get an instance of a validated <see cref="ChessMove"/>.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="move"/> is null.</exception>
        /// <exception cref="ArgumentException">Thrown i <paramref name="move"/> is invalid.</exception>
        public void MovePiece(ChessMove move)
        {
            if (move == null)
            {
                throw new ArgumentNullException();
            }
            if (!move.IsValid)
            {
                throw new ArgumentException();
            }

            ChessEngine.Move(move);
            Invalidate();
        }
예제 #28
0
        public void MoveChessPieceThrows_GivenTargetPositionOccupiedByTheSameTeam()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(1, 0);

            _emptyChessBoard.SetPosition(startingPosition, new Rook(Player.Black));
            _emptyChessBoard.SetPosition(targetPosition, new Pawn(Player.Black));

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 1, Cols: 0) is blocked by another piece."),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #29
0
        public void MoveChessPieceThrows_GivenSpecialPawnForwardMove_WhenTargetPositionIsOccupiedByOpponent()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(2, 0);

            _emptyChessBoard.SetPosition(startingPosition, new Pawn(Player.Black));
            _emptyChessBoard.SetPosition(targetPosition, new Bishop(Player.White));

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 2, Cols: 0) is blocked by another piece."),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
    static void Main(string[] args)
    {
        ChessBoard cb = new ChessBoard();

        cb.SetupBoard(new KeyValuePair <Int32, PieceType>[]
        {
            // Setup Black pieces
            new KeyValuePair <Int32, PieceType>(3, PieceType.BlackRook),
            new KeyValuePair <Int32, PieceType>(5, PieceType.BlackKing),
            new KeyValuePair <Int32, PieceType>(11, PieceType.BlackKnight),
            new KeyValuePair <Int32, PieceType>(12, PieceType.BlackKnight),
            new KeyValuePair <Int32, PieceType>(13, PieceType.BlackPawn),
            new KeyValuePair <Int32, PieceType>(14, PieceType.BlackPawn),
            new KeyValuePair <Int32, PieceType>(16, PieceType.BlackQueen),
            new KeyValuePair <Int32, PieceType>(17, PieceType.BlackPawn),
            new KeyValuePair <Int32, PieceType>(18, PieceType.BlackPawn),
            new KeyValuePair <Int32, PieceType>(19, PieceType.BlackRook),
            new KeyValuePair <Int32, PieceType>(23, PieceType.BlackPawn),
            new KeyValuePair <Int32, PieceType>(24, PieceType.BlackPawn),
            // Setup White pieces
            new KeyValuePair <Int32, PieceType>(31, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(32, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(35, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(36, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(37, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(38, PieceType.WhitePawn),
            new KeyValuePair <Int32, PieceType>(40, PieceType.WhiteKnight),
            new KeyValuePair <Int32, PieceType>(41, PieceType.WhiteBishop),
            new KeyValuePair <Int32, PieceType>(42, PieceType.WhiteRook),
            new KeyValuePair <Int32, PieceType>(53, PieceType.WhiteKing)
        }
                      );
        cb.DisplayBoard();
        int               square      = 41;
        ChessEngine       eng         = new ChessEngine();
        List <FutureMove> futureMoves = eng.Calculate(cb, square);
        int               move1       = futureMoves.Where(m => m.Depth == 1).Count();
        int               move2       = futureMoves.Where(m => m.Depth == 2).Count();
        int               move3       = futureMoves.Where(m => m.Depth == 3).Count();

        Console.WriteLine();
        Console.WriteLine(String.Format("Number of potential squares reached in 1 move  {0,3} from square {1,2}", move1, square));
        Console.WriteLine(String.Format("Number of potential squares reached in 2 moves {0,3} from square {1,2}", move2, square));
        Console.WriteLine(String.Format("Number of potential squares reached in 3 moves {0,3} from square {1,2}", move3, square));
        //dumpMoves( node );
        Console.WriteLine();
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
예제 #31
0
        public void CalculatePawnBeat()
        {
            ChessEngine chessEngine = new ChessEngine
            {
                ["H1"] = new King(Color.White, MoveType.Normal),
                ["E4"] = new Pawn(Color.White),
                ["G8"] = new King(Color.Black, MoveType.Normal),
                ["D5"] = new Pawn(Color.Black)
            };


            Move move = chessEngine.CalculateMove();

            Assert.IsTrue(move.End.AreEqual(new Position("D5")));
        }
예제 #32
0
        public void CheckStartBoardRating()
        {
            ChessEngine chessEngine = new ChessEngine();

            chessEngine.New();

            foreach (Color color in ChessEngineConstants.BothColors)
            {
                BoardRating boardRating = chessEngine.GetRating(color);

                Assert.IsTrue(boardRating.Situation == Situation.Normal);
                Assert.IsTrue(boardRating.Evaluation == Evaluation.Normal);
                Assert.AreEqual(boardRating.Weight, 0);
            }
        }
예제 #33
0
        public void MoveChessPieceThrows_GivenMoveBlockedByOpponent()
        {
            var engine           = new ChessEngine();
            var startingPosition = new Position(0, 0);
            var targetPosition   = new Position(2, 0);
            var blockingPosition = new Position(1, 0);

            _emptyChessBoard.SetPosition(startingPosition, new Rook(Player.Black));
            _emptyChessBoard.SetPosition(targetPosition, new Queen(Player.White));
            _emptyChessBoard.SetPosition(blockingPosition, new Knight(Player.White));

            Assert.Throws(
                Is.TypeOf <InvalidOperationException>().And.Message.EqualTo(
                    "This move (Rows: 2, Cols: 0) is blocked by another piece."),
                () => engine.MoveChessPiece(_chessGame, startingPosition, targetPosition));
        }
예제 #34
0
        public void CalculateTwoMoveMate()
        {
            ChessEngine chessEngine = new ChessEngine
            {
                ["G6"] = new King(Color.White, MoveType.Normal),
                ["C4"] = new Pawn(Color.White),
                ["H8"] = new King(Color.Black, MoveType.Normal),
                ["B5"] = new Pawn(Color.Black),
                ["G5"] = new Rook(Color.White)
            };

            Move move = chessEngine.CalculateMove();

            Assert.IsTrue(move.Rating.Evaluation == Evaluation.BlackCheckMate);
            Assert.IsTrue(move.Rating.Situation == Situation.WhiteVictory);
            Assert.IsTrue(move.Piece is Rook);
        }
예제 #35
0
        public void CheckEnpassant()
        {
            ChessEngine chessEngine = new ChessEngine
            {
                ["G6"] = new King(Color.White, MoveType.Normal),
                ["C2"] = new Pawn(Color.White),
                ["H8"] = new King(Color.Black, MoveType.Normal),
                ["B4"] = new Pawn(Color.Black)
            };

            chessEngine.ExecuteMove(new Move("C2", "C4", chessEngine["C2"], MoveType.PawnDoubleStep));
            Move move = chessEngine.CalculateMove();

            chessEngine.ExecuteMove(move);

            Assert.IsTrue(move.Type == MoveType.EnpassantBlackLeft);
        }
예제 #36
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);
        }
예제 #37
0
 /// <summary>
 /// Sets the ChessEngine to be used for this game
 /// </summary>
 public void SetGame(ChessEngine game, GuiControl control)
 {
     _game = game;
     _control = control;
 }
예제 #38
0
 public void Initialized_Chess_Has_Placed_Pieces_On_The_Board_For_2_Players()
 {
     Mock<IBoard> boardMock = new Mock<IBoard>();
     chess = new ChessEngine( boardMock.Object, new Player( Player.PlayerColor.White ), new Player( Player.PlayerColor.Black ), new ConfigChess() );
     chess.Initialize();
     boardMock.Verify( x => x.PlaceCollectionOfPieces( It.IsAny<Dictionary<Piece, string>>() ), Times.Exactly( 2 ) );
 }