Question

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.

Was it helpful?

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.

OTHER TIPS

You need to think in terms of "Given piece P on location (x,y) on the board which coordinates can the piece move to?". I.e. for a rook on (1,1) you can move to (1,2)..(1,8) and (2,1)..(8,1).

Unfortunately there are additional restrictions, for example:

  • Most pieces cannot pass other pieces. Hence, you need to know the coordinates of pieces on the board.
  • Kings cannot move into a check. Hence, you need to know the locations of where the opponents pieces can move to.
  • Kings can castle if they have not moved (it is not enough to be in the original position). Hence you need to know the history of the game.

Modelling a chess game is an interesting exercise, but perhaps you should try checkers first to get accustomed to working with an abstract representation of a physical game, and then have a second go at chess?

Quick though:

Introduce an interface called "Moveable". Your figure classes (you call them "pieces") will be defined like this. Extract your canMove() method into this interface and add move() method returning some unchecked exception if it fails.

 public class MyPiece extends Piece implements Moveable{
//your code goes here
 }

Create enum called MovementPossibilities. Here you should store all possible movements. Each movement possibility consists of possible directions (binary status, just on/off, true/false, can move in that direction/cannot). For every direction, introduce three integers -> minStep, maxStep, stride. Obviously, they tell you how much your figure can move in given direction.

This attemp is good in one thing - it first lets you test if your figure can move in that direction. If no, no other tests are needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top