Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


derkotah

Member Since 17 Dec 2012
Offline Last Active Dec 17 2012 02:23 PM

#5011633 Chess Movement Using Mouse Listeners (Java)

Posted by derkotah on 17 December 2012 - 04:38 AM

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[i][j] = new Square(null, squareLocation);
	chessBoard[i][j].addMouseListener(squareController);
	
	if((i + j) % 2 == 1)
	{
	 chessBoard[i][j].setBackground(Color.WHITE);
	 chessBoard[i][j].addMouseListener(squareController);
	}
	else
	{
	 chessBoard[i][j].setBackground(Color.BLACK);
	}
	framePanel.add(chessBoard[i][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;
}

}



PARTNERS