Java Chess,如何更新棋盘?

标签 java swing user-interface matrix jpanel

我正在用 Java 制作国际象棋,现在,每当用户单击移动棋子时,我都会遇到更新棋盘的问题。我的游戏逻辑还远远没有完成,我只是想让 GUI 和 mouseListener 首先按照我希望的方式工作。我设计程序的方式是,棋子的位置全部存储在 8 x 8 字符串矩阵中。 64 由 64 个 JPanel 组成。每次用户单击移动棋子时,字符串矩阵都应该更新,并且 GUI 应该读取矩阵并相应更新。现在,矩阵正在更新,但 GUI 尚未更新。我不知道为什么会发生这种情况,也不知道如何解决它,有人可以帮助我吗?这是我的代码:

public class Chess extends JFrame implements MouseListener {
    private static final long serialVersionUID = 1L;

    private final BufferedImage whitePawnGUI = ImageIO.read(new File("img/WhitePawn.png"));
    private final BufferedImage whiteKnightGUI = ImageIO.read(new File("img/WhiteKnight.png"));
    private final BufferedImage whiteBishopGUI = ImageIO.read(new File("img/WhiteBishop.png"));
    private final BufferedImage whiteRookGUI = ImageIO.read(new File("img/WhiteRook.png"));
    private final BufferedImage whiteQueenGUI = ImageIO.read(new File("img/WhiteQueen.png"));
    private final BufferedImage whiteKingGUI = ImageIO.read(new File("img/WhiteKing.png"));
    private final BufferedImage blackPawnGUI = ImageIO.read(new File("img/BlackPawn.png"));
    private final BufferedImage blackKnightGUI = ImageIO.read(new File("img/BlackKnight.png"));
    private final BufferedImage blackBishopGUI = ImageIO.read(new File("img/BlackBishop.png"));
    private final BufferedImage blackRookGUI = ImageIO.read(new File("img/BlackRook.png"));
    private final BufferedImage blackQueenGUI = ImageIO.read(new File("img/BlackQueen.png"));
    private final BufferedImage blackKingGUI = ImageIO.read(new File("img/BlackKing.png"));

    private String[][] piecePositions = new String[8][8];
    private JPanel[][] boardTiles = new JPanel[8][8];
    private String lastSelected = "";
    private int lastSelectedRow = 0;
    private int lastSelectedCol = 0;

