Пример #1
0
        void DrawBoard()
        {
            bool isWhite = false;

            for (int x = 0; x < 8; x++)
            {
                isWhite = !isWhite;
                for (int y = 0; y < 8; y++)
                {
                    Label label = new Label();
                    label.Width     = gameLayoutPanel.Width / 8;
                    label.Height    = gameLayoutPanel.Height / 8;
                    label.BackColor = isWhite ? Color.SandyBrown : Color.Sienna;
                    label.Margin    = Padding.Empty;
                    label.Font      = new Font("Arial", 13, FontStyle.Bold);
                    label.TextAlign = ContentAlignment.MiddleCenter;
                    if (chess.ChessBoard.Board[x, y] != null)
                    {
                        //label.Text = chess.ChessBoard.Board[x, y].name;
                        label.ForeColor = chess.ChessBoard.Board[x, y].color == ChessColor.White ? Color.White : Color.Black;
                    }
                    if (chess.ChessBoard.Board[x, y] != null && chess.ChessBoard.Board[x, y].imageDirect != "")
                    {
                        label.Image = Image.FromFile(chess.ChessBoard.Board[x, y].imageDirect);
                    }
                    gameLayoutPanel.Controls.Add(label);
                    ChessColor  chessColor = isWhite ? ChessColor.White : ChessColor.Black;
                    ChessSquare square     = new ChessSquare(label, new Grid(x, y), OnSquareClick, chessColor);
                    squares[x, y] = square;
                    isWhite       = !isWhite;
                }
            }
        }
Пример #2
0
    public override string MoveTo(ChessSquare square, BasePiece[][] pieces, bool isBuffed)
    {
        var letter = square.Column.ToString().ToLower();

        movedBefore = true;
        return($"{letter}{base.MoveTo(square, pieces, isBuffed)}");
    }
Пример #3
0
        void OnSquareClick(Grid position)
        {
            Console.WriteLine("Clicked");
            ClearHighlighted();
            ChessSquare clickedSquare = squares[position.row, position.column];
            Piece       clickedPiece  = chess.ChessBoard.Board[position.row, position.column];

            if (clickedSquare.label.Image != null && clickedPiece != null && clickedPiece.color == chess.Turn)
            {
                clickedSquare.Focus();
                higlightedSquares.Add(clickedSquare);
            }
            List <PieceMove> moves = chess.GetMoves(position);

            if (moves.Count == 0)
            {
                return;
            }
            foreach (PieceMove move in moves)
            {
                ChessSquare square = squares[move.newPos.row, move.newPos.column];
                square.HighlightLabel(chess.MakeMove, move);
                higlightedSquares.Add(square);
            }
        }
Пример #4
0
        private void pnlBoard_MouseDown(object sender, MouseEventArgs e)
        {
            int squareWidth  = pnlBoard.Width / INT_MAX_COL_FILE;
            int squareHeight = pnlBoard.Height / INT_MAX_ROW_RANK;

            if (e.Button == MouseButtons.Left)
            {
                _squareBeginDragCol = (e.X / squareWidth);
                _squareBeginDragRow = (e.Y / squareHeight);

                ChessSquare currentSquare = _board.Squares[_squareBeginDragCol.Value, _squareBeginDragRow.Value];
                if (currentSquare != null)
                {
                    if (currentSquare.Piece != null)
                    {
                        _currentPieceANMoves = currentSquare.Piece.GetAlgebraicNotationMoves(currentSquare.AlgebraicNotation);
                    }
                    else
                    {
                        _currentPieceANMoves = new string[0];
                    }
                }
                else
                {
                    throw new Exception("Square was unexpectedly null");
                }
            }
            else
            {
                _squareBeginDragCol = null;
                _squareBeginDragRow = null;
            }
            pnlBoard.Invalidate();
        }
Пример #5
0
    public void Move(ChessSquare newPosition)
    {
        int row_change = newPosition.row - currentPosition.row;
        int col_change = DistMap[newPosition.col] - DistMap[currentPosition.col];

        gameObject.transform.position = new Vector3(transform.position.x + SquareSpacing * col_change, transform.position.y, transform.position.z + SquareSpacing * row_change);
        currentPosition.UnHighlight();
        currentPosition = newPosition;
    }
