我正在尝试实现自己的国际象棋游戏,但是我在努力当兵课程的运动。
典当的一般规则是,如果典当仍在其开始位置,则它可以移动2步。之后,它只能向前迈出一步。我的白色棋子可以做应有的一切,但是我的黑色棋子只有两步移动。
棋盘的大小为8x8。
public Point[] getMoveFields() {
System.out.println(ChessBoard.getAllChessPieces().length);
System.out.println(ChessBoard.getAllChessPieces());
Point[]getMoveFields = new Point[2];
System.out.println("(X: " + getX() + ", Y: " + getY() +"); " + "Chess Piece ID: " + getId());
getMoveFields[0]= getColor().equals(ChessColor.WHITE) && (getY()==1)? new Point (getX(),getY()+2) : new Point (getX(),getY()-2);
getMoveFields[1]= getColor().equals(ChessColor.WHITE) && (getY()>=1)? new Point(getX(),getY()+1) : new Point(getX(),getY()-1);
return getMoveFields;
将内容写出来,不要使用?:
运算符。
但是,主要是,如果:
getColor().equals(ChessColor.WHITE)
返回false
,则冒号:
之后的代码将始终运行,因此getMoveFields[0]
和[1]
都将被设置为点,一个为getY()-2
,一个为getY()-1
。
相反,为什么不生成一种检查典当是否针对特定颜色的行的方法,例如:
boolean pawnOnStartingLine();
例如,您可能会想到这样的代码:
public class Pawn {
// === definitions required for demo ===
private ChessColor color = ChessColor.BLACK;
private int x = 0;
private int y = 7;
class Point {
private int x;
private int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d,%d)", x, y);
}
}
public enum ChessColor {
WHITE, BLACK;
}
// === real code starts here ===
public Point[] getMoveFields() {
final Point[] fields;
if (onStartingLine()) {
fields = new Point[2];
fields[0] = new Point(x, y + getStepForward());
fields[1] = new Point(x, y + 2 * getStepForward());
} else {
fields = new Point[1];
fields[0] = new Point(x, y + getStepForward());
}
return fields;
}
private boolean onStartingLine() {
return color == ChessColor.WHITE && y == 1 || color == ChessColor.BLACK && y == 7;
}
private int getStepForward() {
switch (color) {
case WHITE:
return 1;
case BLACK:
return -1;
default:
throw new IllegalStateException();
}
}
public static void main(String[] args) {
Pawn pawn = new Pawn();
Point[] fields = pawn.getMoveFields();
for (Point field : fields) {
System.out.println(field);
}
}
}
请注意,这不一定是最好的设计,但是我认为您已经有了使用明确命名的方法以及getStepForward
方法的小技巧的想法。