Chess Movement Using Mouse Listeners (Java)

Started by
2 comments, last by PsychotikRabbit 11 years, 4 months ago
I'm trying to implement MouseListeners for my Chess Code, I'm using MousePressed and Mouse Released as it is not drag and drop. I have to grab the piece from the firstClick and show all the possible movements for that Piece by highlighting them. What would be the best way to implement this? As of now I have a class called MouseController that is added to each Square that creates a chessboard (using a double array). Hopefully someone can help me out, and if you need to see more code I can provide it!


public class MouseController implements MouseListener
{
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mousePressed(MouseEvent event)
{

}
@Override
public void mouseReleased(MouseEvent event)
{
Square square = (Square) event.getSource();
if(square.getPiece() != null)
{
ArrayList<Location> moveList = square.getPiece().getMoves();
for(Location l: moveList)
{
int x = l.getxCoordinate();
int y = l.getyCoordinate();
square.highLightSquare(x,y);
}
}
else
{
System.out.println("there is nothing ot click!");
}

// Square square = (Square)event.getSource();
// Location location = square.getSquareLocation();
// if(square != null)
// {
// //get the chesspieces possible moves and highlight them
// System.out.println("I got here");
// }
}
}




public class Square extends JPanel
{

private ChessPiece piece;
private Location squareLocation;
private Color squareColor;
private BoardFrame bf;

/**
*
*/
public Square(ChessPiece pieceType , Location squareLocation)
{
this.squareLocation = squareLocation;
this.piece = pieceType;

}

public Color getSquareColor() {
return squareColor;
}
public void setSquareColor(Color squareColor) {
this.squareColor = squareColor;
}

/**
*
* @return
*/
public Location getSquareLocation()
{
return squareLocation;
}

/**
*
* @param squareLocation
*/
public void setSquareLocation(Location squareLocation)
{
this.squareLocation = squareLocation;
}

/**
* @return occupying piece or null if unoccupied
*/
public ChessPiece getPiece() {
return piece;
}

/**
* @param new occupying piece
*/
public void setPiece(ChessPiece piece) {
this.piece = piece;
}

/**
* hightlights the square that has been clicked on
* @param squareToHighlightLocation
*/
public void highLightSquare(int x, int y)
{
setBackground(Color.GREEN);
repaint();
validate();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((squareLocation == null) ? 0 : squareLocation.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Square other = (Square) obj;
if (squareLocation == null) {
if (other.squareLocation != null)
return false;
} else if (!squareLocation.equals(other.squareLocation))
return false;
return true;
}
}



public abstract class ChessPiece
{
private Color pieceColor;
private JLabel pieceImage;
private ArrayList<Location> moveList;

/**
* ChessPiece hold a color and an image
* @param pieceColor
* color of the piece
* @param image
* piece image
*/
public ChessPiece(Color pieceColor)
{
this.pieceColor = pieceColor;
}

/**
* let location be BoardState location(piece)
* create Movelist)
* create traget(location + 1)
* if target is not occupied by players color
* add to movelist
* @param boardState
* current state of the board
* @return
* possible locations
*/
public abstract ArrayList<Location> getPossibleMoves(Square endingLocation, BoardFrame bf);

public ArrayList<Location> getMoves()
{
return this.moveList;
}

/**
* gets the color of the piece
* @return color of the piece
*/
public Color getColor()
{
return this.pieceColor;

}

/**
* gets the imageicon for the image
* @return the piece image
*/
public JLabel getImage()
{
return this.pieceImage;
}

public JLabel createImage(String imagePath)
{
pieceImage = new JLabel(new ImageIcon(imagePath));
return pieceImage;
}
}



*Model for the Chess Game holds all board data
*/
public class BoardState implements Serializable
{
private HashMap<Square, ChessPiece> boardStateMap;
private BoardFrame boardFrame;
public static final String SET_PIECE = "SetPiece";
public static final String REMOVE_PIECE = "RemovePiece";
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

public void addPropertyChangeListener(PropertyChangeListener listener)
{
this.propertyChangeSupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener)
{
this.propertyChangeSupport.removePropertyChangeListener(listener);
}

/**
* creates a new board state HashMap
*/
public BoardState()
{
boardStateMap = new HashMap<Square, ChessPiece>();
}

public void removePiece(Square currentSquare)
{
boardStateMap.remove(currentSquare);
this.propertyChangeSupport.firePropertyChange(REMOVE_PIECE, null, currentSquare);
}

public void setPiece(Square currentSquare, Square landingSquare)
{
boardStateMap.put(landingSquare, currentSquare.getPiece());
this.propertyChangeSupport.firePropertyChange(SET_PIECE, currentSquare, landingSquare);
}

public ChessPiece getPiece(Location location)
{
Square square = new Square(null, location);
return boardStateMap.get(square);
}
/**
* gets called when the board state needs to be seen
* @return board state map
*/
public HashMap<Square, ChessPiece> getBoardStateMap() {
return boardStateMap;
}


/**
* updates the boardstate
* @param key
* @param value
*/
public void setBoardStateMap(Square key, ChessPiece value)
{
boardStateMap.put(key, value);
}
}



/**
* creates a JFrame
*/
public BoardFrame(final BoardState bs)
{
bs.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
String type = e.getPropertyName();
if(type.equals(bs.SET_PIECE))
{
Square landingSquare = (Square)e.getNewValue();
Square currentSquare = (Square)e.getOldValue();
Square landingSquareCoods = chessBoard[landingSquare.getSquareLocation().getxCoordinate()][landingSquare.getSquareLocation().getyCoordinate()];
Square currentSquareCoods = chessBoard[currentSquare.getSquareLocation().getxCoordinate()][currentSquare.getSquareLocation().getyCoordinate()];
if(landingSquare.getPiece() == null)
{
landingSquareCoods.add(currentSquare.getPiece().getImage());
framePanel.validate();
}
else
{
JOptionPane.showConfirmDialog(null, "This spot has already been taken!");
}
}
if(type.equals(bs.REMOVE_PIECE))
{
Square currentSquare = (Square)e.getNewValue();
Square currentSquareCoods = chessBoard[currentSquare.getSquareLocation().getxCoordinate()][currentSquare.getSquareLocation().getyCoordinate()];
if(currentSquare.getPiece() != null)
{
currentSquareCoods.removeAll();
currentSquareCoods.repaint();
framePanel.validate();
}
else
{
JOptionPane.showConfirmDialog(null, "There is no piece to move1");
}
}
}
});
chessFrame = new JFrame("Chess");
chessFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chessFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
chessFrame.setLayout(new BorderLayout());
chessFrame.setResizable(false);
createBoard();
chessFrame.setVisible(true);
}