Пример #6
0
    public void StartAt(ChessSquare square, BasePiece[][] pieces)
    {
        pieces[square.Row - 1][square.Column - 65] = this;
        currentSquare = square;
        var rigidBody = gameObject.GetComponent <Rigidbody>();

        rigidBody.isKinematic      = true;
        rigidBody.detectCollisions = false;
        material = GetComponent <Renderer>().material;
        color    = material.color;
    }
Пример #7
0
    // Start is called before the first frame update
    /// <summary>
    /// Initialize basic piece values, center them
    /// </summary>
    void Start()
    {
        hoverSquareName = "";
        center          = GetComponent <MeshRenderer>().bounds.center;
        square          = FindClosestSquare().GetComponent <ChessSquare>();
        pinToPosition(square.GetComponent <MeshRenderer>().bounds.center);
        square.figure = this;

        pauseMenu    = GameObject.Find("PauseMenu");
        settingsMenu = GameObject.Find("Settings");
    }
Пример #8
0
    //给棋盘的每一个位置添加标志位
    void newBoard()
    {
        board = new ChessSquare[12, 12];
        for (int i = 0; i < 12; i++)
        {
            for (int j = 0; j < 12; j++)
            {
                board[i, j] = new ChessSquare();
            }
        }
        for (int i = 0; i < 12; i++)
        {
            board[i, 0].OutOfBoard();
            board[i, 1].OutOfBoard();
            board[i, 10].OutOfBoard();
            board[i, 11].OutOfBoard();
            board[0, i].OutOfBoard();
            board[1, i].OutOfBoard();
            board[10, i].OutOfBoard();
            board[11, i].OutOfBoard();
        }
        for (int i = 2; i < 10; i++)
        {
            board[3, i].pieceSquare = piece.Pawn;
            board[3, i].sideSquare  = side.White;
            board[2, i].sideSquare  = side.White;
            board[8, i].pieceSquare = piece.Pawn;
            board[8, i].sideSquare  = side.Black;
            board[9, i].sideSquare  = side.Black;

            board[9, i].moved = false;
            board[8, i].moved = false;
            board[3, i].moved = false;
            board[2, i].moved = false;
        }
        board[2, 2].pieceSquare = piece.Rook;
        board[2, 3].pieceSquare = piece.Knight;
        board[2, 4].pieceSquare = piece.Bishop;
        board[2, 5].pieceSquare = piece.Queen;
        board[2, 6].pieceSquare = piece.King;
        board[2, 7].pieceSquare = piece.Bishop;
        board[2, 8].pieceSquare = piece.Knight;
        board[2, 9].pieceSquare = piece.Rook;

        board[9, 2].pieceSquare = piece.Rook;
        board[9, 3].pieceSquare = piece.Knight;
        board[9, 4].pieceSquare = piece.Bishop;
        board[9, 5].pieceSquare = piece.King;
        board[9, 6].pieceSquare = piece.Queen;
        board[9, 7].pieceSquare = piece.Bishop;
        board[9, 8].pieceSquare = piece.Knight;
        board[9, 9].pieceSquare = piece.Rook;
    }
Пример #9
0
    public ChessSquare Clone()
    {
        ChessSquare c = new ChessSquare();

        c.pieceSquare = pieceSquare;
        c.sideSquare  = sideSquare;
        c.obj         = obj;
        c.square      = square;
        c.moved       = moved;

        return(c);
    }
