Hello!大家好!今天我们来写国际象棋棋子的一些走法和吃法,其中主要包括以下几种规则:
1.车走直线,象走斜线,马走日字,后走直线和斜线,王也是走直线和斜线但只能走一格。
2.兵一开始可以往前走两格或者一格,但之后只能往前走一格,而且兵不能后退。
3.兵吃子的时候只能吃斜上方一格的棋子,其他棋子吃法与走法相同。
4.两种兵的特殊走法:升变和吃过路兵
在开始写规则之前,我们要引入两个函数,跟斗兽棋一样,我们要判断出棋子的种类和所属一方。具体的方法我在之前写斗兽棋的时候也有介绍过,就是
private static String getname(MyIcon icon) {判断棋子的种类(不分黑白)
if(icon.getPath()==paths[0]||(icon.getPath()==paths[1])) {
return "pawn";
}
if(icon.getPath()==paths[2]||(icon.getPath()==paths[7])) {
return "rook";
}
if(icon.getPath()==paths[3]||(icon.getPath()==paths[8])) {
return "knight";
}
if(icon.getPath()==paths[4]||(icon.getPath()==paths[9])) {
return "bishop";
}
if(icon.getPath()==paths[5]||(icon.getPath()==paths[10])) {
return "queen";
}
if(icon.getPath()==paths[6]||(icon.getPath()==paths[11])) {
return "king";
}
return "";
}
private static String getside(MyIcon icon) {判断棋子所属一方
if(icon.getPath()==paths[0]||icon.getPath()==paths[2]||icon.getPath()==paths[3]
||icon.getPath()==paths[5]||icon.getPath()==paths[6]||icon.getPath()==paths[4]) {
return "black";
}
if(icon.getPath()==paths[1]||icon.getPath()==paths[7]||icon.getPath()==paths[8]
||icon.getPath()==paths[11]||icon.getPath()==paths[10]||icon.getPath()==paths[9]) {
return "white";
}
return "";
}
那我们先来写车的规则
private static boolean rooklegal(MyLabel a,MyLabel b) {
MyIcon a1=(MyIcon) a.getIcon();起始格子上的棋子
MyIcon b1=(MyIcon) b.getIcon();目标格子上的棋子(有可能是null)
然后我们把两个格子所在的行与列分别取最小值和最大值
int r1=Math.min(a.row, b.row);
int r2=Math.max(a.row, b.row);
int c1=Math.min(a.col, b.col);
int c2=Math.max(a.col, b.col);
if(a.row==b.row&&a.col==b.col) {不能原地不动
return false;
}
if(a.row==b.row) { 这是在同一列的时候
for(int i=c1;i<=c2;i++) {查看他们之间的格子(行数从小到大)
if(labels[a.row][i]!=a) {不包括起始格子本身
if(labels[a.row][i]==b&&b1!=null) {如果循环到了目标格子,而且目标格子上有棋子的话,
就要判断该棋子是否与被走