/**
* creates the essentials needed to make the boardframe
*/
private void createBoard()
{
createTopPanelForFrame();
createWestPanelForFrame();
// createEastPanelForFrame();
createGridLayoutPanelForFrame();
createBoardSquares();
createBoardLabels();
}

/**
* creates the top panel which will hold the labels A-H
*/
private void createTopPanelForFrame()
{
topPanel = new JPanel();
topPanel.setSize(TOP_PANEL_WIDTH, TOP_PANEL_HEIGHT);
topPanel.setLayout(new GridLayout(TOP_PANEL_ROW, TOP_PANEL_COLUMN));
chessFrame.add(topPanel, BorderLayout.NORTH);
}

/**
* creates the top panel which will hold the labels 1-8
*/
private void createWestPanelForFrame()
{
westPanel = new JPanel();
westPanel.setSize(WEST_PANEL_WIDTH, WEST_PANEL_HEIGHT);
westPanel.setLayout(new GridLayout(WEST_PANEL_ROW, WEST_PANEL_COLUMN));
chessFrame.add(westPanel, BorderLayout.WEST);
}

// public void createEastPanelForFrame()
// {
// eastPanel = new JPanel();
// eastPanel.setSize(WEST_PANEL_WIDTH, WEST_PANEL_HEIGHT);
// eastPanel.setLayout(new GridLayout(1,1));
// chessFrame.add(eastPanel, BorderLayout.EAST);
// }

/**
* creates a Panel that has a GridLayout and is added to the frame
*/
private void createGridLayoutPanelForFrame()
{
framePanel = new JPanel();
framePanel.setSize(PANEL_WIDTH, PANEL_HEIGHT);
framePanel.setLayout(new GridLayout(BOARD_SIZE, BOARD_SIZE));
chessFrame.add(framePanel, BorderLayout.CENTER);
}

/**
* creates the alternating squares on the board
*/
private void createBoardSquares()
{
MouseController squareController = new MouseController();
for(int i = 1; i <= BOARD_SIZE; i ++)
{
for(int j = 1; j <= BOARD_SIZE; j++)
{
Location squareLocation = new Location(i,j);
chessBoard[j] = new Square(null, squareLocation);
chessBoard[j].addMouseListener(squareController);

if((i + j) % 2 == 1)
{
chessBoard[j].setBackground(Color.WHITE);
chessBoard[j].addMouseListener(squareController);
}
else
{
chessBoard[j].setBackground(Color.BLACK);
}
framePanel.add(chessBoard[j]);
}
}
}

