示例#1
1
  /**
   * 实现对认输的处理
   *
   * @param dis
   */
  @SuppressWarnings("deprecation")
  public void giveUpAnswer(DataInputStream dis) {
    try {
      boolean isplayer1 = dis.readBoolean();
      boolean isplayer2 = dis.readBoolean();
      cb.changeColor = true;
      cb.canPlay = false;
      v.play("end");
      t.suspend();
      rp.ready.setText("准备");
      rp.isReady = false;
      if (isplayer1 == true && isplayer2 == false) {
        JOptionPane.showMessageDialog(cb, "黑方已经认输,白方胜");
        cb.message = "黑方已经认输,白方胜";
        cb.whiteWin++;
      }
      if (isplayer2 == true && isplayer1 == false) {
        JOptionPane.showMessageDialog(cb, "白方已经认输,黑方胜");
        cb.message = "白方已经认输,黑方胜";
        cb.blackWin++;
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#2
1
 /** 实现对求和的处理 */
 @SuppressWarnings("deprecation")
 public void drawAnswer() {
   if (answer == 0) {
     cb.message = "双方言和,平局!";
     cb.changeColor = true;
     cb.canPlay = false;
     cb.su.update(0, 0, HallPlayerPanel.nickname);
     rp.ready.setText("准备");
     rp.isReady = false;
     t.suspend();
     v.play("end");
     JOptionPane.showMessageDialog(cb, "对方同意了你的求和!");
   }
   if (answer != 0) {
     JOptionPane.showMessageDialog(cb, "对方拒绝了你的请求!");
   }
   answer = 3;
 }
示例#3
0
  /**
   * This code takes a board input where the upper left is (1,1) and the lower right is (8,8). It
   * then displays the board and gives the queens using those coordinates. The calculations are done
   * as if the upper left is (0,0) and the lower right is (7,7)
   */
  public static void EightQueens(int a, int b) {
    ChessBoard temp = new ChessBoard();
    temp.copy(board);

    if (board.getSpace(a, b) == " ") {
      if (board.queenAmount() != 8) {
        board.placeQueen(a, b); // place queen
        for (int i = 0; i < 8; i++)
          for (int j = 0; j < 8; j++) {
            // count++; //for checking total calculations
            if (board.getSpace(i, j) != " ") {
            } // System.out.println( "cannot place queen at ("+i+","+j+")");
            else EightQueens(i, j);
          }
        if (board.queenAmount() != 8) board.copy(temp); // retrace steps to the most previous bord
      }
    }

    /**
     * The next two sections of code change the solutions from a (0,0-7,7) scale to the "Layman's
     * scale" of (1,1-8,8)
     */
    if (board.queenAmount() == 8)
      System.out.println("Queen location: (" + (a + 1) + "," + (b + 1) + ")");

    if (m == a && b == n) {
      System.out.println("Initial placement (" + (a + 1) + "," + (b + 1) + ")");
      // the next line shows the amount of computations the program took to calculate the solution
      // total+=count;
      board.display();
    }
  }
示例#4
0
  /**
   * This methods does calculations using a chessboard as if the upper left corner was (0,0) and the
   * lower right corner was (7,7). It then displays the board and the queen locations using standard
   * chessboard identifications.
   */
  public static void letterEightQueens(int a, int b) {
    ChessBoard temp = new ChessBoard(nByn);
    temp.copy(board);

    if (board.getSpace(a, b) == " ") {
      if (board.queenAmount() != nByn) {
        board.placeQueen(a, b); // place queen
        for (int i = 0; i < nByn; i++)
          for (int j = 0; j < nByn; j++) {
            // count++; //for checking total calculations
            if (board.getSpace(i, j) != " ") {
            } // System.out.println( "cannot place queen at ("+i+","+j+")");
            else letterEightQueens(i, j);
          }
        if (board.queenAmount() != nByn)
          board.copy(temp); // retrace steps to the most previous bord
      }
    }

    /**
     * The next two sections of code change the integer solutions to the character solution, namely,
     * converts from a (0,0-7,7) scale to an (a1-h8) scale
     */
    if (board.queenAmount() == nByn) // if there are 8 queens on the board
    System.out.println("Queen location: " + (char) (b + 97) + (nByn - a));

    if (m == a && b == n) {
      System.out.println("Initial placement " + (char) (b + 97) + (nByn - a));
      // the next line shows the amount of computations the program took to calculate the solution
      // total+=count;
      board.display();
    }
  }
示例#5
0
 public static void main(String[] args) {
   /**
    * Computing ALL computations for 8x8 takes 26,360,768 computations g1, or (8,7) takes the
    * longest; 2,503,040 a3, or (6,1) takes the shortest: 512 Average: 411,887
    */
   try {
     if (args[0].charAt(0) == '0') mutatedChessBoard();
     else if (args[0].length() == 1) { // these lines read coordings from (1,1) to (8,8)
       m = Integer.parseInt(args[0]) - 1; // converts the string to a 0-7 int scale for row
       n = Integer.parseInt(args[1]) - 1; // converts the string to a 0-7 int scale for column
       EightQueens(m, n);
     } else {
       // these lines are for reading from a chess board; ie, a1-h8
       n = (int) args[0].charAt(0) - 97; // converts the character to the column coordinate
       m =
           ((int) args[0].charAt(1) - 49 - (nByn - 1))
               * (-1); // converts the character to the row coordinate
       // m=((int)args[0].charAt(1)-49-7)*(-1);
       letterEightQueens(m, n);
     }
   } catch (Exception ex) {
     System.out.println(ex.getMessage());
     board.display();
     System.out.println("That is not a spot on the chessboard.");
     System.out.println("Chessboard locations: ");
     board.letterBoard();
     System.out.println("\nLayman's terms: ");
     board.coordinateBoard();
   }
 }
示例#6
0
  static boolean solve(int numQueens, int whichCol) {
    // Bottom-out condition 1:
    if (numQueens == 0) {
      // None to assign - done.
      return true;
    }

    // Bottom-out condition 2:
    if (whichCol >= board.size()) {
      // No columns left to try: done.
      return false;
    }

    // Try every un-forbidden spot in each row.
    for (int row = 0; row < board.size(); row++) {
      if (!board.isForbidden(row, whichCol)) {

        // Try this location.
        board.addQueen(row, whichCol);

        boolean solutionExists = solve(numQueens - 1, whichCol + 1);

        if (solutionExists) {
          return true;
        }

        // Else, un-do
        board.removeQueen(row, whichCol);
      }
    }

    // Couldn't find a solution.
    return false;
  }
 static void uncastleRight() {
   chessBoard.set(7, 5, " ");
   chessBoard.set(7, 6, " ");
   chessBoard.set(7, 7, "R");
   chessBoard.set(7, 4, "A");
   kingCMoved = false;
   rook63Moved = false;
 }
 static void castleLeft() {
   chessBoard.set(7, 2, "A");
   chessBoard.set(7, 3, "R");
   chessBoard.set(7, 0, " ");
   chessBoard.set(7, 4, " ");
   kingCMoved = true;
   rook56Moved = true;
 }
  public void initialize(int populationSize, int sizeOfTheBoard) {

    populationSize += (populationSize % 4 != 0) ? 4 - populationSize % 4 : 0;

    for (int i = 0; i < populationSize; i++) {
      ChessBoard chessBoard = new ChessBoard(sizeOfTheBoard);
      chessBoard.configureWithRandomizeDNA();
      currentPopulation.add(chessBoard);
    }
  }
示例#10
0
 @Test
 public final void testCastling7() {
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.WHITE), 7, 4);
   mainboard.set(new Rook(Player.WHITE), 7, 7);
   mainboard.set(new Rook(Player.WHITE), 7, 0);
   mainboard.set(new Queen(Player.WHITE), 7, 5);
   assertFalse(mainmodel.isValidMove(new Move(7, 4, 7, 6), mainboard));
 }
示例#11
0
 @Test
 public final void testCastling5() {
   // make sure can't be done if piece is in the way
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.BLACK), 0, 4);
   mainboard.set(new Rook(Player.BLACK), 0, 7);
   mainboard.set(new Knight(Player.BLACK), 0, 6);
   move1 = new Move(0, 4, 0, 6);
   assertFalse(mainmodel.isValidMove(move1, mainboard));
 }
