0% found this document useful (0 votes)
6 views1 page

Knight Moves Validity Checker

This Java code defines methods to calculate valid knight moves on a chessboard from a given starting position. It checks if a row and column are valid on an 8x8 board, calculates the destination position after a knight's 2 row, 1 column or 2 column, 1 row move, and returns all possible destinations for a knight from a given starting position. The main method tests the methods by checking validity, calculating single moves, and finding all moves from sample positions.

Uploaded by

Adelina Răducan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Knight Moves Validity Checker

This Java code defines methods to calculate valid knight moves on a chessboard from a given starting position. It checks if a row and column are valid on an 8x8 board, calculates the destination position after a knight's 2 row, 1 column or 2 column, 1 row move, and returns all possible destinations for a knight from a given starting position. The main method tests the methods by checking validity, calculating single moves, and finding all moves from sample positions.

Uploaded by

Adelina Răducan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd

package ex_cap1;

public class Ex11_KnightMoves {


public static boolean isValid(int row, int col) {
return row >= 1 && row <=8 && col <= 8 && col >= 1;
}
public static String getDestinationValue(int crtRow, int
crtCol, int rowsMoved, int colMoved) {
int destRow, destCol;
destRow = crtRow + rowsMoved;
destCol = crtCol + colMoved;
return (isValid(destRow, destCol) && isValid(crtRow,
crtCol))==true? "(" + (crtRow + rowsMoved) + "," + (crtCol +
colMoved) + ")":"false";
}
public static String getAllDestinations(int crtRow, int
crtCol) {
return getDestinationValue(crtRow, crtCol, 2, 1) + " " +
getDestinationValue(crtRow, crtCol, 2, -1) + " " +
getDestinationValue(crtRow, crtCol, -2, 1)
+ " " + getDestinationValue(crtRow, crtCol, -2, -1) + "
" + getDestinationValue(crtRow, crtCol, 1, -2) + " " +
getDestinationValue(crtRow, crtCol, 1, 2) + " " +
getDestinationValue(crtRow, crtCol, -1, 2) + " " +
getDestinationValue(crtRow, crtCol, -1, -2);
}

public static void main (String[] args) {


[Link](isValid(1, 9));
[Link](isValid(2, 4));
[Link](getDestinationValue(1, 1, -2, +1));
[Link](getDestinationValue(1, 1, +2, +1));
[Link](getAllDestinations(1, 1));
[Link](getAllDestinations(2, 4));
}

You might also like