Search code examples
javachess

How to move pieces in chess?


I am currently working on designing abstract classes for a possible chess game. I needed help regarding how to move different pieces(for example queen, knight)

public class MyPiece extends Piece {

@Override
public boolean canMove(int x, int y) {
    return (this.x != x && Math.abs(this.y - y) == 1);
}
}

The above code displays a sample for some piece that can just move up and down. It is not a valid chess move. So if i were to move a queen how would i go about?To simply things we are just assuming that we already have a board of matrix (x,y) 8 by 8.


Solution

  • Especially for chess queen it is not so simple. You have to:

    1. determine that the move straight, i.e. horizontal, vertical, or diagonal.
    2. That there are no other pieces on the way.

    So,

    • To determine that move is horizontal check this.x == x && this.y != y
    • To determine that move is vertical check this.y == y && this.x != x
    • To determine diagonal check Math.abs(this.x - x) == Math.abs(this.y - y)

    Now chose the direction, iterate over the way and check that your matrix does not contain elements in cells that are going to be passed by queen during this move.