示例#12
0
 @Test
 public final void testCastling0() {
   // make sure it can be done
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.BLACK), 0, 4);
   mainboard.set(new Rook(Player.BLACK), 0, 7);
   mainboard.set(new Queen(Player.WHITE), 1, 4);
   move1 = new Move(0, 4, 0, 6);
   mainmodel.setTurns(1);
   assertFalse(mainmodel.isValidMove(move1, mainboard));
 }
示例#13
0
 @Test
 public final void testCastling9() {
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.WHITE), 7, 4);
   mainboard.set(new Rook(Player.WHITE), 7, 7);
   mainboard.set(new Rook(Player.WHITE), 7, 0);
   assertTrue(mainmodel.isValidMove(new Move(7, 4, 7, 2), mainboard));
   mainmodel.move(new Move(7, 4, 7, 2), mainboard);
   assertNotNull(mainmodel.pieceAt(mainboard, 7, 2));
   assertNotNull(mainmodel.pieceAt(mainboard, 7, 3));
 }
示例#14
0
 @Test
 public final void testCastling1() {
   // make sure it can be done
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.BLACK), 0, 4);
   mainboard.set(new Rook(Player.BLACK), 0, 7);
   // castle now
   move1 = new Move(0, 4, 0, 6);
   mainmodel.move(move1, mainboard);
   assertEquals(mainboard.pieceAt(0, 6).type(), "King");
   assertEquals(mainboard.pieceAt(0, 5).type(), "Rook");
 }
