我正在用Java制作国际象棋游戏,而棋子给我带来了麻烦。老实说,我不知道为什么,因为他们的动作是最简单的。这是 Piece 声明和 Pawn(扩展 Piece)声明。运动类定义了一个简单的 x;y 对象,我用它来标记板上可能的运动目标。我有一个 GameHandler 类,以后会根据游戏规则清除所有不可能的运动。但是 Pawn 的移动数组似乎很干净;所有其他作品的动作都像奇迹一样工作!提前致谢!
件类
public abstract class Piece{
protected int x, y;
protected boolean isWhite;
protected ArrayList<Movement> moves;
public Piece(int x, int y, boolean isWhite) {
this.x=x;
this.y=y;
this.isWhite = isWhite;
moves = new ArrayList<Movement>();
}
public abstract ArrayList<Movement> getMoves();
//obvious methods
public int getX()
public int getY()
public boolean isWhite()
//end obvious methods
public void setCoordinates(int x, int y){
this.x=x;
this.y=y;
}
}
典当类
public class Pawn extends Piece{
public Pawn(int x, int y, boolean isWhite){
super(x,y,isWhite);
}
public ArrayList<Movement> getMoves() {
moves.clear();
if(isWhite){
if(y>0) moves.add(new Movement(x, y-1));
if(y==7) moves.add(new Movement(x, y-2));
}else{
if(y<7) moves.add(new Movement(x, y+1));
if(y==0) moves.add(new Movement(x, y+2));
}
return moves;
}
}
编辑:添加 King 类作为参考
public class King extends Piece{
public King(int x, int y, boolean isWhite){
super(x,y,isWhite);
}
public ArrayList<Movement> getMoves() {
moves.clear();
if(y-1>=0 && x-1>=0) moves.add(new Movement (x-1, y-1));
if(y-1>=0 && x+1<8) moves.add(new Movement (x+1, y-1));
if(y+1<8 && x+1<8) moves.add(new Movement (x+1, y+1));
if(y+1<8 && x-1>=0) moves.add(new Movement (x-1, y+1));
if(y-1>=0) moves.add(new Movement (x, y-1));
if(y+1<8) moves.add(new Movement (x, y+1));
if(x+1<8) moves.add(new Movement (x+1, y));
if(x-1>=0) moves.add(new Movement (x-1, y));
return moves;
}
}