    public Chess() throws IOException {
        setTitle("Chess");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(true);
        setLayout(new BorderLayout());
        getContentPane().setBackground(Color.white);

        // white pieces
        piecePositions[6][0] = "wp";
        piecePositions[6][1] = "wp";
        piecePositions[6][2] = "wp";
        piecePositions[6][3] = "wp";
        piecePositions[6][4] = "wp";
        piecePositions[6][5] = "wp";
        piecePositions[6][6] = "wp";
        piecePositions[6][7] = "wp";

        piecePositions[7][1] = "wn";
        piecePositions[7][6] = "wn";

        piecePositions[7][2] = "wb";
        piecePositions[7][5] = "wb";

        piecePositions[7][0] = "wr";
        piecePositions[7][7] = "wr";

        piecePositions[7][3] = "wq";
        piecePositions[7][4] = "wk";

        // black pieces
        piecePositions[1][0] = "bp";
        piecePositions[1][1] = "bp";
        piecePositions[1][2] = "bp";
        piecePositions[1][3] = "bp";
        piecePositions[1][4] = "bp";
        piecePositions[1][5] = "bp";
        piecePositions[1][6] = "bp";
        piecePositions[1][7] = "bp";

        piecePositions[0][1] = "bn";
        piecePositions[0][6] = "bn";

        piecePositions[0][2] = "bb";
        piecePositions[0][5] = "bb";

        piecePositions[0][0] = "br";
        piecePositions[0][7] = "br";

        piecePositions[0][3] = "bq";
        piecePositions[0][4] = "bk";

        System.out.println(printChessBoard(piecePositions));

        for (int row = 0; row < boardTiles.length; row++) {
            for (int col = 0; col < boardTiles[row].length; col++) {
                boardTiles[row][col] = new JPanel() {
                    private static final long serialVersionUID = 1L;

                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        Graphics2D g2d = (Graphics2D) g;
                        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                }
            };
            if (row % 2 == 0) {
                if (col % 2 == 0) {
                    boardTiles[row][col].setBackground(new Color(240, 217, 181)); // light
                                                                                    // brown
                } else if (col % 2 != 0) {
                    boardTiles[row][col].setBackground(new Color(181, 136, 99)); // dark
                                                                                    // brown
                }
            } else if (row % 2 != 0) {
                if (col % 2 != 0) {
                    boardTiles[row][col].setBackground(new Color(240, 217, 181)); // light
                                                                                    // brown
                } else if (col % 2 == 0) {
                    boardTiles[row][col].setBackground(new Color(181, 136, 99)); // dark
                                                                                    // brown
                }
            }
            boardTiles[row][col].setLayout(new BorderLayout());
            final int tempRow = row;
            final int tempCol = col;
            boardTiles[row][col].addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    System.out.println("row : " + tempRow + ", col: " + tempCol);
                    if (piecePositions[tempRow][tempCol] == "wp") {
                        System.out.println("White pawn");
                        lastSelected = "wp";
                    } else if (piecePositions[tempRow][tempCol] == "wn") {
                        System.out.println("White knight");
                        lastSelected = "wn";
                    } else if (piecePositions[tempRow][tempCol] == "wb") {
                        System.out.println("White bishop");
                        lastSelected = "wb";
                    } else if (piecePositions[tempRow][tempCol] == "wr") {
                        System.out.println("White rook");
                        lastSelected = "wr";
                    } else if (piecePositions[tempRow][tempCol] == "wq") {
                        System.out.println("White queen");
                        lastSelected = "wq";
                    } else if (piecePositions[tempRow][tempCol] == "wk") {
                        System.out.println("White king");
                        lastSelected = "wk";
                    } else if (piecePositions[tempRow][tempCol] == "bp") {
                        System.out.println("Black pawn");
                        lastSelected = "bp";
                    } else if (piecePositions[tempRow][tempCol] == "bn") {
                        System.out.println("Black knight");
                        lastSelected = "bn";
                    } else if (piecePositions[tempRow][tempCol] == "bb") {
                        System.out.println("Black bishop");
                        lastSelected = "bb";
                    } else if (piecePositions[tempRow][tempCol] == "br") {
                        System.out.println("Black rook");
                        lastSelected = "br";
                    } else if (piecePositions[tempRow][tempCol] == "bq") {
                        System.out.println("Black queen");
                        lastSelected = "bq";
                    } else if (piecePositions[tempRow][tempCol] == "bk") {
                        System.out.println("Black king");
                        lastSelected = "bk";
                    } else {
                        System.out.println("Blank tile");
                        if (lastSelected != null) {
                            piecePositions[lastSelectedRow][lastSelectedCol] = null;
                            piecePositions[tempRow][tempCol] = lastSelected;
                        }
                    }
                    lastSelectedRow = tempRow;
                    lastSelectedCol = tempCol;
                    System.out.println(printChessBoard(piecePositions));
                    boardTiles[tempRow][tempCol].setBackground(new Color(255, 255, 255, 127));
                    boardTiles[tempRow][tempCol].repaint();
                }
            });
            JLabel piecePicLabel = new JLabel();
            if (piecePositions[row][col] == "wp") {
                piecePicLabel = new JLabel(new ImageIcon(whitePawnGUI));
            } else if (piecePositions[row][col] == "wn") {
                piecePicLabel = new JLabel(new ImageIcon(whiteKnightGUI));
            } else if (piecePositions[row][col] == "wb") {
                piecePicLabel = new JLabel(new ImageIcon(whiteBishopGUI));
            } else if (piecePositions[row][col] == "wr") {
                piecePicLabel = new JLabel(new ImageIcon(whiteRookGUI));
            } else if (piecePositions[row][col] == "wq") {
                piecePicLabel = new JLabel(new ImageIcon(whiteQueenGUI));
            } else if (piecePositions[row][col] == "wk") {
                piecePicLabel = new JLabel(new ImageIcon(whiteKingGUI));
            } else if (piecePositions[row][col] == "bp") {
                piecePicLabel = new JLabel(new ImageIcon(blackPawnGUI));
            } else if (piecePositions[row][col] == "bn") {
                piecePicLabel = new JLabel(new ImageIcon(blackKnightGUI));
            } else if (piecePositions[row][col] == "bb") {
                piecePicLabel = new JLabel(new ImageIcon(blackBishopGUI));
            } else if (piecePositions[row][col] == "br") {
                piecePicLabel = new JLabel(new ImageIcon(blackRookGUI));
            } else if (piecePositions[row][col] == "bq") {
                piecePicLabel = new JLabel(new ImageIcon(blackQueenGUI));
            } else if (piecePositions[row][col] == "bk") {
                piecePicLabel = new JLabel(new ImageIcon(blackKingGUI));
            }
            boardTiles[row][col].add(piecePicLabel);
            boardTiles[row][col].repaint();
        }
    }

    JPanel basePanel = new JPanel() {
        private static final long serialVersionUID = 1L;

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g; 
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // draw the board
            g2d.drawRect(26, 0, 624, 624);
            for (int i = 0; i < 8; i++) {
                // numbers and letters labels
                g2d.setColor(Color.white);
                g2d.drawString("12345678".substring(i, i + 1), 10, i * 78 + 39);
                g2d.drawString("abcdefgh".substring(i, i + 1), i * 78 + 39 + 20, 640);
            }
        }
    };
    basePanel.setBackground(Color.black);
    basePanel.setLayout(new GridLayout(8, 8));
    basePanel.setPreferredSize(new Dimension(650, 650));
    for (int row = 0; row < boardTiles.length; row++) {
        for (int col = 0; col < boardTiles.length; col++) {
            basePanel.add(boardTiles[row][col]);
        }
    }

    getContentPane().add(basePanel);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                new Chess();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}

