0

If i do the code like this, it only works one time, i cant do other move and i know the error is all in the mousePressed function, but i can't solve it: The problem is specifically here:

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);
    }

But this is the fully code, and i hope you guys have the solution for a so simple problem like this. I'm brazilian, the word "foi" means something like "done", and i used it to catch the two coordinates of the mouse and move one piece and after exclude the position where the piece was originally.

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;
    }
}

Honestly, i think there's no issue with the Moves class:

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;
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Please format your code for easy readability. No need for more than 1 blank line in a row, for instance. No need to make code harder to read than needed. – Hovercraft Full Of Eels Aug 22 '21 at 14:45
  • I've taken the liberty of formatting your code for you today, but again, in the future, please do this first yourself. – Hovercraft Full Of Eels Aug 22 '21 at 14:50
  • its my first time in the stackoverflow and i'm kinda lost but ty for the advise – Pedro Martins Aug 22 '21 at 14:52
  • 1
    I have already done so. If you don't get a great answer soon, then your next step should be to cull this code down to the bare minimum that compiles, runs and demonstrates your problem, a [mre] (please read the link). Again, when asking questions of volunteers, it is beneficial to you to make the question as easy to answer as possible. – Hovercraft Full Of Eels Aug 22 '21 at 14:53
  • 1
    Also, regarding first time here, welcome to Stack Overflow. I invite (or rather *urge*) you to read the [help] links, especially the [ask] subsection that will explain how this site works and how it is different from other sites. – Hovercraft Full Of Eels Aug 22 '21 at 14:54
  • Please delete the self-disparaging comments, as they don't help you or us, and instead tell us information *in your question* as an [edit] that helps us to better understand your code and your problem. You want to focus on a clear and specific problem and question, again, one that is easier to answer. – Hovercraft Full Of Eels Aug 22 '21 at 15:00
  • Also, check out Jon Skeet's ["Stack Overflow question checklist"](http://meta.stackoverflow.com/q/260648) which can be useful when you want to write a good and well-received question. – Hovercraft Full Of Eels Aug 22 '21 at 15:02
  • 1
    Does this answer your question? [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – EJoshuaS - Stand with Ukraine Aug 22 '21 at 15:10
  • Where do you ever re-set foi back to true? If it is never reset, your logic won't work. You need: `if (!foi) {...... foi = true; } else {...... foi = false);` That `else` is important – Hovercraft Full Of Eels Aug 22 '21 at 15:23

1 Answers1

1

Where do you ever re-set foi back to true? If it is never reset, your logic won't work. You need something like:

@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;
    }
}

The else is key here.

There are other bugs that you still need to fix

Side note: none of us can run your code since we don't have the images. In the future, create and post a valid Minimal, Reproducible Example with your program. Here is mine, where I got rid of your images:

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;
    }
}

Side note 2:

I would re-write this program over again, putting program logic in non-GUI classes, and making the GUI as "dumb" as possible since all program logic is out of it and added into the non-GUI model code, basically in an attempt to separate the "model" from the "view" as this will allow for much easier testing and improvement of the model (the non-GUI logic). I'd also use JPanels for each square, and put my piece ImageIcons into JLabels that are easy to move from panel to panel.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • My friend, i have no words to describe how happy i am with your answer, really, that's it, and you opened a new world on my mind, i'll tryna improve my logic in non-GUI, and following some advises of other members that answered me, i'll also study how to diagnose problems and how to use the debugger (i has no idea until now about how debugging works), so, i'm really glad, i wish you a great day, even at these chaotic times of pandemic routine and isolation, at least in my country, Brazil. – Pedro Martins Aug 22 '21 at 16:32
  • @PedroMartins https://stackoverflow.com/help/someone-answers – George Z. Aug 23 '21 at 10:55