gpt4 book ai didi

java - 如何使用JAVA根据当前位置找到可能的棋子(马)位置?

转载 作者:行者123 更新时间:2023-11-30 06:50:40 27 4
gpt4 key购买 nike

我正在尝试解决这个练习。它应该采用两个坐标参数,并显示与输入的位置坐标相关的可能的下一个位置。目前我可以得到具有输入位置的棋盘,但是如何计算骑士国际象棋人物的下一个可能的位置?感谢您提供任何线索/建议。我的主文件:

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();
}
}

板级:

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();
}

}

图形类:

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;
}

}

骑士等级:

package lt.chess;

public class Knight extends Figure {

Knight(String name) {
super(name);
}

}

最佳答案

为了在 Minh 的答案中添加对板边缘和使用字段的控制,我将提供一种创建下一个可能位置(点)的方法

 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);
}
}
}

为了检查这些点,我使用了第二种方法:

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;
}

我不确定你的练习,但你可能会考虑释放骑士来自的领域。

关于java - 如何使用JAVA根据当前位置找到可能的棋子(马)位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855277/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com