Пример #10
0
    private List <BasePiece> StraightLineWalk(ChessSquare target, BasePiece[][] pieces)
    {
        var inPath  = new List <BasePiece>();
        var colDiff = target.Column - currentSquare.Column;
        var colSign = colDiff > 0 ? 1 : -1;
        var rowDiff = target.Row - currentSquare.Row;
        var rowSign = rowDiff > 0 ? 1 : -1;

        var row = currentSquare.Row - 1;
        var col = currentSquare.Column - 65;

        if (colDiff == 0)
        {
            for (var i = 1; i < Math.Abs(rowDiff); i++)
            {
                var possibleTarget = pieces[row + (i * rowSign)][col];
                if (possibleTarget != null && possibleTarget.Team != Team)
                {
                    inPath.Add(possibleTarget);
                }
            }
        }
        else if (rowDiff == 0)
        {
            for (var i = 1; i < Math.Abs(colDiff); i++)
            {
                var possibleTarget = pieces[row][col + (i * colSign)];
                if (possibleTarget != null && possibleTarget.Team != Team)
                {
                    inPath.Add(possibleTarget);
                }
            }
        }
        else if (Math.Abs(rowDiff) == Math.Abs(colDiff))
        {
            for (var i = 1; i < Math.Abs(colDiff); i++)
            {
                var possibleTarget = pieces[row + (i * rowSign)][col + (i * colSign)];
                if (possibleTarget != null && possibleTarget.Team != Team)
                {
                    inPath.Add(possibleTarget);
                }
            }
        }

        return(inPath);
    }
Пример #11
0
 public override void FindMoves(ChessSquare[,] squares)
 {
     this.Moves.Clear();
     for (int p = 0; p <= 7; ++p)
     {
         int c = this.Square.COL + DIRECTIONS[p, 0];
         int r = this.Square.ROW + DIRECTIONS[p, 1];
         if (c >= 0 && r >= 0 && c <= 7 && r <= 7)
         {
             ChessSquare square         = squares[c, r];
             bool        squareBlocked  = square.Piece != null && square.Piece.WHITE == this.WHITE;
             bool        squareAttacked = this.WHITE ? square.BlackAttacked : square.WhiteAttacked;
             if (!(squareBlocked || squareAttacked))
             {
                 this.Moves.Add(square);
             }
         }
     }
 }
