Java MVC - How to Divide a Done Text Game into MVC

Java MVC - How to divide a done text game into MVC?

Your game model can have more than one view: a GUI view, a console view, a status view, etc. Typically each view arranges to listen for changes in the model, and it then queries the model for the information it needs to render it's particular view. This simple game was designed specifically to illustrate the concepts. The section named "Design" elaborates in more detail.

Addendum: This outline corresponds roughly to this architecture, symbolized below.

MVC diagram

public class MVCOutline {

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
//@Override
public void run() {
new MVCOutline().create();
}
});
}

private void create() {
JFrame f = new JFrame("MVC Outline");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MainPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

class MainPanel extends JPanel {

public MainPanel() {
super(new BorderLayout());
Model model = new Model();
View view = new View(model);
Control control = new Control(model, view);
this.add(view, BorderLayout.CENTER);
this.add(control, BorderLayout.WEST);
}
}

class Control extends JPanel implements ... {

private Model model;
private View view;

public Control(Model model, View view) {
this.model = model;
this.view = view;
}
}

class View extends JPanel implements Observer {

private Model model;

public View(Model model) {
this.model = model;
model.addObserver(this);
}

public void update(Observable o, Object arg) {
// update GUI based on model
}
}

class Model extends Observable {

public void next() {
this.notifyObservers(...);
}
}

How can you organize the code for a game to fit the MVC pattern?

It might help you to think of the Model as a kind of game API. What would your game be reduced to if there were no UI at all for the game ordained from the beginning? You mention that what you have in mind is an RPG, so in this case you can imagine having the player character, his/her inventory, spells, abilities, NPCs, and even things like the map and combat rules all being part of the model. It is like the rules and pieces of Monopoly without the specifics of how the final game displays that or how the user is going to interact with it. It is like Quake as an abstract set of 3D objects moving through a level with things like intersection and collision calculated but no rendering, shadows, or sound effects.

By putting all of those into the model the game itself is now UI agnostic. It could be hooked to an ASCII text interface like Rogue games have, or a command line UI akin to Zork, or a web based, or 3D UI. Some of those UIs might be a terrible fit depending upon the game mechanics, but they would all be possible.

The View layer is the UI dependent layer. It reflects the specific choice of UI you went with and will be very much dedicated to that technology. It might be responsible for reading the state of the model and drawing it in 3D, ASCII, or images and HTML for a web page. It is also responsible for displaying any control mechanisms the player needs to use to interact with the game.

The Controller layer is the glue between the two. It should never have any of the actual game logic in it, nor should it be responsible for driving the View layer. Instead it should translate actions taken in the View layer (clicking on buttons, clicking on areas of the screen, joystick actions, whatever) into actions taken on the model. For example, dropping an item, attacking an NPC, whatever. It is also responsible for gathering up data and doing any conversion or processing to make it easier for the View layer to display it.

Now, the way I've described it above is as though there is a very distinct event sequence driving the game that is probably only really appropriate for a web game. That's because that's what I've spent my time on lately. In a game which is not driven by a user's request and a server's response like the web (e.g. a game running on the user's machine) you would probably want to make sure that the Model layer implemented the Observer pattern well. For example, if actions take place in the Model because time is passing then you might not want to have the View layer constantly polling the Model for updates. Instead by using the Observer pattern the Model could notify any observers of changes to Model objects as they happen. That could in turn be used to prompt immediate update to the View to reflect the change.

Then if 60 seconds passing resulted in some repairs happening for the player's base, the base could effect the repairs and immediately notify any Observers attached to it that the base has updated. The View could be attached as an Observer and note that it needs to re-display the base because its state has changed. The notification itself might have included enough information to update the View or it might have to turn around and consult the model in order to update, but the result will be the same.

App design to MVC pattern

First of all, let's start by saying what actually MVC is:

Model

It's an abstraction layer that contain a lot of classes to deal with application logic. And since then its an abstracted concern, that means, the are no strict rules of a Model definition until its scoped in business logic

View

A view should read data from a Model directly and prepare an output. For each model there should be singular view.

Controller

Also known as Editor, its responsible for changing state of a Model, that means it should only be responsible for defining/re-defining common variables you are dealing with.

If your application satisfies something like this,

- A controller writes to either a Model or a View and does nothing else

- A view contains only display logic

- A model consist of application core classes

Then you are on the right track - you are applying MVC correctly.

An example of basic implementation,

class ModelLayer
{
public void ModelLayer()
{
this.age = 1;
}

public int getAgeFromDb()
{
return this.age;
}

public void setAge(int age)
{
this.age = age;
}
}

class View
{
public void View(ModelLayer modelLayer)
{
this.modelLayer = modelLayer;
}

public string render()
{
return this.modelLayer.getAgeFromDb();
}
}

class Controller
{
public void Controller(ModelLayer modelLayer)
{
this.modelLayer = modelLayer;
}

public void onSaveBtnClick()
{
this.modelLayer.setAge(2);
}
}

MVC, and adding listeners to JPanels that are contained in other Componenets

As noted here, "not every interaction needs to pass through your application's controller." Your approach is not wrong, but it may scale poorly. Consider using Action to encapsulate functionality, as suggested here. In a database context, this simple example creates an Action that adds a query result tab to a JTabbedPane. This more elaborate example uses a SwingWorker to query a database in the background; a corresponding Action might instantiate the worker and execute() it.

MVC Java Swing how to correctly get data from database from a view

As discussed here, "not every interaction needs to pass through your application's controller," but authentication and registration are reasonable candidates for your controller to manage. As outlined here, your controller may manipulate your data model directly, and listening views should update themselves accordingly. As shown here, Swing provides a number of ways to implement the observer pattern in order to handle such notifications. The exact details depend on how your application handles modality, but your authentication and registration dialogs can fire a suitable PropertyChangeEvent to notify listeners as needed. Examples may be found here and here.

MVC pattern: which is better? For views or controllers to create and reference the other?

As seen in this outline, the controller has the model and the view(s). Any sub-views are managed by the respective parent view. Sub-views may forward events to the parent as discussed here. There's a simple example here with more links.



Related Topics



Leave a reply



Submit