示例#15
0
 @Test
 public final void testCastling11() {
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.BLACK), 0, 4);
   mainboard.set(new Rook(Player.BLACK), 0, 7);
   mainboard.set(new Rook(Player.BLACK), 0, 0);
   mainmodel.setTurns(1); // so its black's turn
   assertTrue(mainmodel.isValidMove(new Move(0, 4, 0, 2), mainboard));
   mainmodel.move(new Move(0, 4, 0, 2), mainboard);
   assertNotNull(mainmodel.pieceAt(mainboard, 0, 2));
   assertNotNull(mainmodel.pieceAt(mainboard, 0, 3));
 }
示例#16
0
 @Test
 public final void testCastling2() {
   // make sure can't be done if rook moved
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.clearBoard();
   mainboard.set(new King(Player.BLACK), 0, 4);
   mainboard.set(new Rook(Player.BLACK), 0, 7);
   move1 = new Move(0, 7, 1, 7);
   mainmodel.move(move1, mainboard);
   move1 = new Move(1, 7, 0, 7);
   mainmodel.move(move1, mainboard);
   // castle now
   move1 = new Move(0, 4, 0, 6);
   assertFalse(mainmodel.isValidMove(move1, mainboard));
 }
示例#17
0
  public ChessMoves nextMoves(ChessBoard b) {
    // Initialize moves to 0
    ChessMoves moves;
    int i = this.getPosition().getRow();
    int j = this.getPosition().getCol();

    moves = new ChessMoves();
    try {
      for (int dy = -1; dy < 2; dy++) {
        for (int dx = -1; dx < 2; dx++) {
          int to_i = i + dy;
          int to_j = j + dx;
          if (!((dx == 0) && (dy == 0))
              && (to_i >= 0)
              && (to_i <= 7)
              && (to_j >= 0)
              && (to_j <= 7)) {
            ChessPosition pos = new ChessPosition(to_i, to_j);
            ChessPiece p = b.pieceAt(pos);
            if (p == null) moves.addMove(pos);
            else if (p.getColor() != this.getColor())
              moves.addMove(pos, ChessMoves.MoveType.CAPTURE);
          }
        }
      }

      // Check the King can castle

    } catch (Exception e) {
      // Since only valid positions are created, don't worry about exceptions
      moves = null;
    }

    return moves;
  }
示例#18
0
 private int examineMove(AbstractMove theMove, Player player, int depth, String position) {
   Player player2 = player.getOpponent();
   player2.findAllMoves(theMove.isCheck());
   int endPositionScore = getScoreForEndPosition(player2);
   if (endPositionScore != -1) {
     itsTable.add(position, endPositionScore);
     return endPositionScore;
   } else if (depth == 1) {
     int score = itsScorer.getScore(itsBoard, itsPlayer);
     itsTable.add(position, score);
     return score;
   } else {
     int bestScore = 1234;
     Collection moves = getAllMoves(player2);
     for (Iterator i = moves.iterator(); i.hasNext(); ) {
       AbstractMove move = (AbstractMove) i.next();
       move.getPiece().findMoves_safe();
       move = player2.movePiece(move);
       String newPosition = itsBoard.getPositionCode() + player2.getColor();
       int thisScore = -321;
       boolean hasIt = itsTable.has(newPosition);
       if (hasIt) {
         thisScore = itsTable.getScore();
       } else {
         thisScore = examineMove(move, player2, depth - 1, newPosition);
         itsTable.add(newPosition, thisScore);
       }
       bestScore = compareScores(player2, bestScore, thisScore);
       player2.reverseMove(move);
     }
     return bestScore;
   }
 }
 static int kingPositionC() {
   int kingPositionC = 0;
   while (!"A".equals(chessBoard.get(kingPositionC / 8, kingPositionC % 8))) {
     kingPositionC++;
   }
   return kingPositionC;
 }
 public static String posibleMoves() {
   String list = "";
   for (int i = 0; i < 64; i++) {
     switch (chessBoard.get(i / 8, i % 8)) {
       case "P":
         list += posibleP(i);
         break;
       case "R":
         list += posibleR(i);
         break;
       case "K":
         list += possibleKnight(i);
         break;
       case "B":
         list += posibleB(i);
         break;
       case "Q":
         list += posibleQ(i);
         break;
       case "A":
         list += possibleKing(i);
         break;
     }
   }
   return list; // x1,y1,x2,y2,captured piece
 }
