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?
Related
I am attempting to create a very simple top-down game in Java, but I am unsure how to approach a problem dealing with program performance.
I used a 2D array to store certain values that represent certain things, such as the surrounding environment and the player's position. I then used the paint() method to draw a grid to the screen based on a section of the 2D array. The player is always in the center of the grid. I have it coded such that the player never truly "moves", but rather the environment around him "moves" (if you press a key to move up, a new section of the array is drawn that is the same as the past section except it has a new row at the top and the bottom-most row is now the past section's second-to-bottom row, all the while the player stays in the center, if that makes sense).
Thus, we have a situation where the whole screen needs to be redrawn each time the player moves. As you might have gathered, this is bad for the program's performance, since it has to iterate through a 2D array and draw it the screen each time I call repaint(). If the user hits the key to move upwards twice in succession, the program will lag and the screen will flicker as it redraws the whole section of the array.
How can I improve the performance issue, given that I want to keep the player in the center of the screen at all times and have the environment move around him? Should I instead investigate Jscrollpanes? Is iterating through arrays in the paint() method not the way to go?
Thank you so much for both your time and also helping an inexperienced programmer.
At my university I was given a task of implementing draughts game in a literate, object-oriented way following mvc design pattern. I was told that:
each of two game pieces should form a separate class that has separate fields for attack and non-capturing move in a form of collection;
checking the validity of a given move should be performed in a setwise manner.
I have no idea hot to do this, that is:
how to implement moves in the above defined way, i.e. in a form of collection
what sort of setwise operations should I use.
What sort of sets should I have, the procedural approach feels much more natural to me.
I'd be thankful for any suggestions on that or links discussing such implementations.
Some problems I find here. First of all, I guess model is given a mere pair of field indexes from a client view. So there is no initial information as to the nature of the move, i.e. whether it is a capturing on non-capturing move. In case of a king piece is not immediately given. Secondly, I guess the piece class should contain some sort of a vector, but how to account for men's limitation of moving only forward or either king's unlimited length of a move or requirement in some draught's rules that king should step one field after the captured piece?
Additional requirements were that implementation should be oriented towards legal directions of a game (diagonals) not around an array and that it should be elastic enough to fit different regional variations of the game.
Here is some insight on what you might want to try. Start with the view, if you can not create the "Checkers" board there is little use in going on.
Step 1: create the "view" the visual of the board with what ever gui programming language you wish.
Step 2: create the basic model, what the pieces are, ie, pawn or queen are the only two allowable pieces, set up icons for each single chip of course for pawn 2 stack for queen.
Step 3: setup the controller: one accept mouse clicks on the view board that captures whether it is selecting a position on the board that has a piece, and then realizes it is a piece and then outlines the possible moves of the piece. The controller should also tell the view board to update where the icon of the piece is on the board including when the game starts all the locations of the starting pieces which is stored in some collection in the model.
I would create an instance of the class for the pieces for each piece on the board easily done using a loop to create the pieces. Once you have those steps done you should be able to easily modify it to know when it is a capture move, an upgrade move(when a pawn reaches the other end of the board) illegal and legal moves.
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.
In a game that I am creating at the moment I want to make it so that the player holds a gun.
Right now I have the gun and the player as one image and it works but it would be alot better to have the gun and the player as seperate images because right now it looks like the player shots bullet from it's forehead and if I would have the gun as an seperate object it would be easier to make the bullets shot out of the gun. I will also implement a weapon switching system later on so then it will also be easier to have the guns as seperate objects.
The problem is that because I have used an AffineTransform and Vector2d to rotate the player to always face the mouse cursor I can't manage to make it so that it always looks like the player holds the gun. It's more that sometimes the gun is a little inside the player, sometimes it looks fine and sometimes the gun is floating in the air, either infront of the player or at the side of the player.
Is there any easy way that I could make the gun "stick" to a part of the player object?
You probably "just" need to use the right anchor, for example in rotate. To make this easier, imagine that the Gun bitmap (or Shape?) has the same size as the player.
I tried to illustrate that in this drawing:
The left image is the player, and the right image is the gun. Notice that the gun image has the same dimension as the player image, but is of course almost empty. The red point would be the anchor of the rotation - for example in the center of the image, even though that doesn't matter. If you superimpose the gun on the player and rotate both using the same anchor the gun will always be in the right place.
If you know your linear algebra you can of course also solve this analytically. But I would suggest first getting it to work the way you want, and then exploring more elegant solutions from there. A good quick read I found is this four part blog post. Part 3 and 4 touches on your question. If you want a more thorough introduction any linear algebra textbook will do, or you might like this free online course.
In our game we make the sword and shield stick to the appropiate position of the sprite of the player/enemy by having helpermethods like the ones below:
public int getPlayerLeftHand()
public int getPlayerRightHand()
And everytime the player is drawn (in our game he always has a shield and sword) his sword/shield is drawn at his right/left hand respectively by calling the above methods. The implementors (player/enemy) decide where their hands are so you don't have to worry at all about whether they are rotated or not, you know that every time you call the method the implementors take care of giving you the correct coordinates, in our case by checking what direction they are facing then displacing the coordinates appropriately.
Alternatively if you want a more OOP approach you could pass the player/enemy to the weapon and let them decide how and where they want to be rendered.
You solve this by accumulating transformation matrices.
First, you have a transformation matrix that positions the player. Next, you define a matrix that positions the gun in the hand of the untransformed player. Multiply the two matrices together, and you have one that positions the gun in the hand of the transformed player.
Finally, while you're at it, write a transform matrix that positions a bullet relative to the barrel of the gun. Multiply all three matrices together, and your bullet is where it belongs.
Your 3d graphics library will have routines to do all this for you.
I have to be blunt though: if you don't already know all this, you may have bitten off more than you can chew.
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.