How should objects be in a Java game - java

EDIT: i just deleted the entire post and reformulated the question to be more generic.
I want to do a simple strategy game: map, units.
Map: one class. Units: another class, self drawn.
Simple questions:
How does an unit should redraw itself on the map.
A unit should be a JPanel or similar Swing component (just to be able to manage them as an entity with its own mousehandlers) or can be another thing, without neglecting the fact that it should be an autonomous object with its own action handlers and fields.
Is this map-units model correct of a simple game that would help me to learn in a fun way Java and OOP fundamentals.
Thats it!

There are 2 ways.
Either have a Map class which is the main JPanel, to maintain the collection of units, but keep the Unit class as non-Swing. When the Map's paint() method is called, ask each Unit to redraw itself by calling a method in each visible Unit. The Unit could be inherited from any base class, for example Rectangle, or some other data structure you use in the program. In this case, the Unit class handles painting and calculations, but the Map handles the clicks and events for each Unit. It could pass the message on to the Unit if needed; however, if the unit itself doesn't need to know about these things, this method works well. The Unit class is light and economical. You can also decide whether the Unit knows its position in the Map or not.
Or have each unit as a JComponent, and handle its own events separately. The disadvantage is that each instance of a Unit creates a pile of data for drawing it as well. So if you have hundreds of units, only a couple of which are drawn, this way is not efficient. The advantage is each unit can handle its own GUI events without translation etc. This assumes also a 1:1 mapping of actual units in the game and graphical units on the screen. Also it is trickier to implement certain event handlers in the Unit, if a Unit needs to know about what other Units are around!
A third and arguably better way is to have a purely data Unit class, containing the game information about the unit, as in (1), but which has a method to create the JComponent when needed. The JComponent could, for example, be an inner class in the Unit - it could then access the Unit data. This is great if a unit may need to be displayed in 2 places (e.g. on 2 screens or views).
--
Addendum to address comments
That is correct, in (1) the Map (main JPanel) implements the mouse handler, and asks each unit in turn if it is 'hit'. This allows you to do more complex things, such as have 2 units overlapping/on top of each other, and both could respond to the click.
Also, for example, they may not be rectangular, or may be drawn with an alpha channel (if the Units were JComponents, they will by default grab any mouse event over their whole rectangle, to themselves). If your units don't overlap and are in their own rectangles, then JComponent's own mouse handler is enough.
If you use approach (1), the Map can ask each unit whether it contains a clicked point, and the Map can then handle the 'selection' process. Remember, a unit on its own won't be able to work out what other units are selected - selection may involve deselecting another unit. In that case, the selection operation is really a Map operation, not a Unit operation, although it may change the appearance or function of the Unit as well.
If you use separate JComponents for the Units, you can override contains(Point) to determine if the mouse hits the item, but this won't let other Units also respond to the click. But each Unit could 'select itself' (set a flag used when drawing) then notify the Map (it will need to find it using getParent or by a preset property).
Key things you need to know before deciding on this design would be:
Will you ever need more than one 'Map' panel per game?
Will you ever need more Unit objects than are to be displayed?
Will you ever need to display a Unit more than once?
If the answers are yes, you should separate the 'Data' classes from the 'View' classes, as suggested in 3.
then: What does a Unit need to 'do' and what does it need to know about the Map and other Units in order to do this? e.g. moving is usually done by the Map class in this situation, as it depends on the Map and on other Units; drawing is best done by the Unit because there may be many unit subtypes with different data structures that may need to be drawn; Unit selection operations as you have pointed out lie somewhere in between. If you see how Swing implements this (e.g. ButtonGroup, ListSelectionModel), the 'selection' itself can be though of as a separate class.

