开发者

Implementing rules for a Bishop in Chess

I'm trying to think of a way to efficiently and neatly determine whether a valid move is be开发者_高级运维ing made with a bishop in chess.

The piece will be moved from srcX,srcY to dstX,dstY

This is part of one of my ideas:

    if(srcX < dstX && srcY < dstY) {
        // Moving towards the top right of the board
                        // Determine the decrease in X coordinate
            int deltaX = dstX-srcX;

            // If the move is valid, the Y coordinate will have decreased by the same number as X
            int validY = dstY-deltaX;

            if(validY == srcY) {
                validMove = true;
            }

    }

but it's going to be a bit long winded, doing that for ever corner.. Can anyone think of a nicer way?


I would break it up into two steps.

1) Is it a valid destination? 2) Are there obstructions?

The first is easy to calculate. Since a bishop can only move diagonals the deltaX and deltaY must be equal.

So, if( abs(srcX-dstX) == abs(srcY-dstY) )

That rules out logically invalid moves.

Then it is a simple matter iterating through the positions in between as you have done to check for obstructions.


If it's a diagonal the x and y move shoudl be the same, so...

return Math.abs(srcx - dstx) == Math.abs(srcy - dsty);


The move is valid if:

      Destx-Desty = SourceX - SourceY      OR 

16 - DestX- DestY = SourceX - SourceY
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