Пример #12
0
        private void BtnMovePiece_Click(object sender, EventArgs e)
        {
            try
            {
                var from = new ChessSquare((ChessFile)CmbBxMoveFromLetter.SelectedIndex, (ChessRank)CmbBxMoveFromDigit.SelectedIndex);
                var to   = new ChessSquare((ChessFile)CmbBxMoveToLetter.SelectedIndex, (ChessRank)CmbBxMoveToDigit.SelectedIndex);

                chessboard1.MovePiece(chessboard1.CheckMoveValidity(from, to));
                LblLastMove.Text = $"Last move: {from} to {to}";
                //MessageBox.Show($"Captured piece: {capturedPiece}");
            }
            catch (InvalidCoordinatesException invalidCoordinates)
            {
                MessageBox.Show($"{invalidCoordinates.Message}: '{invalidCoordinates.ParameterName}'");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #13
0
    /// <summary>
    /// manages beating, send piece status to beaten
    /// </summary>
    public void beat()
    {
        var beatenStack = GameObject.Find($"Beaten Pieces {color.ToString()}");
        var stacks      = beatenStack.GetComponent <Beat>().stacks;

        for (int i = 0; i < 15; i++)
        {
            var stack = stacks[i];
            if (stack.isEmpty)
            {
                square = null;
                pinToPosition(stack.transform.position);
                stack.isEmpty      = false;
                transform.position = new Vector3(transform.position.x, transform.position.y - 0.1111f, transform.position.z);
                tag    = "Untagged";
                beaten = true;
                break;
            }
        }
        //Debug.Log("Beat boi!");
    }
Пример #14
0
        private void pnlBoard_MouseUp(object sender, MouseEventArgs e)
        {
            // do we know where we dropped?
            if (_lastSquareMousedOverCol != null && _lastSquareMousedOverRow != null)
            {
                // do we know where we started?
                if (_squareBeginDragCol != null && _squareBeginDragRow != null)
                {
                    ChessSquare startingSquare = _board.Squares[_squareBeginDragCol.Value, _squareBeginDragRow.Value];
                    ChessSquare dropSquare     = _board.Squares[_lastSquareMousedOverCol.Value, _lastSquareMousedOverRow.Value];
                    if (_board.AttemptMove(startingSquare, dropSquare))
                    {
                    }
                }
            }

            _squareBeginDragCol  = null;
            _squareBeginDragRow  = null;
            _currentPieceANMoves = new string[0];
            pnlBoard.Invalidate();
        }
Пример #15
0
 internal ChessMove(ChessSquare startSquare, int destSquare, MoveType type = MoveType.Default) :
     this(startSquare, new ChessSquare(destSquare), type)
 {
 }
Пример #16
0
    private void HighlightSquare(ChessSquare square, bool selecting)
    {
        Color color;
        var   element = cellElements[square.Row - 1][square.Column - 65];

        if (selecting)
        {
            color = Color.black;
        }
        else
        {
            color = startingColors[element];
        }
        var path      = $"StandardChessRow{square.Row}/Cube{square.Column}";
        var component = gameObject.transform.Find(path);

        component.gameObject.GetComponent <Renderer>().material.color = color;

        if (element == (turn == 1 ? team1Element : team2Element))
        {
            var borderColor = startingColors[element];
            if (!selecting)
            {
                borderColor = Color.black;
            }

            foreach (var border in component)
            {
                var borderTransform = (Transform)border;
                borderTransform.gameObject.GetComponent <Renderer>().material.color = borderColor;
            }

            if (square.Row < 8)
            {
                var northBorder     = gameObject.transform.Find($"StandardChessRow{square.Row + 1}/Cube{square.Column}/BorderS");
                var borderTransform = (Transform)northBorder;
                borderTransform.gameObject.GetComponent <Renderer>().material.color = borderColor;
            }

            if (square.Row > 1)
            {
                var southBorder     = gameObject.transform.Find($"StandardChessRow{square.Row - 1}/Cube{square.Column}/BorderN");
                var borderTransform = (Transform)southBorder;
                borderTransform.gameObject.GetComponent <Renderer>().material.color = borderColor;
            }

            if (square.Column != 'A')
            {
                var westBorder      = gameObject.transform.Find($"StandardChessRow{square.Row}/Cube{(char)(square.Column - 1)}/BorderE");
                var borderTransform = (Transform)westBorder;
                borderTransform.gameObject.GetComponent <Renderer>().material.color = borderColor;
            }

            if (square.Column != 'H')
            {
                var eastBorder      = gameObject.transform.Find($"StandardChessRow{square.Row}/Cube{(char)(square.Column + 1)}/BorderW");
                var borderTransform = (Transform)eastBorder;
                borderTransform.gameObject.GetComponent <Renderer>().material.color = borderColor;
            }
        }
    }
Пример #17
0
    public bool move(int i, int j)
    {
        ChessMove move = new ChessMove();

        move.castling    = false;
        move.initialPos  = new Vector2(selectedI, selectedJ);
        move.finalPos    = new Vector2(i, j);
        move.eatenPiece  = board [i, j].pieceSquare;
        move.moved       = board [selectedI, selectedJ].moved;
        move.eatenSide   = board [i, j].sideSquare;
        move.eatenMoved  = board [i, j].moved;
        move.movingPiece = board [selectedI, selectedJ].pieceSquare;

        /* Guardamos los datos de las 2 */
        ChessSquare oldInitial = board [selectedI, selectedJ].Clone();
        ChessSquare oldNext    = board [i, j].Clone();

        /* Se copian los datos de la ficha */
        board [i, j].sideSquare  = board [selectedI, selectedJ].sideSquare;
        board [i, j].pieceSquare = board [selectedI, selectedJ].pieceSquare;
        board [i, j].moved       = true;

        /* Se formatea la antigua celda */
        board [selectedI, selectedJ].sideSquare  = side.None;
        board [selectedI, selectedJ].pieceSquare = piece.None;
        board [selectedI, selectedJ].moved       = true;

        /* Comprobamos futuro jaque. Restablecemos si es invalido el movimiento. */
        AttacksTable t = new AttacksTable(board, !white);

        if (checkCheck(board, oldInitial.sideSquare, t))
        {
            board [i, j].sideSquare  = oldNext.sideSquare;
            board [i, j].pieceSquare = oldNext.pieceSquare;
            board [i, j].moved       = oldNext.moved;

            board [selectedI, selectedJ].sideSquare  = oldInitial.sideSquare;
            board [selectedI, selectedJ].pieceSquare = oldInitial.pieceSquare;
            board [selectedI, selectedJ].moved       = oldInitial.moved;

            checkedCooldown = Time.time;
            return(false);
        }


        /* Se paran los botecitos y se desplaza la ficha */
        board [i, j].obj.GetComponent <Bouncy>().stopBounce();
        paintPiece(i, j);
        showPiece(i, j);
        hidePiece(selectedI, selectedJ);

        /* Se comprueba coronamiento y se efectua */
        if (board [i, j].pieceSquare == piece.Pawn && (i == 9 || i == 2))
        {
            selectedI = i;
            selectedJ = j;

            promotion = true;
            playing   = false;
            Deselect();
            board [i, j].square.GetComponent <Square>().range();
        }
        else
        {
            changeTurn();
            if (oldNext.pieceSquare == piece.King)
            {
                theEnd();
            }
        }

        history.Add(move);
        return(true);
    }
Пример #18
0
 private void chessboard1_OnPieceRemoved(Chessboard sender, ChessSquare from, ChessPiece removedPiece, Point dropPoint)
 {
     LblLastMove.Text     = "Last move:";
     LblGameStatus.Text   = "Game status:";
     LblRemovedPiece.Text = $"Removed piece: {removedPiece.Kind} from {from} to {dropPoint.X},{dropPoint.Y}";
 }
Пример #19
0
    public bool move(int i, int j)
    {
        ChessMove move = new ChessMove();

        move.castling = false;

        move.initialPos = new Vector2(selectedI, selectedJ);
        move.finalPos   = new Vector2(i, j);

        move.eatenPiece  = board[i, j].pieceSquare;
        move.moved       = board[selectedI, selectedJ].moved;
        move.eatenSide   = board[i, j].sideSquare;
        move.eatenMoved  = board[i, j].moved;
        move.movingPiece = board[selectedI, selectedJ].pieceSquare;

        //把数据赋值
        ChessSquare oldInitial = board[selectedI, selectedJ].Clone();
        ChessSquare oldNext    = board[i, j].Clone();

        //复制的数据记录
        board[i, j].sideSquare  = board[selectedI, selectedJ].sideSquare;
        board[i, j].pieceSquare = board[selectedI, selectedJ].pieceSquare;
        board[i, j].moved       = true;

        //旧的棋子位置需要更新状态,也就是格式化
        board[selectedI, selectedJ].sideSquare  = side.None;
        board[selectedI, selectedJ].pieceSquare = piece.None;
        board[selectedI, selectedJ].moved       = true;

        //检查是否可以移动
        AttacksTable t = new AttacksTable(board, !white);

        if (checkCheck(board, oldInitial.sideSquare, t))
        {
            board[i, j].sideSquare  = oldNext.sideSquare;
            board[i, j].pieceSquare = oldNext.pieceSquare;
            board[i, j].moved       = oldNext.moved;

            board[selectedI, selectedJ].sideSquare  = oldInitial.sideSquare;
            board[selectedI, selectedJ].pieceSquare = oldInitial.pieceSquare;
            board[selectedI, selectedJ].moved       = oldInitial.moved;

            checkedCooldown = Time.time;
            return(false);
        }


        //棋子移动以及棋子移动后的状态调整
        board[i, j].obj.GetComponent <Bouncy>().stopBounce(); //棋子动画停止
        paintPiece(i, j);                                     //棋子移动,具体操作将棋子的贴图赋给选择的棋盘位置上的棋子
        showPiece(i, j);                                      //让选择的棋盘为指导上的棋子显示出来
        hidePiece(selectedI, selectedJ);                      //棋子移动后,原位置上的棋子隐藏

        if (board[i, j].pieceSquare == piece.Pawn && (i == 9 || i == 2))
        {
            selectedI = i;
            selectedJ = j;

            promotion = true;
            playing   = false;
            Deselect();
            board[i, j].square.GetComponent <Square>().range();
        }
        else
        {
            changeTurn();
            if (oldNext.pieceSquare == piece.King)
            {
                theEnd();
            }
        }

        history.Add(move);
        return(true);
    }
Пример #20
0
    public virtual string MoveTo(ChessSquare square, BasePiece[][] pieces, bool isBuffed)
    {
        var opposingPiece = pieces[square.Row - 1][square.Column - 65];

        if (isBuffed)
        {
            if (Element == 2) // Fire
            {
                var burnoutPieces = StraightLineWalk(square, pieces);
                foreach (var piece in burnoutPieces)
                {
                    var burnoutRigidBody = piece.GetComponent <Rigidbody>();
                    burnoutRigidBody.isKinematic      = false;
                    burnoutRigidBody.detectCollisions = true;
                    piece.Dead = true;

                    KillPiece(burnoutRigidBody);
                    Destroy(piece, 5);
                }
            }
        }

        Rigidbody rb;
        Rigidbody currentrb;
        var       capturing = false;
        var       check     = IsCheck(pieces);
        var       checkmate = false;

        if (opposingPiece != null)
        {
            capturing             = true;
            rb                    = opposingPiece.GetComponent <Rigidbody>();
            currentrb             = GetComponent <Rigidbody>();
            rb.isKinematic        = false;
            rb.detectCollisions   = true;
            currentrb.isKinematic = false;

            currentrb.detectCollisions = true;

            KillPiece(rb);
            //if (isBuffed)
            //{
            //    if (Element == 2)
            //        KillPiece(currentrb);
            //    else if (Element == 4)
            //    KillPiece(currentrb);
            //    else
            //      KillPiece(rb);

            //      KillPiece(currentrb);
            //}
            opposingPiece.Dead = true;
            Destroy(opposingPiece, 5);
        }

        if (check)
        {
            check     = true;
            checkmate = IsCheckmate(pieces);
        }
        pieces[square.Row - 1][square.Column - 65] = this;
        if (currentSquare != null)
        {
            pieces[currentSquare.Row - 1][currentSquare.Column - 65] = null;
        }
        currentSquare = square;

        return($"{(capturing ? "x" : "")}{currentSquare.ToString()}{(check ? "+" : "")}{(checkmate ? "+": "")}");
    }
Пример #21
0
 private void chessboard1_OnSquareSelected(Chessboard sender, ChessSquare origin, ChessPiece selectedPiece)
 {
     LblSelectedSquare.Text = $"Selected square: {origin.File}{origin.Rank}";
     LblSelectedPiece.Text  = $"Selected piece: {selectedPiece.Kind}";
 }
Пример #22
0
        public void Grid_Click(object sender, EventArgs e)
        {
            string[] stringArr = (sender as Button).Tag.ToString().Split(",");
            int      row       = int.Parse(stringArr[0]);
            int      col       = int.Parse(stringArr[1]);

            ChessSquare chessSquare = cb.Chessboard[row, col];

            if (chessSquare.IsOccupied)
            {
                if (chessSquare.ChessPiece.Name.Equals("Pawn"))
                {
                    try
                    {
                        cb.MovePawn(((ChessPawn)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                else if (chessSquare.ChessPiece.Name.Equals("Knight"))
                {
                    try
                    {
                        cb.MoveKnight(((ChessKnight)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                else if (chessSquare.ChessPiece.Name.Equals("Bishop"))
                {
                    try
                    {
                        cb.MoveBishop(((ChessBishop)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                else if (chessSquare.ChessPiece.Name.Equals("Queen"))
                {
                    try
                    {
                        cb.MoveQueen(((ChessQueen)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                else if (chessSquare.ChessPiece.Name.Equals("King"))
                {
                    try
                    {
                        cb.MoveKing(((ChessKing)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                else if (chessSquare.ChessPiece.Name.Equals("Rook"))
                {
                    try
                    {
                        cb.MoveRook(((ChessRook)cb.Chessboard[row, col].ChessPiece), int.Parse(rowIn.Text.ToString()) - row, int.Parse(colIn.Text.ToString()) - col);
                    }
                    catch (System.InvalidOperationException error)
                    {
                        label1.Text = error.Message;
                    }
                    catch (System.FormatException)
                    {
                        label1.Text = "Input numbers please.";
                    }
                }
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        if (cb.Chessboard[i, j].IsOccupied)
                        {
                            buttonGrid[i, j].Text = cb.Chessboard[i, j].ChessPiece.ToString();
                        }
                        else
                        {
                            buttonGrid[i, j].Text = "";
                        }
                    }
                }
            }
        }
Пример #23
0
 private void OnSquareClick(ChessSquare square)
 {
     MessageBox.Show("You clicked on Row: " + square.Row + " - Column: " + square.Column);
 }
Пример #24
0
        protected async void SquareTapped(object sender, EventArgs e)
        {
            ChessSquare chessSquare = (ChessSquare)sender;

            if (chessSquare.Square.Equals(_activeSelection))
            {
                ClearColored();
                return;
            }

            if (_activeSelection == null ||
                !_board.IsValidMove(new Move(_activeSelection, chessSquare.Square, _board.WhoseTurn(), PawnPromotion.Queen)))
            {
                ClearColored();
                if (_board[chessSquare.Square] == null || _board[chessSquare.Square].Owner != _board.WhoseTurn())
                {
                    return;
                }

                List <Move> validMoves = ChessUtilities.GetValidMovesOfSourceSquare(chessSquare.Square, _board);
                if (validMoves.Count == 0)
                {
                    return;
                }
                _activeSelection = chessSquare.Square;
                ChessSquare src = this.FindByName <ChessSquare>(chessSquare.Square.ToString());
                src.BackgroundColor = Color.DarkCyan;
                _colored.Add(src);
                foreach (Move m in validMoves)
                {
                    ChessSquare dest = this.FindByName <ChessSquare>(m.Destination.ToString());
                    dest.BackgroundColor = Color.Cyan;
                    _colored.Add(dest);
                }
            }
            else
            {
                PawnPromotion?promotion = null;
                if (_board[_activeSelection] is Pawn && (chessSquare.Square.Rank == Rank.First || chessSquare.Square.Rank == Rank.Eighth))
                {
                    string strProm;
                    do
                    {
                        strProm = await DisplayActionSheet("Promote to what ?", null, null, "Queen", "Rook", "Knight", "Bishop");
                    } while (strProm == null);
                    Enum.TryParse(strProm, out PawnPromotion temp_promotion);
                    promotion = temp_promotion;
                }
                var move = new Move(_activeSelection, chessSquare.Square, _board.WhoseTurn(), promotion);
                _board.MakeMove(move, isMoveValidated: true);

                ChessSquare src = this.FindByName <ChessSquare>(_activeSelection.ToString());


                Piece p1 = _board[chessSquare.Square];
                Piece p2 = _board[_activeSelection];

                if (p1 is King && move.GetAbsDeltaX() == 2 ||
                    p1 is Pawn && move.GetAbsDeltaX() == 1) // Draw complete board only on Special Moves (Castle, Enpassant).
                {
                    DrawBoard();
                }
                else // On regular moves, draw particular squares only. (For performance reasons)
                {
                    if (p1 == null)
                    {
                        chessSquare.Source = "";
                    }
                    else
                    {
                        chessSquare.Source   = $"{p1.Owner}{p1.GetType().Name}";
                        chessSquare.Rotation = (p1.Owner == Player.White) ? 0 : 180;
                    }

                    if (p2 == null)
                    {
                        src.Source = "";
                    }
                    else
                    {
                        src.Source   = $"{p2.Owner}{p2.GetType().Name}";
                        src.Rotation = (p2.Owner == Player.White) ? 0 : 180;
                    }
                }

                ClearColored();

                GameState state = _board.GameState;
                if (state == GameState.BlackWinner)
                {
                    await DisplayAlert("Game over!", "Black has won the game.", "OK");
                }
                else if (state == GameState.WhiteWinner)
                {
                    await DisplayAlert("Game over!", "White has won the game.", "OK");
                }
                else if (state == GameState.Stalemate || state == GameState.Draw)
                {
                    await DisplayAlert("Game over!", "Game is draw.", "OK");
                }
            }
        }
Пример #25
0
 internal ChessMove(ChessSquare startSquare, ChessSquare destSquare, MoveType type = MoveType.Default)
 {
     StartSquare       = startSquare;
     DestinationSquare = destSquare;
     MoveType          = type;
 }
Пример #26
0
 public King(ChessSquare square) : base(square)
 {
 }