I made a peg solitaire game a few years ago which was pretty much just a JPanel that extended MouseListener and MouseMotionListener. The pegs were primitive circles drawn in the paint method, but you could track where they landed by taking the cursor position and mathematically working out the square in which it landed. That lined up with an array that stored either a 1 or 0 for each square on the board depending if anything was there. You could also drag each piece by finding the current cursor position then calling repaint() in the mouseDragged method you get from implementing MouseMotionListener.
I'd probably suggest doing it that way to begin with. Create an array of whatever size and use that to track the units. Then each time you make a move just check that array and redraw your units in the paint method. If you're using mouse movement then you can get the current position of the unit on mouseDown then do what I mentioned before with mouseDragged, and then get your final location on mouseUp and also do your calculations in regards to legal moves etc in mouseUp.
In the paint method you'll just loop over the array that defines the map and if there is a unit at the current position on the array then do something like g.fillOval(x,y,x_dimension,y_dimension). That array could just have its elements set to 0 for no unit at the current position, or 1 for a team 1 unit at the current position, 2 for team 2 etc. The paint method will take those numbers and draw pieces accordingly (change color for each type or whatever).
I hope that makes a bit of sense.

Related

Java LibGDX Update and Draw Methods

People usually write "draw(SpriteBatch batch)" and "update(float deltaTime)" methods in their player classes. Why don't they just write "render(SpriteBatch batch, float deltaTime)"? Because of readability? I mean, why they make two methods? They can do in single method.
Readability and ease of updating/changing is one reason.
But there are also logistical reasons. You want to be sure your whole game state is fully up to date before you start drawing, so whatever is on screen is as up-to-date as possible. If you put updating and rendering into one method for each object, then objects that are updated and drawn first might look out of date compared to objects that are updated later and affect the state of the earlier objects. But if updating and drawing are separated, you can update the entire game and then draw the entire game.
And if your game uses physics, the separation of updating and drawing allows you to update your world at a fixed timestep (at a different rate as the drawing) to ensure the game play is not affected by frame rate.
That's because you want to seperate between your game logic and your render function. It's easier to read and also helps if you want to update your game logic more often than your render logic.

Chess game design and Singleton pattern

I am currently creating a chess game consisting of the following classes:
ChessPiece - For all the various chess pieces, composed with a MovementBehaviour instance variable
MovementBehaviour - Interface implemented by PawnMovementBehaviour,
KingMovementBehaviour etc classes to define
how each piece type moves
ChessBoard - Consisting of a ChessPiece[][] 2D array with functionality like addPiece()/removePiece()/replacePiece() etc
Player - Small class helps associate which pieces belong to which human player
Game - The main class essentially which will begin by asking players for their names and desired piece colors and then running the
game by instantiating a ChessBoard and letting players move turn by
turn until checkmate is reached.
I was wondering if I should be using a Singleton pattern (With regards to the ChessBoard class) ? Currently I am not and I am passing the instance of the ChessBoard into the chess pieces movement functionality so that the piece can understand its surroundings. This is because of course moves are deemed legal depending on what spaces are occupied/empty on the board at any time.
Singletons are very rarely a good idea. I happen to have started a similar project recently so I will answer this from my current experience.
The way I've implemented it is by considering a chessboard a collection of Location objects, where a location holds an X-value, Y-value and a Piece object. Only relevant places are filled in where empty ones aren't even tracked.
You seem to be wondering if you should use a singleton for the single purpose of validation. There are many, many things you have to validate when a move is done: Can you move that way? Are you check? Is it en-passant? Is it a rochade? etc.
What you could do is create a bunch of validate methods that take as arguments a chessboard and the start- and endlocation. This way you have all information required to check if the move is valid. This does require the pieces to know their own properties: how can I move? What's my color?
When you have all this, you can implement the different validation logic to make a move.
Using a singleton will be rather nasty when you could just extract the validation and pass the chessboard around. It would also be much harder to test (and good testing is definitely something you want in a chessgame).
My setup looks like this:
Chessboard.CanMoveToLocation(int startX, int startY, int endX, int endY) {
// Call validators with local field chessboard and given location objects
}
Each validator will return a custom enum ValidationResult to indicate if it's allowed or forbidden for this particular validator.
You'll have to make sure the validators are called in the correct order (returning false after checking if it's a valid move is not a good idea: he might have been rochading or slaying en-passant). Or you could ofcourse combine related validators.
Should you wish to take a look: my current (far from finished) implementation.
In my experience, I'd rather use Observer Pattern in this case.
The ChessBoard class plays the role of Observer and the ChessPiece which should be an abstract class is the Subject class. You might want to make a look on Observer Pattern and it usage
When you take one Piece and make a movement, that means the location of that Piece has been changed and the Piece will notify to the board to check the movement whether it is valid or not.

