【问题标题】:Can't move pieces properly with mousePressed无法使用 mousePressed 正确移动棋子
【发布时间】:2021-08-22 14:34:31
【问题描述】:

如果我这样做,它只能工作一次,我不能做其他动作,我知道错误都在 mousePressed 函数中,但我无法解决它: 问题具体在这里:

public void mousePressed(MouseEvent me) {
    if(foi==false) {
        posxmouse = me.getX()/100;
        posymouse = me.getY()/100;
        foi = true;
    }
    if(foi==true) {
        posx1mouse = me.getX()/100;
        posy1mouse = me.getY()/100;
        System.out.println("posx: " + me.getX()/100);
        System.out.println("posy: " + me.getY()/100);
        board = moves.MajorMovePawn(board, posymouse, posxmouse, posy1mouse, posx1mouse);
    }

但这是完整的代码,我希望你们能解决这样一个如此简单的问题。 我是巴西人,“foi”这个词的意思是“完成”,我用它来捕捉鼠标的两个坐标并移动一块,然后排除该块原来的位置。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 *
 * @author Pedro Maxx
 */
public class Game extends JPanel implements MouseListener {
    public Moves moves = new Moves();
    public String[][] initialboard = { 
            { "TB", "HB", "BB", "KB", "QB", "BB", "HB", "TB" },
            { "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB" }, 
            { "V", "V", "V", "V", "V", "V", "V", "V" },
            { "V", "V", "V", "V", "V", "V", "V", "V" }, 
            { "V", "V", "V", "V", "V", "V", "V", "V" },
            { "V", "V", "V", "V", "V", "V", "V", "V" }, 
            { "PW", "PW", "PW", "PW", "PW", "PW", "PW", "PW" },
            { "TW", "HW", "BW", "KW", "QW", "BW", "HW", "TW" }, 
        };
    public boolean foi, move = false;
    public static boolean vezW = true, vezB = false, done;
    public boolean obst = false;
    public int posx, posy, posx1, posy1;
    public String[][] board = new String[8][8];
    public ImageIcon pawnB = new ImageIcon("ChessJava//PawnBlack.png"),
            pawnW = new ImageIcon("ChessJava//PawnWhite.png"), towerB = new ImageIcon("ChessJava//TowerBlack.png"),
            towerW = new ImageIcon("ChessJava//TowerWhite.png"), horseB = new ImageIcon("ChessJava//HorseBlack.png"),
            horseW = new ImageIcon("ChessJava//HorseWhite.png"), bishopB = new ImageIcon("ChessJava//BishopBlack.png"),
            bishopW = new ImageIcon("ChessJava//BishopWhite.png"), queenB = new ImageIcon("ChessJava//QueenBlack.png"),
            queenW = new ImageIcon("ChessJava//QueenWhite.png"), kingB = new ImageIcon("ChessJava//KingBlack.png"),
            kingw = new ImageIcon("ChessJava//KingWhite.png");
    public Image imgPawnB = pawnB.getImage(), imgPawnW = pawnW.getImage(), imgTowerB = towerB.getImage(),
            imgTowerW = towerW.getImage(), imgHorseB = horseB.getImage(), imgHorseW = horseW.getImage(),
            imgBishopB = bishopB.getImage(), imgBishopW = bishopW.getImage(), imgQueenB = queenB.getImage(),
            imgQueenW = queenW.getImage(), imgKingB = kingB.getImage(), imgKingW = kingw.getImage();
    public int movesPawn2 = 2, movesPawn1 = 1, posxmouse = 0, posymouse = 0, posx1mouse = 0, posy1mouse = 0;;

    public Game() {
        setFocusable(true);
        setPreferredSize(new Dimension(800, 800));
        addMouseListener(this);
        setInicio();
    }

    public void setInicio() {
        for (int conti = 0; conti < 8; conti++) {
            for (int contij = 0; contij < 8; contij++) {
                board[conti][contij] = initialboard[conti][contij];
            }
        }
    }

    public void paintComponent(Graphics g) {
        Graphics2D grafico = (Graphics2D) g;
        super.paintComponent(g);
        //Cria o tabuleiro: 
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if ((i + j) % 2 == 0) {
                    g.setColor(Color.white);
                } else {
                    g.setColor(Color.GREEN);
                }
                grafico.fillRect(j * 100, i * 100, 100, 100);
            }
        }
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j].equals("PB")) {
                    grafico.drawImage(imgPawnB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("PW")) {
                    grafico.drawImage(imgPawnW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("BB")) {
                    grafico.drawImage(imgBishopB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("BW")) {
                    grafico.drawImage(imgBishopW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("TB")) {
                    grafico.drawImage(imgTowerB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("TW")) {
                    grafico.drawImage(imgTowerW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("HB")) {
                    grafico.drawImage(imgHorseB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("HW")) {
                    grafico.drawImage(imgHorseW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("QB")) {
                    grafico.drawImage(imgQueenB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("QW")) {
                    grafico.drawImage(imgQueenW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("KB")) {
                    grafico.drawImage(imgKingB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("KW")) {
                    grafico.drawImage(imgKingW, (j * 100), (i * 100 + 10), null);
                }
            }
        }
        repaint();
    }

    @Override
    public void mousePressed(MouseEvent me) {
        if (foi == false) {
            posxmouse = me.getX() / 100;
            posymouse = me.getY() / 100;
            foi = true;
        }
        if (foi == true) {
            posx1mouse = me.getX() / 100;
            posy1mouse = me.getY() / 100;
            System.out.println("posx: " + me.getX() / 100);
            System.out.println("posy: " + me.getY() / 100);
            board = moves.MajorMovePawn(board, posymouse, posxmouse, posy1mouse, posx1mouse);
        }
    }

    @Override
    public void mouseReleased(MouseEvent me) {
    }

    @Override
    public void mouseClicked(MouseEvent me) {
    }

    @Override
    public void mouseEntered(MouseEvent me) {
    }

    @Override
    public void mouseExited(MouseEvent me) {
    }

    public String testPiece(int posypiece, int posxpiece) {
        String piece = "";
        // Testar se é um peão branco
        if (board[posypiece][posxpiece].equals("PW")) {
            piece = "PW";
            System.out.println("É um peão branco!");
        }
        // Testar se é um peão preto: 
        if (board[posypiece][posxpiece].equals("PB")) {
            piece = "PB";
            System.out.println("É um peão preto!");
        }
        return piece;
    }

    public boolean movePawnWhite(int posypawn, int posxpawn, int posypawn1, int posxpawn1) {
        boolean pode = true;
        if (testPiece(posypawn, posxpawn).equals("PW")) {
            if (!board[posypawn - 1][posxpawn].equals("V")) {
                pode = false;
            }
            if (!board[posypawn - 2][posxpawn].equals("V")) {
                pode = false;
            }
        }
        return pode;
    }
}

老实说,我认为 Moves 类没有问题:

public class Moves {
    public int boardaux[][] = new int[8][8];

    public String[][] MajorMovePawn(String board[][], int posy, int posx, int posy1, int posx1) {
        String[][] boardFinal = board;
        if(boardFinal[posy][posx].equals("PW")) {
            System.out.println(board[posy][posx]);
            if(board[posy1][posx1].equals("V")) {
                boardFinal[posy1][posx1] = "PW";
                boardFinal[posy][posx] = "V";
            }
        }
        return boardFinal;
    }
}

【问题讨论】:

  • 请格式化您的代码以便于阅读。例如,一行中不需要超过 1 个空行。无需使代码比需要的更难阅读。
  • 我今天冒昧地为你格式化了你的代码,但同样,在未来,请先自己做。
  • 我已经这样做了。如果您没有很快得到很好的答案,那么您的下一步应该是将此代码缩减到编译、运行和演示您的问题的最低限度,minimal reproducible example(请阅读链接)。同样,在向志愿者提问时,让问题尽可能容易回答对您是有益的。
  • 另外,关于第一次来这里,欢迎来到 Stack Overflow。我邀请(或者更确切地说敦促)您阅读help center 链接,尤其是How to Ask 小节,它将解释本网站的工作原理以及它与其他网站的不同之处。

标签: java swing mouselistener chess


【解决方案1】:

你曾在哪里将 foi 重新设置为 true?如果它从不重置,您的逻辑将无法正常工作。你需要这样的东西:

@Override
public void mousePressed(MouseEvent me) {
    if (!foi) {
        posxmouse = me.getX() / 100;
        posymouse = me.getY() / 100;
        foi = true;
    } else {
        posx1mouse = me.getX() / 100;
        posy1mouse = me.getY() / 100;
        board = moves.MajorMovePawn(board, posymouse, posxmouse, posy1mouse, posx1mouse);
        foi = false;
    }
}

else 是这里的关键。

还有其他问题需要修复

旁注:我们没有人可以运行您的代码,因为我们没有图像。将来,使用您的程序创建并发布有效的Minimal, Reproducible Example。这是我的,我删除了你的图片:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import javax.swing.*;

/**
 *
 * @author Pedro Maxx
 */
public class Game extends JPanel implements MouseListener {
    private static final Font PIECE_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 40);
    public Moves moves = new Moves();
    public String[][] initialboard = { { "TB", "HB", "BB", "KB", "QB", "BB", "HB", "TB" },
            { "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB" }, { "V", "V", "V", "V", "V", "V", "V", "V" },
            { "V", "V", "V", "V", "V", "V", "V", "V" }, { "V", "V", "V", "V", "V", "V", "V", "V" },
            { "V", "V", "V", "V", "V", "V", "V", "V" }, { "PW", "PW", "PW", "PW", "PW", "PW", "PW", "PW" },
            { "TW", "HW", "BW", "KW", "QW", "BW", "HW", "TW" }, };
    public boolean foi, move = false;
    public static boolean vezW = true, vezB = false, done;
    public boolean obst = false;
    public int posx, posy, posx1, posy1;
    public String[][] board = new String[8][8];
    public int movesPawn2 = 2, movesPawn1 = 1, posxmouse = 0, posymouse = 0, posx1mouse = 0, posy1mouse = 0;
    private Image imgPawnB = createImage("P", Color.BLACK);
    private Image imgPawnW = createImage("P", Color.LIGHT_GRAY);
    private Image imgBishopB = createImage("B", Color.BLACK);
    private Image imgBishopW = createImage("B", Color.LIGHT_GRAY);
    private Image imgTowerB = createImage("R", Color.BLACK);
    private Image imgTowerW = createImage("R", Color.LIGHT_GRAY);
    private Image imgHorseB = createImage("N", Color.BLACK);
    private Image imgHorseW = createImage("N", Color.LIGHT_GRAY);
    private Image imgQueenB = createImage("Q", Color.BLACK);
    private Image imgQueenW = createImage("Q", Color.LIGHT_GRAY);
    private Image imgKingB = createImage("K", Color.BLACK);
    private Image imgKingW = createImage("K", Color.LIGHT_GRAY);

    public Game() {
        setFocusable(true);
        setPreferredSize(new Dimension(800, 800));
        addMouseListener(this);
        setInicio();
    }

    private Image createImage(String txt, Color color) {
        BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setFont(PIECE_FONT);
        g2.setColor(color);
        g2.drawString(txt, 20, 60);
        g2.dispose();
        return img;
    }

    public void setInicio() {
        for (int conti = 0; conti < 8; conti++) {
            for (int contij = 0; contij < 8; contij++) {
                board[conti][contij] = initialboard[conti][contij];
            }
        }
    }

    public void paintComponent(Graphics g) {
        Graphics2D grafico = (Graphics2D) g;
        super.paintComponent(g);
        // Cria o tabuleiro:
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if ((i + j) % 2 == 0) {
                    g.setColor(Color.white);
                } else {
                    g.setColor(Color.GREEN);
                }
                grafico.fillRect(j * 100, i * 100, 100, 100);
            }
        }
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j].equals("PB")) {
                    grafico.drawImage(imgPawnB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("PW")) {
                    grafico.drawImage(imgPawnW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("BB")) {
                    grafico.drawImage(imgBishopB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("BW")) {
                    grafico.drawImage(imgBishopW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("TB")) {
                    grafico.drawImage(imgTowerB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("TW")) {
                    grafico.drawImage(imgTowerW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("HB")) {
                    grafico.drawImage(imgHorseB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("HW")) {
                    grafico.drawImage(imgHorseW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("QB")) {
                    grafico.drawImage(imgQueenB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("QW")) {
                    grafico.drawImage(imgQueenW, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("KB")) {
                    grafico.drawImage(imgKingB, (j * 100), (i * 100 + 10), null);
                }
                if (board[i][j].equals("KW")) {
                    grafico.drawImage(imgKingW, (j * 100), (i * 100 + 10), null);
                }
            }
        }
        repaint();
    }

    @Override
    public void mousePressed(MouseEvent me) {
        System.out.println("foi: " + (foi));
        if (!foi) {
            posxmouse = me.getX() / 100;
            posymouse = me.getY() / 100;
            foi = true;
        } else if (foi) {
            posx1mouse = me.getX() / 100;
            posy1mouse = me.getY() / 100;
            System.out.println("posx: " + me.getX() / 100);
            System.out.println("posy: " + me.getY() / 100);
            board = moves.MajorMovePawn(board, posymouse, posxmouse, posy1mouse, posx1mouse);
            foi = false;
        }
    }

    @Override
    public void mouseReleased(MouseEvent me) {
    }

    @Override
    public void mouseClicked(MouseEvent me) {
    }

    @Override
    public void mouseEntered(MouseEvent me) {
    }

    @Override
    public void mouseExited(MouseEvent me) {
    }

    public String testPiece(int posypiece, int posxpiece) {
        String piece = "";
        // Testar se é um peão branco
        if (board[posypiece][posxpiece].equals("PW")) {
            piece = "PW";
            System.out.println("É um peão branco!");
        }
        // Testar se é um peão preto:
        if (board[posypiece][posxpiece].equals("PB")) {
            piece = "PB";
            System.out.println("É um peão preto!");
        }
        return piece;
    }

    public boolean movePawnWhite(int posypawn, int posxpawn, int posypawn1, int posxpawn1) {
        boolean pode = true;
        if (testPiece(posypawn, posxpawn).equals("PW")) {
            if (!board[posypawn - 1][posxpawn].equals("V")) {
                pode = false;
            }
            if (!board[posypawn - 2][posxpawn].equals("V")) {
                pode = false;
            }
        }
        return pode;
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Game game = new Game();
            frame.add(game);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

class Moves {
    public int boardaux[][] = new int[8][8];

    public String[][] MajorMovePawn(String board[][], int posy, int posx, int posy1, int posx1) {
        String[][] boardFinal = board;
        if(boardFinal[posy][posx].equals("PW")) {
            System.out.println(board[posy][posx]);
            if(board[posy1][posx1].equals("V")) {
                boardFinal[posy1][posx1] = "PW";
                boardFinal[posy][posx] = "V";
            }
        }
        return boardFinal;
    }
}

旁注2:

我会重新编写这个程序,将程序逻辑放在非 GUI 类中,并使 GUI 尽可能“愚蠢”,因为所有程序逻辑都在其中并添加到非 GUI 模型代码中,基本上是为了将“模型”与“视图”分开,因为这将允许更容易地测试和改进模型(非 GUI 逻辑)。我还会为每个方块使用 JPanel,并将我的 ImageIcons 放入 JLabels 中,以便在面板之间移动。

【讨论】:

  • 我的朋友,我无法用言语来形容我对你的回答感到多么高兴,真的,就是这样,你在我的脑海中打开了一个新世界,我会试着用非语言改进我的逻辑GUI,并遵循其他回答我的成员的建议,我还将研究如何诊断问题以及如何使用调试器(我直到现在才知道调试是如何工作的),所以,我真的很高兴,我祝您有美好的一天,即使在这些大流行常规和隔离的混乱时期,至少在我的国家巴西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多