1.重载判断重复棋子的方法,给方法添加color参数,旨在比较棋子的颜色
private static boolean isExist(int x,int y,Color color) {//循环棋子数组(判断连续棋子是否是同色棋子)int lenth = chesses.length;for(int i = 0; i < lenth; i ++) {Chess chess = chesses[i];if(chess != null) {if(x == chess.getX() && y == chess.getY() && chess.getColor().equals(color)) {return true;}}}return false;}
2.根据当前棋子的坐标进行检索,看相邻位置是否有棋子,方向分为 向左、向右、向上、向下、右上左下、左上右下,如果大于等于5颗,则胜利
private static boolean isWin(Chess chess) {//默认有一颗int count = 1;int x = chess.getX();int y = chess.getY();//先向左判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环for(int i = x - 1; i >= 0 && i >= x - 4; i --) {if(isExist(i, y, chess.getColor())) {count ++;}else {break;}}if(count >=5) {return true;}//其他方向同理//此为斜向例子count = 1;//先向右上判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环for(int i = x + 1, j = y - 1;i < SIZE && i <= x + 4 && j >= 0 && j >= y -4;i ++,j --) {if(isExist(i, j, chess.getColor())) {count ++;}else {break;}}//再向左下判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环for(int i = x - 1,j = y + 1;i >= 0 && i >= x - 4 && j < SIZE && j <= y + 4;i --,j ++) {if(isExist(i, j, chess.getColor())) {count ++;}else {break;}}if(count >=5) {return true;}
3.弹出胜利提示框,停止下棋
//点击事件添加,用于停止游戏if (gameOver) {return;}//胜利if(isWin(chess)) {Alert alert = new Alert(AlertType.INFORMATION);alert.initOwner(this);alert.setTitle("对战结果:");alert.setContentText(isBlack ? "白棋赢" : "黑棋赢");alert.show();gameOver = true;return;}
4.和局
if(count == SIZE * SIZE) {//定义消息提示框Alert alert = new Alert(AlertType.INFORMATION);//定义消息框的弹出位置(从本窗体)alert.initOwner(this);//设置标题alert.setTitle("对战结果:");//设置弹出内容alert.setContentText("和棋");//显示弹出框alert.show();//和局也代表游戏结束gameOver = true;}
