OOP question regarding object instances, observer/observable pattern, and singletons - java

Making a minesweeper app and I have a GameGrid class to hold all the squares in a multidimensional arraylist of squares, and it handles initializing the squares along with determining where the mines will be. The Square class has variables for its position (x and y), and a variable hasMine. Now, due to some circumstances arising, I have needed to pass a GameGrid instance into the constructor of Square because I needed to access a method inside GameGrid. My question is, is this good design? For some reason, the fact that I'm passing a GameGrid instance into a Square just doesn't feel right.
I've tried to experiment with an Observer/Observable type pattern with unfortunately no luck. Another option would be to make GameGrid a singleton, just not sure if that's the best option here.
I bet a similar situation like this has probably come up before, just wondering what the best solution would be.
Edit:
Decided to clear a few things up and clarify the actual problem I'm running into.
So each square is responsible for changing its own icon when it's clicked (when it's flipped over). The problem arises when I want to implement the O-fill behavior when a zero is clicked (this concept is easy if you're familiar with minesweeper). When a zero is clicked on, all the zeroes around will automatically be flipped over. I need to use GameGrid for this and not Square because Square doesn't have access to all the squares around it.
But since a few comments have been posted and I've done a little research, I've figured out that I think I'll either just keep it as it is, and pass in the desired GameGrid instance into Square, or I'll try to work with a custom observer/observable like pattern where the updated argument (normally from notifyObservers(Object arg)) will be a custom Class that I can use to hold all the required information needed.

Related

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.

2-Dimensional Tile-Based Game: Each tile as an object impractical?

I've been trying various ways of creating a two-dimensional tile-based game for a few months now. I have always had each tile be a separate object of a 'Tile' class. The tile objects are stored in a two-dimensional array of objects. This has proven to be extremely impractical, mostly in terms of performance with many tiles being rendered at once. I have aided in this by only allowing tiles within a certain distance of the player being rendered, but this isn't that great either. I have also had problems with the objects returning a null-pointer exception when I try to edit the tile's values in-game. This has to do with the objects in the 2D array not being properly initialized.
Is there any other, simpler way of doing this? I can't imagine every tile-based game uses this exact way, I must be overlooking something.
EDIT: Perhaps LWJGL just isn't the correct library to use? I am having similar problems with implementing a font system with LWJGL... typing out more than a sentence will bring down the FPS by 100 or even more.
For static objects (not going anywhere, staying where they are) 1 tile = 1 object is OK. That's how it was done in Wolf3d. For moving objects you have multiple options.
You can, if you really really want to, store object sub-parts in adjacent cells/tiles when an object isn't contained fully within just one of them and crosses one or more cell/tile boundaries. But that may be not quite handy as you'd need to split your objects into parts on the fly.
A more reasonable approach is to not store moving objects in cells/tiles at all and process them more or less independently of the static objects. But then you will need to have some code to determine object visibility. Actually, in graphics the most basic performance problems come from unnecessary calculations and rendering. Generally, you don't want to even try to render what's invisible. Likewise, if some computations (especially complex ones) can be moved outside of the innermost loops, they should be.
Other than that it's pretty hard to give any specific advice given so little details about what you're doing, how you're doing it and seeing the actual code. You should really try to make your questions specific.
A two-dimensional array of Tile objects should be fine........ this is what most 2D games use and you should certainly be able to get good enough performance out of OpenGL / LWJGL to render this at a good speed (100FPS+).
Things to check:
Make sure you are clipping to only deisplay the visible set of tiles (According to the screen width and height and the player's position)
Make sure the code to draw each tile is fast... ideally you should be drawing just one textured square for each tile. In particular, you shouldn't be doing any complex operations on a per-tile basis in your rendering code.
If you're clever, you can draw multiple tiles in one OpenGL call with VBOs / clever use of texture coordinates etc. But this is probably unnecessary for a tile-based game.

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...................

How can I split up paint swing method in java?

I'm developing a fair sized hospital simulation game in java.
Right now, my pain method is starting to look a little big, and I need a way to split it up into different sections...
I have an idea, but I'm not sure if this is the best way.
It starts by painting the grass, then the hospital building, then any buildings, then people, then any building previews when building. The grass and hospital building will not change, so I only need to paint this once. The buildings themselves won't change very often, only when new ones are built.
I was thinking, use boolean values to determine which sections need repainting?
Ideal, id like to be able to split up the paint method, and then call each one when needed, but I'm unsure how to physically split it up.
I am still quite new to java, and learning on the go.
Thanks in advance.
Rel
Another idea is to create a super class or interface for all items that must be drawn on the screen. Lets cvall this class ScreenObject. You can then have a draw(Graphics2d g) method specified in the ScreenObject class. Next, each object that must be drawn implements the draw() method and is only concerned about drawing itself. You can even consider creating a variable that determines whether this draw method should be run at all.
In the main class that paints the screen you can have a reference to all ScreenObjects in an ArrayList and your paint() method will simply iterate over this calling draw() on each object.
I'm assuming from your description that your scene is split up into tiles. Keeping an array of booleans is a good way to keep track of which tiles need redrawn on the next update. A LinkedList might perform a little better in some situations. (I'm thinking of a Game of Life simulation where there are tons of tiles to redraw and you need to check each neighbor, so you may not need to go this route.)
Without seeing your code I can't give very specific advice on splitting up your paint method. I can tell you that in sprite animations, each sprite object typically has its own draw method that takes the main Graphics object (or more likely a buffer) as a parameter. Since the sprite should know its own image and location, it can then draw itself into the main image. Your paint method can then just loop through your list of sprites that need to be redrawn and call their draw method.
You might look to Killer Game Programming in Java for more detailed information.
Well I am not really an expert at programming but to split up my paint method Ive always just made a new method that takes a Graphics object and call that from paint, it has always helped me to keep my code organized but I have never had a big project like it sounds you are working on so it might not work for your situation.

Categories