Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkers Game: Not Error Checking Correctly?

Tags:

java

I'm making a Checkers game for an assignment. The whole thing is running the way it should, except for one weird thing. Here's my board:

Checkers Board

I move by giving the source row and column, then the destination row and column.

move(int srcR, int srcC, int destR, int destC)

I'm supposed to print out an error if I try to move a piece to an invalid spot (not diagonally). So if I try to move a piece from 5 2 -> 4 2, it gives me an error message.

if(destR == srcR+1 || destR == srcR-1 &&
    destC == srcC+1 || destC == srcC-1){
        // code code code
}else
    message = "Invalid Move! Can only move diagonally one space.";

For most things it works, but if I try to move directly down one space (for example, 2 3 -> 3 3) it's moving the piece and not giving me the error message.

I'm stuck! Any ideas why this may be happening? I can post more code if needed.

like image 481
alu Avatar asked Aug 05 '13 15:08

alu


2 Answers

According to your logic, if

destC == srcC-1

is true, the whole expression will be true. You have to pay attention to the order that Java evaluate the boolean operations~ Add () when necessary~

like image 196
charles_ma Avatar answered Sep 20 '22 07:09

charles_ma


It is quite simple, I think. There are only four allowed moves.

int deltaX = Math.abs(srcR - destR);
int deltaY = Math.abs(srcC - destC);
boolean validMove = deltaX == 1 && deltaY == 1;

Of course, this check allows backward moves. But the direction of a backward move depends on the playing color and wether the piece is promoted by reaching the other end.

like image 20
Martijn Courteaux Avatar answered Sep 18 '22 07:09

Martijn Courteaux