Mouselistener in chess game - java

I am creating a chess game, and I have now populated my graphic chessboard with all the pieces, now I need to use Mouselistner to move the pieces around. Before implementing the graphic version I created a 2D console version, that took in "player moves", so I do have all those methods, but I need to now use Mouselistener, I read up about the methods, however, do I need to implement mouselistener in each class?
I have 1 abstract Piece class as well as 7 subclasses (incl Dummy piece), and a ChessBoard class that populates all the pieces and provides methods for moving (from the console version..) so where do I put the mouselistener? In the Jcomponent extension, JFrame or ChessBoard class that contains the methods to populate the chessboard and moves?

Sorry for such a simple answer, but all you need to do is add the mouselistener to your ChessBoard class. From there I'm assuming you can access the Piece subclass objects you've instantiated and call methods on them (i.e. mouseClicked, piece.pickUp()). If you code is arranged in such a way that you need to implement a mouse listener in many of your classes, consider the following:
addMouseListener( new MouseAdapter() {
#Override
public void mouseClicked( MouseEvent e ) {
// Do something
}
} );
http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseAdapter.html
Also, if it were me, I would transfer the methods for moving your Pieces to your Piece class, preferably at a higher level and then you don't have to rewrite the same code twice. Then in your game, whenever mouseReleased is invoked, call some method like attemptToMove(BoardPoint p) that will check if your piece's current position and the new position, p are within your piece's means of travel. A BoardPoint could be something you set up with x, y coordinates for your own board in an 8 X 8 style, like a 2-dimensional integer array.

It depends somewhat on how you have your pieces implemented. If they are GUI objects themselves, such as buttons or panels, then putting the mouseListener on them will allow the Swing framework to figure out which one has been clicked on. If the pieces all extend a Piece class, then you can put a handler in that as long as the logic it needs to execute (such as moving a piece around) can be made the same for all pieces.
If, on the other hand, you are drawing graphic images on the board in your code, so there is no GUI component for Swing to detect being clicked, then it makes more sense to implement the mouseListener on the board. In this case, your code is going to have to figure out which square was clicked on, and whether it has a piece on it; after that the handling will be much like the previous case.

Related

Design idea of "Turn" in chess

I am writing a chess program, and I am at the stage of implementing the game loop.
To implement player Turn in chess, I want to get some advice on how to do it efficiently.
So, this is how my chess with GUI works so far:
I generate a class called BoardGUI(JPanel) with a size of 8x8 and place a class called TileGUI(JPanel) on each grid.
I also added a MouseListener on TileGUI and wrote all functions regarding the Piece's movement on the board.
All tiles that have a Piece also contains the information of the Piece (color, type).
My initial thought of implementing the "Turn" is to create an integer called turn, initialized to 0, and make the Black Piece movable when the turn integer is an odd number and make the White Piece movable when the turn integer is an even number.
This is the best idea, or will there be a more clever way to do this?

Java Swing brief paintComponent graphics