/**
* creates the A-H, 1-8 and Player's Turn Labels
*/
private void createBoardLabels()
{
ALabel = new JLabel("A");
topPanel.add(ALabel);
BLabel = new JLabel("B");
topPanel.add(BLabel);
CLabel = new JLabel("C");
topPanel.add(CLabel);
DLabel = new JLabel("D");
topPanel.add(DLabel);
ELabel = new JLabel("E");
topPanel.add(ELabel);
FLabel = new JLabel("F");
topPanel.add(FLabel);
GLabel = new JLabel("G");
topPanel.add(GLabel);
HLabel = new JLabel("H");
topPanel.add(HLabel);

OneLabel = new JLabel("1");
TwoLabel = new JLabel("2");
ThreeLabel = new JLabel("3");
FourLabel = new JLabel("4");
FiveLabel = new JLabel("5");
SixLabel = new JLabel("6");
SevenLabel = new JLabel("7");
EightLabel = new JLabel("8");
westPanel.add(EightLabel);
westPanel.add(SevenLabel);
westPanel.add(SixLabel);
westPanel.add(FiveLabel);
westPanel.add(FourLabel);
westPanel.add(ThreeLabel);
westPanel.add(TwoLabel);
westPanel.add(OneLabel);
PlayerTurnLabel = new JLabel("? Turn");
// eastPanel.add(PlayerTurnLabel);
}

/**
* set x Coordinate to pieceLocations x coordinate
* set y Coordinate to pieceLocations y coordinate
*
* @param pieceLocation
*/
public void addPieceToBoard(Location pieceLocation, ChessPiece pieceToAdd, BoardState bs)
{
int xCoordinate = pieceLocation.getxCoordinate();
int yCoordinate = pieceLocation.getyCoordinate();
chessBoard[xCoordinate][yCoordinate].add(pieceToAdd.getImage());
chessBoard[xCoordinate][yCoordinate].repaint();
framePanel.validate();
}

public boolean isSquareNull(int x, int y)
{
boolean isNull;
if(chessBoard[x][y].getPiece() == null)
{
isNull = true;
}
else
{
isNull = false;
}
return isNull;
}

}
Advertisement
You are calling the method to highlight solution squares on the mouseReleased event instead of the mousePressed. MousePressed is the trigger for your "drag" and MouseReleased is the trigger for your "drop". What do you need to know exactly about mouse listeners ?

You are calling the method to highlight solution squares on the mouseReleased event instead of the mousePressed. MousePressed is the trigger for your "drag" and MouseReleased is the trigger for your "drop". What do you need to know exactly about mouse listeners ?

I've tried the method in both mousePressed and MouseDragged and both come up null. I wanted to use the BoardState class to figure out the square's location and chesspiece, so that I can verify whether it is null or not, but I haven't exactly found a way to do that as I can't pass in any parameters to a mouseEvent. I'm knowledgeable enough about mouseListeners to complete the task, it's more rather how to implement it that's keeping me back.
I've already worked on something similar, it's just mathematics. MouseEvent can provide you the mouse position of the click (MouseEvent.getX(), MouseEvent.getY()).
We're lucky that you are making a chess game because of chessboard. To get the selected square location you can simply loop through all rows and column and check if the position of the mouse is within the square.

I wrote a little method which would find a square , I didn't test it but I think it can help you out.


private final int NUMBER_OF_ROWS = 8;
private final int NUMBER_OF_COLUMNS = 8;
private final int SQUARE_SIZE = 32;

public Square getSquareAt(int x, int y) {
for(int col = 0; col < NUMBER_OF_COLUMNS ; ++col ) {
for(int row = 0; row < NUMBER_OF_ROWS; ++row ) {
int squareX = row * SQUARE_SIZE;
int squareY = col * SQUARE_SIZE;
Rectangle rectangle = new Rectangle(squareX,squareY, SQUARE_SIZE, SQUARE_SIZE);

if(rectangle.contains(x, y)) {
return chessBoard[col][row];
}
}
}
return null;
}


I let java.awt detect if the coordinate of the mouse is within the bounds of the square.

Edit: That will work if there is one unique mouse listener listening on the chessboard panel. (container of all squares).

This topic is closed to new replies.

Advertisement