I currently developing a Chess Game in java using the eclipse IDE,
I Have all the movement of the pieces down apart from the Pawn which is the hardest because the Pawn has to be able to make to different moves
The Pawn should be able to move twice at the start and then only one after that
Currently I have set the pawn to only move twice but I am stuck on getting the rest of the logic to work
I have been working with the idea of an if/else statement
I could use some help writing it
Here is the Code so far for the Pawn and I have included comment's for your use
Update to Problem it is only with the black pawn is not moving right I was able to set the white one the right way but not the black I dont know why it doesnt work
//Pawn Movement
private boolean isValidPawnMove(int sourceRow, int sourceColumn, int targetRow, int targetColumn) {
boolean isValid = false;
if( isTargetLocationFree() ){
if( sourceColumn == targetColumn){
if( sourcePiece.getColor() == Piece.COLOR_WHITE ){
// White Pawn
if( sourceRow+1 == targetRow || sourceRow == 1 && targetRow == 3){//Pawns can move to at the start then only 1 after that
isValid = true;
}else{
isValid = false;
}
}
else{
// Black Pawn
if( sourceRow-1 == targetRow || sourceRow == -1 && targetRow == -3){
isValid = true;
}else{
isValid = false;
}
}
}else{
//If you try to move left or right into a different Column
isValid = false;
}
//Take square occupied by an opponent’s piece, which is diagonally in front
}else if( isTargetLocationCaptureable() ){
if( sourceColumn+1 == targetColumn || sourceColumn-1 == targetColumn){
//One column to the right or left
if( sourcePiece.getColor() == Piece.COLOR_WHITE ){
//White Piece
if( sourceRow+1 == targetRow ){
//Move one up
isValid = true;
}else{
//Not moving one up
isValid = false;
}
}else{
//Black Piece
if( sourceRow-1 == targetRow ){
//Move one down
isValid = true;
}else{
//Not moving one down
isValid = false;
}
}
}else{
//Not one column to the left or right
isValid = false;
}
}
return isValid;
}
Thanks for any help you can provide
I think the easiest solution is to explicitly check the source and target rows as white pawns can only move two forward from the second rank, so your logic becomes (for white):
if( sourceRow+1 == targetRow || sourceRow == 2 && targetRow == 4) {
Obviously you will also need to check that (sourceColumn, 3) is also empty.