示例#21
0
 public void init() throws Exception {
   table = ImageIO.read(new File("image/board.jpg"));
   black = ImageIO.read(new File("image/black.gif"));
   white = ImageIO.read(new File("image/white.gif"));
   selected = ImageIO.read(new File("image/selected.gif"));
   // 把每个元素赋为"╋",用于在控制台画出棋盘
   for (int i = 0; i < BOARD_SIZE; i++) {
     for (int j = 0; j < BOARD_SIZE; j++) {
       board[i][j] = "╋";
     }
   }
   chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HETGHT));
   chessBoard.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           // 将用户鼠标事件的座标转换成棋子数组的座标。
           int xPos = (int) ((e.getX() - X_OFFSET) / RATE);
           int yPos = (int) ((e.getY() - Y_OFFSET) / RATE);
           board[xPos][yPos] = "●";
           /*
           电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
           还涉及:
           1.如果下棋的点已经棋子,不能重复下棋。
           2.每次下棋后,需要扫描谁赢了
           */
           chessBoard.repaint();
         }
         // 当鼠标退出棋盘区后,复位选中点座标
         public void mouseExited(MouseEvent e) {
           selectedX = -1;
           selectedY = -1;
           chessBoard.repaint();
         }
       });
   chessBoard.addMouseMotionListener(
       new MouseMotionAdapter() {
         // 当鼠标移动时,改变选中点的座标
         public void mouseMoved(MouseEvent e) {
           selectedX = (e.getX() - X_OFFSET) / RATE;
           selectedY = (e.getY() - Y_OFFSET) / RATE;
           chessBoard.repaint();
         }
       });
   f.add(chessBoard);
   f.pack();
   f.setVisible(true);
 }
示例#22
0
 @Test
 public void testMove() {
   q_w.move(4, 0);
   assertTrue(q_w.getX() == 4 && q_w.getY() == 0);
   p1_b.move(6, 3);
   assertFalse(p1_b.getX() == 6 && p1_b.getY() == 3);
   board.print();
 }
示例#23
0
 public void drawPieces(Graphics g) {
   g.setColor(Color.red);
   for (int i = 0; i < 8; i++)
     for (int j = 0; j < 8; j++) {
       Piece piece = chessBoard.getPiece(i, j);
       if (piece != null) g.drawString(piece.toString(), i * 50, j * 50 + 10);
     }
 }
示例#24
0
 private int getScoreForEndPosition(Player player) {
   int returnValue = -1;
   if (player.isInStaleMate() || itsBoard.isThirdOccuranceOfPosition()) returnValue = 500;
   else if (player.isInCheckMate()) {
     if (player == itsPlayer) returnValue = 0;
     else returnValue = 1000;
   }
   return returnValue;
 }
示例#25
0
 @Test
 public final void testKing4() {
   // move the king right 2 spaces
   mainmodel = new ChessModel();
   mainboard = new ChessBoard();
   mainboard.set(new King(Player.BLACK), 2, 0);
   move1 = new Move(2, 0, 2, 2);
   assertFalse(mainmodel.isValidMove(move1, mainboard));
 }
示例#26
0
 public void search(ChessBoard board, Player player) {
   itsTable = new PositionHashTable();
   itsMoves.clear();
   itsPlayer = player;
   itsBoard = board;
   Collection moves = getAllMoves(player);
   for (Iterator i = moves.iterator(); i.hasNext(); ) {
     AbstractMove move = (AbstractMove) i.next();
     move.getPiece().findMoves_safe();
     move = player.movePiece(move);
     itsBoard.recordPosition();
     String positionCode = itsBoard.getPositionCode() + player.getColor();
     int score = examineMove(move, player, itsSearchQuality, positionCode);
     move.setScore(score);
     itsMoves.add(move);
     itsBoard.removeLastPosition();
     player.reverseMove(move);
   }
 }
