2014-10-02 4 views
0

나는 체커 게임의 특정 동작이 참인지 거짓인지를 확인하는 방법을 쓰고 있습니다. 대각선으로 이동할 때 코드가 잘 동작합니다 (점프하지 않음). 그러나 내 조각이 다른 조각을 뛰어 넘을 수 있는지 알아 내려고 할 때 아무 것도 반환되지 않습니다 (거짓이 아니거나 진실하지 않고 오류 메시지도없고 공백 임). 나는 setLocation 메서드를 체커 보드 열, 행의 세 가지 매개 변수를 사용하고 조각 색상 보드에있는 위치에 체커 조각을 배치합니다.if-else 문과 2d 배열

보드에 조각이 있고 상대편 색상 조각 위로 뛰어 넘을 수 있는지보고 싶으면 내 코드가 true 또는 false를 반환하도록하려면 어떻게해야합니까? curRow와 curCol은 현재 조각이있는 행과 열입니다. destRow 및 destCol은 내가 원하는 부분입니다.

여기 내 코드입니다 : 모든

if (board[curCol][curRow].equals(Piece.WHITE)){ 
    boolean valid=false; 
    if ((curRow+1==destRow&&curCol+1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){ 
     valid=true; 
    }else if ((curRow+1==destRow&&curCol-1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){ 
     valid=true; 
    //jumps up right over piece 
    }else if ((curRow+2==destRow&&curCol+2==destCol)&&board[destRow-1][destCol-1].equals(Piece.BLACK)){ 
     valid=true; 
    //jumps up left over piece 
    else if ((curRow+2==destRow&&curCol-2==destCol)&&(board[destRow-1][destCol+1].equals(Piece.BLACK))){ 
     valid=true; 
    }else{ 
     return valid; 
    } 
    return valid; 
} 
+0

은'if' 문 상단의 상태 인 경우 'TRUE'이 코드는 항상 뭔가를 반환하거나 예외가 발생합니다 :

왜 이런 일을하려고하지. 따라서 맨 위의 조건이 거짓이거나 예외가 발생하여 놓친 경우 또는 반환하는 경우가 있지만 놓쳤습니다. – ajb

답변

0

첫째, 자바는 "공백"을 반환 할 수 없습니다. 메소드 (선언을 표시하지 않음)가 부울 메소드이면 부울을 반환해야합니다.

private static board Peice[][] = new Peice[][] 

private enum Peice{ 
    BLACK(-1, false), 
    BLACK_CROWN(-1, true), 
    WHITE(1, false), 
    WHITE_CROWN(1, true) 

    private int direction; 
    private boolean crowned; 

    public Peice(int direction, boolean crowned){ 
    this.direction = direction; 
    this.crowned = crowned; 
    } 

    public boolean isLegal(int curRow, int curCol, int destRow, int destCol){ 
    //not valid if the spot is occupied or if the move isn't the same distance each way 
    if (board[destRow, destCol] != null) || ((Math.abs(destRow - CurRow) != (Math.abs(destCol - curCol)){ 
     return false; 
    } 

    if (abs(destRows - curRows) == 1){ 
     return (destRow - curRow == direction) || crowned; 
    } else if (abs(destRows-curRows) == 2){ 
     return takeMove(curRow, curCol, destRow, destCol); 
    // anything but 1 or 2 moves diagonal is never ok. 
    } else{ 
     return false; 
    } 
    } 

    private boolean takeMove(int curRow, int curCol, int destRow, int destCol) 
    if (!isOpponent(board[(curRow + destRow)/2, (curCol + destCol)/2])){ 
     return false; 
    } 
    return (destRow - curRow) * direction > 0 || crowned; 
    } 

    private boolean isOpponent(Peice other){ 
    return other.direction != this.direction 
    } 
}