I am creating a java 2D game and have come to a point where I am thinking of creating "pop-up graphics" i.e graphics that will populate the screen when a certain event occurs. Say, you pick up a certain item, I want this item to be displayed in the middle of the screen in a box containing information about said item.
Currently I have one big paintComponent that paints all of the graphics for the game (tiles, entities, players etc (which has been done efficiently I might add)). I know that I can probably have a boolean value which checks if an item has been picked up in that method, but it feels wrong.
What I am wondering is, is there a way for items to have their own paintComponent so that when it is called, it will show say a bo for a brief period WITHOUT having a boolean value in the big paintComponent method that I currently use for everything?
Small code example (won't execute)
public class popUpGraphics extends (JComponent or JPanel or whatever works best for this scenario)
{
public popUpGraphics(){
}
#Override
protected void paintComponent(Graphics g){
//g.Draw(stuff);
}
}
and then somewhere in an event I instantiate this or somesuch.
I do not want this to override the other paintcomponent, I just want to add to it
(as if it was another layer) to the paintComponent
In short I want to know:
1. Is is possible to have brief graphics shown without including in the huge paintComponent method
2. What Swing library should be extended (JComponent, JPanel etc)
Thanks in advance!

Using JPanel to draw straight lines and get point coordinates

I am at a total loss right now. I haven't worked much with building GUIs in Java, I've been reading all about swing and JPanel, and I think what I am trying to do is possible, I just haven't figured out how.
I'm trying to build a GUI in which you can draw straight lines within a certain drawing area, I would like to be able to get the start/endpoint coordinates in order to perform some math with those points. Any help would be greatly appreciated!
I will leave the code to you so here is the algorithm:
1. Create a JFrame and add a JPanel to it.
2. Add a mouse listener for the JPanel
3. Every time the mouse is pressed, get the x and y of the click. (starting points)
4. When the mouse is dragged , record x and y continuously.
5. When mouse is released, record the x and y. (ending points)
6. You could either use the drawLine() method of Graphics class or use draw() of Graphics2D in this case you will need a Line2D.Double -- the arguments remain the same - start x, start y, end x and end y
here is an image to explain a lil bit better:
Start with Performing Custom Painting and 2D Graphics.
Basically, you going to need a mouse listener to monitor the user interaction with your panel, check out How to write mouse listeners for more infor still.
Depending on your needs, if you need to maintain all the click points of the user, you would need to store them in something like a List, or if you just need to know the start and end points, the you just need a couple of Point objects.
You would be able to use these to paint onto your surface and performing your required calculations.
Remember, in this context, the points are contextual to the container they were generated on. That is 0x0 will be the top left of the container
Updated
You could also take advantage of the Shape API, using a Line2D to represent the two points. This would make it easier to distinguish between distinct lines/points
This is harder than just "draw straight lines with (x1,y1) and (x2, y2)" approach.
You need a Line(your custom) object that is dynamically created and placed on the JPanel which is listening for MouseEvents The canvas area being the JPanel itself. You also need to separate the MODEL from the VIEW so that your custom canvas JPanel will draw itself properly with an override for paintComponent()
The question is slightly vague, so I can't provide any code.
you need to add the mouse listener on JPanel.
then:
public void mouseClicked(MouseEvent me){
if(click==1){
int x1=me.getX();
int y1=me.getY();
click=click+1;
}
else{
int x2=me.getX();
int y2=me.getY();
click=1;
}
}
drawLine(x1,y1,x2,y2)
To draw line with mouse move you can also add mouse motion listener.

2D array AND JButton

Now I need to write a 8-puzzle game, which looks [like this]
The instructor asked us to write three different classes, which are Piece.java, EightPuzzle.java, and EightPuzzlePanel.java.
As you can see,
Piece.java represents each individual piece like "1", "2" in this eight puzzle board;
EightPuzzle.java represents the the game board to hold these 9 pieces/buttons.
EightPuzzlePanel.java is the GUI stuff.
So my question is, since we need to create a Piece[][] piece = new Piece[][], a 2D array, and we also need to arrange these piece on the board. I thought I could create 9 JButtons and put the 2D array in link with the 9 JButtons (or there have a better way to sort the 2D-array), but I don't know how to do that.
Also the buttons need to be controlled by both mouse and keyboard. This is another challenge for me.
Since this is homework I will not go into much detail, but this is how I would go about it:
Make Piece extends the JButton class. The Piece object takes the text to display and also the location of the image you would like it to render. You should be able to find plenty of examples online on how to add an image to a JButton.
Make EightPuzzle extend the JPanel class and also use the Grid Layout to render the Pieces neatly in a grid. This class takes on a 2D array of Piece objects which it will then render.
Make EightPuzzlePanel also extend the JPanel class. This class takes in another JPanel (EightPuzzle) and appends any other buttons you might need.
Finally create a Main class which extends JFrame and then I append the EightPuzzlePanel to it (which should in turn contain the other panel with the other buttons).
For the mouse and key, you'll need to set up some action listeners.
For this problem you can just use a 1-D array. As long as you have the 9 pieces stored in you array you can use you layout manager to put them in the right place- then traversing through the array is simple.

MouseMotion Sensor Method Call

I have encountered a problem, for which no matter how long I study the API's of the class and superclasses, I can not figure out.
Suppose I wish to design a sort of a game where the mouse motion controls the motion of a block that is used to bounce a ball, which then destroys multi colored bricks.
How do you specifically make the block "listen" to the mouse?
The below code is what I have attempted to achieve the desired results.
/** Breakout Program*/
public class Breakout extends GraphicsProgram implements MouseMotionListener {
...
/** The Paddle Itself */
private GRect paddle = new GRect(0, HEIGHT-PADDLEBOTTOM_OFFSET, PADDLEWIDTH, PADDLEHEIGHT);
...
/** Run the Breakout program. */
public void run() {
paddle.setFillColor(Color.BLACK);
paddle.setFilled(true);
add(paddle);
paddle.addMouseListener(this);
...
}
/** Move the horizontal middle of the paddle to the x-coordinate of the mouse position -
* -but keep the paddle completely on the board. */
public void mouseMoved(MouseEvent e) {
GPoint p= new GPoint(e.getPoint());
double x = p.getX();
paddle.setLocation(x, HEIGHT-PADDLEBOTTOM_OFFSET);
}
}
Any clarification on why/what I am doing incorrectly would be helpful, thanks.
Your class is all set to be used as a mouse listener -- you just have to tell some component to send you MouseEvents. In order to do that, you need to implement MouseMotionListener, which you've already done, so you're most of the way there.
All that's left to do is call the method addMouseMotionListener(this) on your JFrame, JDialog, or whatever window you're using.
In the future, it may be worth setting up a separate class to serve as the listener, just to keep your code straight; the most common solution is called an anonymous inner class, which you may want to Google. But with your deadline approaching, what you've got will work fine.
After mouseMoved() updates the paddle location, you would typically invoke repaint() on the display component. Is there anything in GraphicsProgram apropos to this?
It looks like all of the classes belong to your application, so I am guessing you are working with AWT or Swing.
Try calling repaint() on the paddle.
Just an extra comment to "Etaoin", when you get time and if you are serious about doing OO well, do a search on "is-a" and "has-a" relationships in OO.
If the "is-a" relationship holds true (an apple "is-a" fruit) then its legitimate to use the implements on the class, otherwise if its a "has-a" relationship (a car "has-a" wheel, but a car "is-not-a" wheel) then implements is NOT appropriate - you need to use composition, in other words a member variable of the class.
In your code, can you say that the Breakout class "is-a" MouseMotionListener? The answer is "no", BTW! Breakout "is-a" game, or is an application, but the MOuseMotionListener is part of the implementation.
As "Etaoin" has said, you should implement the MouseMotionListener as an inner class, though I prefer private inner classes, not anonymous classes (to keep the constructor short and to the point, among other reasons).
When you "get" OO, its great and very powerful, but takes real effort to make the "paradigm shift" from procedural thinking.

Categories

Resources