i'm trying to solve this exercise. It should take two parameters for coordinates and display possible next positions in relation to the entered position coordinates. Currently i'm able to get the board with entered position, but how to calculate next possible positions for the Knight chess figure? Thanks for any clues / suggestions. My Main file:
package lt.chess;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Board board = new Board();
Scanner scanner = new Scanner(System.in);
System.out.println("");
System.out.print("Enter board number: ");
String digit = scanner.next();
System.out.print("Enter board letter: ");
String letter = scanner.next();
Knight knight = new Knight("Knight");
board.setFigure(knight, digit, letter);
board.showFigures();
}
}
Board class:
package lt.chess;
public class Board {
private String letters = "ABCDEFGH";
private String digits = "12345678";
private Figure[][] arrayFigure = null;
public Board() {
arrayFigure = new Figure[letters.length()][digits.length()];
createBoard();
}
private void createBoard() {
for (int row = digits.length() - 1; row >= 0; row--) {
System.out.print(digits.charAt(row));
for (int x = 0; x < letters.length(); x++) {
System.out.print(" ");
if (arrayFigure[row][x] != null)
System.out.print("X");
}
System.out.println("");
if (row == 0) {
System.out.print(" ");
for (int col = 0; col < letters.length(); col++) {
System.out.print(letters.charAt(col) + " ");
}
}
}
}
public void setFigure(Knight knight,
String digit,
String letter) {
int y = digits.indexOf(digit);
int x = letters.indexOf(letter);
arrayFigure[y][x] = knight;
}
public void showFigures() {
createBoard();
}
}
Figure class:
package lt.chess;
public class Figure {
private String[] figureColor = {"Black", "White"};
private String figureName;
Figure(String figureName) {
this.figureName = figureName;
}
public String getName() {
return this.figureName;
}
}
Knight class:
package lt.chess;
public class Knight extends Figure {
Knight(String name) {
super(name);
}
}
To add a control for board-edges and used fields to Minh's answer, I would provide a method creating the next possible positions (Points)
private LinkedList<Point> getNextPositions(int x, int y){
int[] xOffsets = {-2, -1, 1, 2, 2, 1, -1, -2};
int[] yOffsets = {1, 2, 2, 1, -1, -2, -2, -1};
Point nextPosition;
LinkedList<Point> = new LinkedList<Point>();
for(int i = 0; i < xOffsets.length; i++) {
nextPosition = new Point(x+xOffsets(i),y+yOffsets(i));
if (isWithinBoardAndFree(nextPosition))
{
erg.add(nextPosition);
}
}
}
To check these points I used a second method:
private boolean isWithinBoardAndFree(Point point, Figure[][] board){
if (point.x >= 0 && point.x >= 0)
{
if (board[point.x][point.y] == null)
{
return true;
}
}
return false;
}
I am not sure about your exercise, but you might consider releasing a field the knight came from.