示例#27
0
  public boolean Step(Position start, Position end) {
    int startRow = start.getNumber1();
    int startColumn = start.getNumber2();
    int endRow = end.getNumber1();
    int endColumn = end.getNumber2();
    if ((startRow == endRow || startColumn == endColumn)
        || (Math.abs(startRow - endRow) == Math.abs(endColumn - startColumn))) {
      if (startRow == endRow || startColumn == endColumn) {
        int diffPos = 0;
        if (startRow == endRow) {
          diffPos = startColumn < endColumn ? 1 : -1;
          for (int i = startColumn + 1; i < endColumn; i += diffPos) {
            if (ChessBoard.getFigure(startRow, i) != null) {
              return false;
            }
          }
        } else if (startColumn == endColumn) {
          diffPos = startRow < endRow ? 1 : -1;
          for (int i = startRow + 1; i < endRow; i += diffPos) {
            if (ChessBoard.getFigure(i, startColumn) != null) {
              return false;
            }
          }
        }
      } else if (Math.abs(startRow - endRow) == Math.abs(endColumn - startColumn)) {
        int diffPosNum1 = startRow < endRow ? 1 : -1;
        int diffPosNum2 = startColumn < endColumn ? 1 : -1;

        for (int i = startRow + 1, j = startColumn + 1;
            i < endRow;
            i += diffPosNum1, j += diffPosNum2) {
          if (ChessBoard.getFigure(i, j) != null) {
            return false;
          }
        }
      }

      if (ChessBoard.getFigure(endRow, endColumn) != null
          && ChessBoard.getFigure(endRow, endColumn).getColor() == this.getColor()) {
        return false;
      }
      ChessBoard.resetFigure(endRow, endColumn);
      System.out.println(
          "figure changed his position from ["
              + row
              + ","
              + column
              + "] to ["
              + endRow
              + ","
              + endColumn
              + "]");
      ChessBoard.setFigure(color, row, column);
      return true;
    }

    return false;
  }
 public static void undoMove(String move) {
   if (move.charAt(4) == 'E') { // enpassant left
     unEnpassantLeft(move);
   } else if (move.charAt(4) == 'N') { // enpassant right
     unEnpassantRight(move);
   } else if (move.charAt(4) == 'Z') {
     uncastleRight();
   } else if (move.charAt(4) == 'Y') {
     uncastleLeft();
   } else if (move.charAt(4) == 'P') {
     // if pawn promotion
     chessBoard.set(1, move.charAt(0), "P");
     chessBoard.set(0, move.charAt(1), String.valueOf(move.charAt(2)));
   } else {
     chessBoard.set(
         move.charAt(0), move.charAt(1), chessBoard.get(move.charAt(2), move.charAt(3)));
     chessBoard.set(move.charAt(2), move.charAt(3), String.valueOf(move.charAt(4)));
   }
 }
示例#29
0
 public void CheckRight(ChessBoard cel) {
   int r = cel.getRow();
   int c = cel.getColumn();
   if (c + 1 < 8 && cell[r][c + 1].state != ' ' && cell[r][c + 1].state != turn) {
     for (int i = c + 2; i < 8; i++) {
       if (cell[r][i].state == turn) {
         can = true;
         for (int j = c; j < i; j++) {
           cell[r][j].state = cel.state = turn;
           cell[r][j].repaint();
         }
         return;
       } else {
         if (cell[r][i].state == ' ') break;
         else continue;
       }
     }
   }
 }
示例#30
0
 public void CheckLeft(ChessBoard cel) {
   int r = cel.getRow();
   int c = cel.getColumn();
   if (c - 1 >= 0 && cell[r][c - 1].state != ' ' && cell[r][c - 1].state != turn) {
     for (int i = c - 2; i >= 0; i--) {
       if (cell[r][i].state == turn) {
         can = true;
         for (int j = i + 1; j <= c; j++) {
           cell[r][j].state = cel.state = turn;
           cell[r][j].repaint();
         }
         return;
       } else {
         if (cell[r][i].state == ' ') break;
         else continue;
       }
     }
   }
 }