1.重载判断重复棋子的方法,给方法添加color参数,旨在比较棋子的颜色

  1. private static boolean isExist(int x,int y,Color color) {
  2. //循环棋子数组(判断连续棋子是否是同色棋子)
  3. int lenth = chesses.length;
  4. for(int i = 0; i < lenth; i ++) {
  5. Chess chess = chesses[i];
  6. if(chess != null) {
  7. if(x == chess.getX() && y == chess.getY() && chess.getColor().equals(color)) {
  8. return true;
  9. }
  10. }
  11. }
  12. return false;
  13. }

2.根据当前棋子的坐标进行检索,看相邻位置是否有棋子,方向分为 向左、向右、向上、向下、右上左下、左上右下,如果大于等于5颗,则胜利

  1. private static boolean isWin(Chess chess) {
  2. //默认有一颗
  3. int count = 1;
  4. int x = chess.getX();
  5. int y = chess.getY();
  6. //先向左判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环
  7. for(int i = x - 1; i >= 0 && i >= x - 4; i --) {
  8. if(isExist(i, y, chess.getColor())) {
  9. count ++;
  10. }else {
  11. break;
  12. }
  13. }
  14. if(count >=5) {
  15. return true;
  16. }
  17. //其他方向同理
  18. //此为斜向例子
  19. count = 1;
  20. //先向右上判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环
  21. for(int i = x + 1, j = y - 1;
  22. i < SIZE && i <= x + 4 && j >= 0 && j >= y -4;
  23. i ++,j --) {
  24. if(isExist(i, j, chess.getColor())) {
  25. count ++;
  26. }else {
  27. break;
  28. }
  29. }
  30. //再向左下判断有没有相同颜色的棋子,如果有count++ ,否则就退出循环
  31. for(int i = x - 1,j = y + 1;
  32. i >= 0 && i >= x - 4 && j < SIZE && j <= y + 4;
  33. i --,j ++) {
  34. if(isExist(i, j, chess.getColor())) {
  35. count ++;
  36. }else {
  37. break;
  38. }
  39. }
  40. if(count >=5) {
  41. return true;
  42. }

3.弹出胜利提示框,停止下棋

  1. //点击事件添加,用于停止游戏
  2. if (gameOver) {
  3. return;
  4. }
  5. //胜利
  6. if(isWin(chess)) {
  7. Alert alert = new Alert(AlertType.INFORMATION);
  8. alert.initOwner(this);
  9. alert.setTitle("对战结果:");
  10. alert.setContentText(isBlack ? "白棋赢" : "黑棋赢");
  11. alert.show();
  12. gameOver = true;
  13. return;
  14. }

4.和局

  1. if(count == SIZE * SIZE) {
  2. //定义消息提示框
  3. Alert alert = new Alert(AlertType.INFORMATION);
  4. //定义消息框的弹出位置(从本窗体)
  5. alert.initOwner(this);
  6. //设置标题
  7. alert.setTitle("对战结果:");
  8. //设置弹出内容
  9. alert.setContentText("和棋");
  10. //显示弹出框
  11. alert.show();
  12. //和局也代表游戏结束
  13. gameOver = true;
  14. }