2D graphics library for Android

I'm working on an Android application that requires 2D graphical view with a large set of objects. Here's what I basically need to display:
In my case, there could be hundreds of spatially distributed objects. This view is going to behave like a map, so the user is able to scroll in horizontally and vertically, zoom in and zoom out. It also requires click event handling, so the user is able to click any triangle and I then should display some extended information related with that particular triangle.
I'm mostly concerned about 3 things:
In case I re-draw all the objects per in my onDraw() handler, that would be really slow. Also, there I cases when I don't even need to draw all these objects since some of them are invisible depending on zoom level and scroll position. These requires using quad trees which I don't want to implement manually.
All these objects are defined as (x,y,rotation,type), so in case customer decides that we need a "show all" button, I'll have to implement a functionality to calculate bounding boxes.
I need to be able to handle click events and (probably) dragging for all these shapes.
Is there any library that can help me with these tasks? Just don't want to spend 3 days on stuff that I believe must already have been implemented.
All the methods in the Canvas class of the android.graphics package should suffice. The Canvas does clipping (meaning drawing commands get discarded if it's not visible) so if the image is static you could render it into a Picture and draw that on onDraw().
I think the drawing methods have methods to calculate bounds and return them. See Path's computeBounds(RectF bounds, boolean exact).

Can an object remove itself? How?

I'm trying to write a simple ball game, and there's several turns (ie., ball lives). The ball "dies" when it passes the bottom border of the screen. What I have so far works, but doesn't seem to be the proper way to do things:
if (ball.getY() > bottomOfScreen) {
ball.die();
remove(ball);
}
The die() method basically fades the ball's colour slowly (dark_gray -> pause(50) -> light_gray -> pause(50)), but doesn't actually do anything useful.
The remove(), obviously, gets rid of the ball from the screen, which is what I want. It makes sense to me for this remove() to be a part of Ball's die() method, as opposed to it being a separate method call in the main program -- but I'm not sure how to go about this?
Can an object delete itself? And, if it can, is object suicide better than object murder, from a philosophical/methodological point of view?
Thanks!
The object can remove itself given it has some sort of reference to the view rendering mechanism. Your sample doesn't give enough information so I'll exemplify one way to do it:
public class Ball {
private ViewRenderer view;
public void remove() {
view.remove(this);
}
}
Neither suicide nor murder is better or worse. It depends on your design and requirements.
In this sample though, murder might be preferable since this way the Ball object doesn't need to know in which context it's being used.
It is possible to create a method in which the ball removes itself, but it's a bad thing to do. In order to remove itself from the screen, the Ball must have a reference to the screen. This creates a circular chain of references (Ball has a reference to screen, screen has a reference to Ball) which is going to make your design more complicated and your testing much more complicated.
Suicide is fine - the screen tells the ball to die, and the ball dies. But this is about removal of a relationship, not dying. The thing maintaining the relationship is the screen, and so it should be the thing doing the removal.
Also remember that the two do not necessarily have to happen together. The screen might want to keep a dead ball around for some reason, and it might want to remove a ball that isn't dead. Even if that doesn't happen in your app right now, allow for the possibility.
In a sense of deleting the object from memory: no, in Java that is handled by the garbage collector exclusively.
What you could do is to remove the object from collections containing it, but this would require the object to have access to those collections (which in most cases would not be feasible, since there might be a lot of collections).
I'd suggest the containing object (the screen in your case) to poll for the contained object's (the ball's) state and remove it after it is actually dead.
There is presumably some object (e.g. the Screen, or the ViewRenderer in Johan's example) that holds a reference to the Ball, and removing this reference has to be done by the Screen ("object murder"). "Object suicide" amounts to Ball passing a message to the Screen asking to be "murdered".
Since it is the Ball that knows when it has passed the boundary, it makes sense to me (without knowing the details of your design) for the removal to be initiated by the Ball. Then the Screen can find out about this change by one of several means:
The Screen can poll the Ball.
The Ball can hold a direct backward reference to the Screen, which creates an unfortunate circular dependency.
The Ball can hold a reference to the screen via a BallObserver interface. This is an application of the observer pattern.
The first is simplest, and this makes it a good choice if it fits naturally into your mechanism for painting the screen. The third is more flexible in principle, but you might not need this flexibility in practice. The middle option might be OK in a simple program, but you should probably consider it as a step on the way to the third.
And if you don't have a Screen (or ViewRenderer, or whatever) object and really mean "a separate method call in the main program" then you should probably reconsider your design.
No, objects cannot suicide. Any reference of itself is just a reference.
To "clear" the object within itself one would just clear all instance variables.
To "clear" the object outside itself one would set the variable equal to null.

MVC-design and displaying arrays using Swing/Graphics in Java

I'm working on a small Chess game and think I'm almost done with the basic model and ready to start writing the GUI.
What I've been wondering for a long time is that if the Chess board is represented by a Square array of [8][8], and I create a method to draw a square and somehow establish a relation between that method and the Square model, will I then magically have a visual Chess board?
I mean, say that a square is 10x10 pix, does that mean that the first element (represented by a square) will begin at (0, 0), element two at (10, 0), element/square nine at (0, 10) etc?
When I checked out Graphics2D I noticed that the method to draw a rectangle requires x and y coordinates, what do I do if I want the position to depend on the array element?
Or I am going to have to write down the coordinates of each square on the board?
Another thing that has been bothering me is whether it's [row][column] or [column][row]?
I've been using [column][row] in my code since it seems right if you think of it as (x, y).
When you move up and down you change the row, = y, etc.
I've been trying to google around to find out how to apply the MVC-design, what to think about, do's an dont's, etc. The only thing I know this far is that model = data logic, view = gui and control = interaction, the conclusion is that either I'm bad at googling or there isn't any good information targeted at beginners regarding MVC.
Mainly I don't really understand the relation between M, V and C.
So, let's get the easy question out of the way: as far as 2D arrays goes, it's actually up to you to decide whether it's [row][column] or [column][row]. Java doesn't care. As long as you treat it consistently throughout your app you can think of it whichever way makes most sense to you. If it helps (and it might not) remember that a 2D array is just an array of arrays.
As for MVC, this is how I think of it: M is the model of the data (the array, for example), V is the visual representation of that data (displayed to the user, as a chessboard perhaps) and C is the controller, which connects the two and transmits changes in one to the other, translating or otherwise interpreting user actions as necessary. If the user drags a chess piece from one square to another, the Controller interprets this gesture, implements the logic that decides if the maneuver is legal and what side-effects it might have (like capturing a piece), and updates both the model and the view as required. The confusion lies in that most UI toolkits, Java's included, often blur the boundaries between these pieces, so that bits of the Controller end up in the View, or the Model, or both. It's not necessarily a problem, but it's something to be aware of. The main thing is to try, as far as possible, to keep a well-defined boundary between the data, the view, and the logic that interfaces the two.
To answer your question about drawing and co-ordinates, it really depends how you implement your chessboard UI. You could implement it entirely using Java Swing, for example, and by making clever use of JLabels, JPanels, and maybe a GridLayout, or perhaps even a JTable, you could almost (almost!) have an automagially updating chessboard. On the other hand, you could implement your own UI classes from scratch, making use of Java2D and the drawing primitives it provides, and then you'd have to do more management of co-ordinates and such.
Ri8 dear... Actually .. we cant seen clearly advantages of MVC architecture in small application means window based small application... but when you r going with large scale enterprise application .. you realize that ..
When large enterprise level distributed system developing there are lots of developers, designers and other persons are working with it. Now , suppose developer make designing in their coding part .. so it is very hard to understand by any designer.. so this part is seperated so disigner can easily modified and udnerstand this very well and for that there is no need of help of programmer and its a VIEW component....
Same as if there is some business logic is combined with view components then it is hard to understand by programmer and it take too much time to separate that logic from VIEW component, so any programmer can easily & speedly understand that logic .. so Logic means Model and design means any GUI part means VIEW component is separated...
Now Controller .. component .. so, CONTROLLER component provide bridge between those two model and view component.. menan it decided that which view may be given to end user..
and it controll View with the help of model component.............
GOt .. IT........!!!!...
IF any Suggestion... Most Well Come...................

Categories