Reputation: 31
i am developing a chessgame and have been able to made my Pawn piece move both one and two squares forward but i am having difficulty preventing it from moving two squares forward after its first move. Please i will be grateful if someone can help me with a logic or idea on how to implement it.
Here is my code:
private boolean isValidPawnMove(int sourceRow, int sourceColumn, int targetRow, int
targetColumn) {
boolean isValid = false;
if(isTargetLocationFree()){
if(sourceColumn == targetColumn){
//same column
if(sourcePiece.getColor() == Piece.YELLOW_COLOR){
//yellow
if(sourceRow + 1 == targetRow ){
//move one up
isValid = true;
}else if(sourceRow + 2 == targetRow ){
isValid = true;
}else{
//not moving one up
isValid = false;
}
}else{
//brown
if(sourceRow - 1 == targetRow){
//move one down
isValid = true;
}else if(sourceRow - 2 == targetRow){
isValid = true;
}else{
//not moving one down
isValid = false;
}
}
}else{
//not the same column
isValid = false;
}
}else if(isTargetLocationCaptureable()){
if(sourceColumn + 1 == targetColumn || sourceColumn - 1 == targetColumn ){
//one column to the right or left
if(sourcePiece.getColor() == Piece.YELLOW_COLOR){
//yellow
if(sourceRow + 1 == targetRow){
//move one up
isValid = true;
}else{
//not moving one up
isValid = false;
}
}else{
//brown
if(sourceRow - 1 == targetRow ){
//move one down
isValid = true;
}else{
//not moving one down
isValid = false;
}
}
}else{
//One column to the left or right
isValid = false;
}
}
return isValid;
}
private boolean isTargetLocationCaptureable(){
if(targetPiece == null){
return false;
}else if( targetPiece.getColor() != sourcePiece.getColor()){
return true;
}else{
return false;
}
}
private boolean isTargetLocationFree(){
return targetPiece == null;
}
Upvotes: 0
Views: 400
Reputation: 234797
For yellow pieces, just check that sourceRow
is 1 (or 2, depending on how you are numbering rows):
...
}else if(sourceRow == 1 && targetRow == 3){
// double-row first move
isValid = true;
}else{
...
Do a similar thing for the brown pieces.
Upvotes: 2
Reputation: 276
I'd do it one of two ways:
Upvotes: 0
Reputation: 3625
Assuming you have a class for your Pawn, then you should create a field in the class called firstmove
or numMoves
. This would be set to true
or 0
respectively, and after the first move set to false
or numMoves++
. Then, in your validity checker, you can say
if p.firstMove
//accept 1 or 2
else
//accept only 1
Upvotes: 0
Reputation: 393841
I won't write the code for you, but your condition should be based on the sourceRow. If your source row is the original row the pawn started on (second or seventh row, depending on which player), only then can the pawn move two rows.
Upvotes: 5