Design and implement a class called Square that creates objects that represent s
ID: 3683095 • Letter: D
Question
Design and implement a class called Square that creates objects that represent squares on a chess board. The Square constructor should take three parameters: the row and column numbers of a square on a chess board, and a third integer that gives the size of a board that contains the square being constructed. (Your construction should work with any NxN board with N >= 6.) An object of the Square class should have a row number and a column number that represent the square’s position on the board. An object of the square class should also have a method, called legalMoves(), that returns a list of the row and column numbers of those squares that can be reached from the given square by legal knight move. Include whatever additional attributes and methods as appropriate. Illustrate your class by providing a program that accepts as input a row number, a column number, and a board size, and displays the list of legal knight moves corresponding data. (Assume that the rows and columns are labeled with (0,0) in the upper left corner.)
Explanation / Answer
public class Square {
int row,column,size;
Square(int r,int c,int n)
{
this.row=r;
this.column=c;
this.size=n;
}
public void legalMoves()
{
//conditions for checking four directions of the knight
if(column+2<size)
{
if((row-1)>=0)
System.out.println((row-1)+" "+(column+2));
if((row+1)<size)
System.out.println((row+1)+" "+(column+2));
}
if(column-2>=0)
{
if((row-1)>=0)
System.out.println((row-1)+" "+(column-2));
if((row+1)<size)
System.out.println((row+1)+" "+(column-2));
}
if(row-2>=0)
{
if((column+1)<size)
System.out.println((row-2)+" "+(column+1));
if((column-1)>=0)
System.out.println((row-2)+" "+(column-1));
}
if(row+2<size)
{
if((column+1)<size)
System.out.println((row+2)+" "+(column+1));
if((column-1)>=0)
System.out.println((row+2)+" "+(column-1));
}
}
public static void main(String args[])
{
//change here to check for different box.
Square a=new Square(2,3,8);
//method for checking moves
System.out.println("Legal moves");
a.legalMoves();
}
}
------------------------------------------------------------------------------------------------------
//if the knight is at (2,3) here are the legal moves given by the above program.
example output for the above prog:
Legal moves
1 5
3 5
1 1
3 1
0 4
0 2
4 4
4 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.