I'm making a Java chess game as a uni project, and I'm basically getting the move from a player using a GUI.
My game has several classes, but the main classes are the Pieces, HumanPlayer and GraphicalDisplay classes.
What I'm basically doing is, when the HumanPlayer wants to make a move, it's currently using a class called PieceController, which is using a PieceModel class and the GraphicalDisplay classes as the model and view.
The problem is that I'm having to write code to set, for example, MouseListeners to certain cells in the chess grid (contained in an two dimensional array called cellHolder) in the Model class. This is because the code that contains adding listeners to cells also change state of the data, which is then used to display the game in the GUI.
This is causing a problem. The cellHolder object is created inside the GraphicalDisplay (GUI) class, but it's also used in the model and therefore the model is using data from the view.
I can't really think of another way of doing this without having to share (or pass as an argument) the cellHolder.
Any suggestions on how to improve the current MVC design?
Check this link http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
About Design Patterns In Java this one is called "the Adapter Pattern" .. It's basically a software design pattern that allows the interface of an existing class to be used from another interface
Related
I'm working on developing a Java application for organising personal music collections that allows the user to search their digital music library with the help of textual lists displayed in a table, choose songs for playback and provide information about them i.e. something like Rekordbox (https://rekordbox.com/en/).
After conducting some research on how to design and implement such a system, I came across the Model-View-Presenter design pattern and from what I understood it is a pattern that allows flexible , reusable and test driven code to be written.
So to come to my problem:
View classes: Assume I want to have a Swing UI that consists of a JFrame which has 3 JPanels inside of it as separate view classes. i.e. MainFrameView with MenuBarView, TablePanelView, PlayerPanelView which are created inside the frame (which is a view class itself). Those panels have various Swing components inside of them such as JMenuBar, JTable, JButtons, JProgressBar.
Model classes: The two models I have are TableModel (used by the TablePanelView to display the user's music library and which stores the path to the directories of his/her songs in a List ) and PlayerModel (used by the PlayerPanelView to manipulate the the digital audio files that the user selects i.e play/pause/stop songs, fast forward etc.) The PlayerModel uses the selected by the user song directory to initialize itself.
So, my question is how can I implement the Presenter so that the different views (which use different models) are being able to communicate and share information between each other? Should I have a single Presenter to which the views talk or have a presenter for every view? If it's possible to have a single presenter how can that be achieved? If I have one Presenter for the MenuBarView, TablePanelView and PlayerPanelView and those views are contained in another view (which is the MainFrameView ) should I combine the presenters in some way, and if yes how?
If i were you I would try the MVC (Model View Control) pattern before trying MVP. It´s very similar but I would say it´s a bit easier to understand.
I wouldn´t create a own view for the MenuBar because you probably won´t create it dynamically. Just write a method in your MainFrameView where you initialize it and call that in the constructor of the MainView.
The model is a property of the item you use. Now if you want to create a Panel with a own model but also want to access the model from the MainFrameView you simply write a Getter/Setter for it. It looks like this in the MainFrameView:
public TablePanelView tpv;
public void initTablePanelView(TablePanelModel tpm){
tpv = new TablePanelView();
tpv.setModel(tpm);
}
So you can use the public methods getModel() or setModel() that you wrote in the TablePanelView to access the Model.
I hope that helped.
I have an application that is a Maths Game for kids. Since I'm in college, I've usually only had a god object for all my past projects but for this applciation I've split my code into multiple classes:
MathsGame.java: main class which initialises components and constructs and controls the UI.
DiffScreen.java: contains methods for use on the difficulty selection screen.
GameScreen.java: contains methods for use on the game screen.
EndGameScreen.java: contains methods for use on the end game screen.
MigJPanel.java: extends JPanel and sets layout to MigLayout and adds a matte border.
Each screen that the 3 XScreen classes control is simply an instance of MigJPanel and screens are switched to using a CardPanel container JPanel.
I'm wondering how I can divide my code to each class so that they are properly abstracted but I'm not entirely sure how to approach this.
Should my 3 screen classes be extending from my MigJPanel so these then can be instantiated?
So instead of having my DiffScreen, GameScreen, and EndGameScreen classes solely containing methods related to each screen which are then called from MathsGame, each screen will control itself within its own class.
If yes to the previous question, should the UI components for each screen be made inside that screen's class?
At the moment, all components for each of the three screens are created in my MathsGame constructor. This makes the connection between a screen and the class which 'controls' (I use this word very lightly at the moment) it even further apart. So each screen is just an instance of MigJPanel whose components are constructed in MathsGame. The only relation the EndGameScreen class—for example—has to the End Game screen is that when the MathsGame causes the End Game Screen to be displayed, anything done there makes a method in EndGameScreen be called from MathsGame.
I hope I explained myself well. If not, leave a comment and I'll clarify. Any help would be greatly appreciated!
Yes
Yes.
Focus on self containment and maintain areas of responsibility. It is the responsibility of each UI screen to manage it's content, no one else, in fact, you should guard against allowing unrestricted modification to these components and provide access only through managed methods indirectly (setters and getters), which allow the modification of the properties you want to be changed, and not simply providing the component via a getter, this prevents problems with people removing components you don't want removed, for example.
You could also use interfaces to maintain common functionality if required, so if the MathsGame really only wants to deal with a certain amount of the information/functionality, you can use an interface that all the other screens use which will simplify the process, as the MathsGame only needs to know about the class that implement the interface and not EVERY thing else that might be going on...as a suggestion..
Also, where should I put the code for switching between screens?
From my perspective, it's the responsibility of the MathsGame game to determine when and to which screen should be shown. What I would normally do, is provide some kind of notification process that the current screen can ask the MathsGame to switch screens, maybe via a listener or other agreeded interface. This would mean that each screen would need reference to MathsGame.
Instead of passing it (MathsGame) directly, I'd create an interface that MathsGame would implement (say NavigationController), which defined the calls/contract that each sub screen could use (nextScreen/previousScreen) for example.
Take a look at Model-View-Controller for more ideas
I am trying to create a game in java using several design patterns / principles. One of them being MVC. The situation is like this:
Model: Holds all game logic
Controller: Button interaction and list of GameElements (see code)
View: All GUI stuff including drawing.
Now, my game objects are all located under the Model, but for my drawing I've tried doing this (inside paintComponent)
ArrayList<GameElement> ge = FieldController.getElements(); // This is located under Controller
for(GameElement ge: GameElements)
{
graphics.setColor(ge.getColor());
graphics.fillRect(ge.x,ge.y,ge.width,ge.height);
}
Which works, but my question is: Where should the ArrayList of GameElements really be kept?
Is it okay to hold it in the control? Or should it be kept in the view?
I'm quite sure it should not be held in the model because then View&Model would be too tightly coupeled.
Your List<GameElement> belongs in the model. Upon notification, a listening view should decide how to render the element. In this context, the notion of loose coupling refers to the notification; the view still has to interpret what it learns from the model. In this simplified example, the model manages an abstract Piece having an attribute for color. The GUI view shown renders this attribute as an Icon having the specified color. In contrast, a text view might render the attribute as a String.
I have finished writing a Hangman game, but I want to move the hangman out of the canvas when the game is over. I create that hangman with any partition of his body. When I move the object it can move only one object at a time. How can I bunch them together?
You have to create an object of the class GCompound. This class of object allows you to create new object that can be manipulated like GOval and so. In the Stanford course, there is an example called GFace.
Probably you can refactor your code to make the whole hangman one object through the whole implementation and whenever needed make different parts visible. When the time comes to remove him, just dispose of the whole thing either by resetting them to non-visible or try making a new object I guess... If you cna post the code of your implementation I may be able to give you some more help...
I am making a knight's tour implementation in java, and currently I have everything jumbled into one giant mess of code.
I have a class called MainFrame which includes the code to solve the knights tour as well as methods for the menu, etc.
I want to create a new class called KT (for knights tour) which will contain the code for the algorithm, but I'm having lots of issues doing that.
I don't want to post code here because i dont want someone from my class copying or something, so I will just briefly explain.
In class KT, I have declared the variables, arrays, etc. I have methods such as printSolution, move, redo (the backtracking), etc.
However I am unsure how to tie in the code for the buttons (which is declared in MainFrame). For example, I have a loop in the print method that prints the correct solution on the 8x8 board. Right now I'm being asked to create a new method for the button even though I have the button in class MainFrame.
I have a KT k = new KT(); and then I'm launching MainFrame. Is that where I am doing it wrong or is it something really simple that I'm being too dumb to figure out?
tl;dr program works well when i have everything in one class, but i want to make two classes and make everything "look" nice
First of all, give your KnightTour class an actual name. Like, you know, KnightTour. If you were coding this for cash money, the next guy who had to read your code would want to punch the guy who called a class something like KT.
Think about creating this class so that you can use it from a GUI controller like your button and menu laden applet. But so that it can ALSO be used from, say, a character based application where you type commands at a prompt and have your new class evaluate those commands.
The reason I suggest this is because it will force you to create your KnightTour class so that it is PURELY the "business logic" for your app. By that I mean that your KnightTour class should not know anything about buttons, menus, GUIs, text interfaces, or anything like that. You need to think about your KnightTour class in terms of what it must accomplish.
I don't really know what KnightTour does. So I'll just throw out some ideas of what kind of functionality it might need to support. I'm assuming everything takes place on a chess board?
Get the state (occupied, unoccupied) for a given board location (x,y)
Put a chess piece (piece enumerator) on a given location (x,y)
Validate placement of a piece (piece enumerator, location x,y)
Suggest a move, returning a Suggestion object with a piece enumerator and location
Reset the board to start all over.
Now, when you push a button that says "place a piece on 5,5" then you'll handle that event in your GUI controller, and then call the "set piece" method (#2 above) to do that work. If you have a character based application, when you type "put knight at 5,5" then you'll parse that text, and then invoke #2 above. The key point is that both of those user interfaces access the same KnightTour methods to do the same work.
In the actionPerformed method of your MainFrame class just call the appropriate methods to get the solution from KT (which, by the way, I would rename to KnightsTour...readability counts).
Ideally you want all your logic (the model) broken up into sensible methods in KnightsTour, and all your display and button-handling code (the view and controller) in MainFrame. If that's difficult, it's a good sign that you need to rethink how you divided things into methods (and what you're doing with global state...which is frowned upon).
I'm sorry I can't be more specific--I'm kind of hand-tied since you didn't post code.