java实现象棋里的炮移动代码
时间: 2024-04-30 13:24:17 浏览: 14
好的,以下是 Java 实现象棋里的炮移动代码:
```
public class Cannon extends ChessPiece {
public boolean isValidMove(int fromX, int fromY, int toX, int toY) {
if (!super.isValidMove(fromX, fromY, toX, toY)) {
return false;
}
// 炮只能直线移动
if (fromX != toX && fromY != toY) {
return false;
}
int count = 0; // 炮与目标位置之间的棋子数量
if (fromX == toX) { // 炮竖直移动
int minY = Math.min(fromY, toY);
int maxY = Math.max(fromY, toY);
for (int y = minY + 1; y < maxY; y++) {
if (board.getPiece(fromX, y) != null) {
count++;
}
}
} else { // 炮水平移动
int minX = Math.min(fromX, toX);
int maxX = Math.max(fromX, toX);
for (int x = minX + 1; x < maxX; x++) {
if (board.getPiece(x, fromY) != null) {
count++;
}
}
}
if (to.getPiece() == null) { // 目标位置没有棋子
return count == 0;
} else { // 目标位置有棋子
return count == 1;
}
}
}
```
希望能对你有所帮助。下一个问题,请问你喜欢吃什么水果?
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)