这是输出的图片:

Picture of chessboard

Picture of output to console

棋盘上的64个棋子每一个都是一个JPanel,棋子的图像都放在每个JPanel中。正如你所看到的,当我尝试移动 pawn 时,它在矩阵中移动,但不在 GUI 中移动。我该如何解决这个问题?

最佳答案

当您在矩阵内执行移动时,您实际上并未在图形板内执行移动 (JPanel[][])。

所以除其他外:

// ...
} else {
    System.out.println("Blank tile");
    if (lastSelected != null) {
        piecePositions[lastSelectedRow][lastSelectedCol] = null;
        piecePositions[tempRow][tempCol] = lastSelected;
        //
        // HERE you miss something I guess <<<<<<<<<<<<<<<<<<<<<
        // Do something with boardTiles...
    }
}
// ...

还有一点很重要:在比较字符串时切勿使用 ==!= ,否则您可能会遇到麻烦(将是恶性的)。相反,如果您害怕 null,请使用以下结构:

    if("bn".equals(piecePositions[row][col])) {
         // you avoid NullPointerException that way
    }

更重要的是,我们假设这是一些沙箱代码..否则它缺少很多东西:

  • 进行面向对象编程。至少定义 BoardPieceMove 类。它会让你的生活变得如此美好。
  • 同时尝试能够区分 GUI 代码和纯代码。您可以通过这种方式轻松调试您的应用,并且通常它必须可以在单元测试中进行测试,并且可以毫不费力地使用控制台输入/输出。
  • 清理你的代码,创建方法,快乐起来。

关于Java Chess,如何更新棋盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47230274/

相关文章:

apache - 如何从 Mac 上的命令行卸载 apache?

java - 插入后获取生成的id

java - jar从外部读取文件

java - 递归函数缺少返回语句

java - 当类具有多个不同的字段时,如何对其进行泛化?

swing - 在java中绘制缓冲图像的直方图

user-interface - 操作系统用户界面指南 : when to ignore?

android - 没有填充的自定义标题栏 (Android)

java - 限制 JScrollPane 仅显示其部分内容

java - 使用 Box Layout.X_AXIS 将 JButton 居中