Model-View-Controller (MVC) in Games

MVC is a useful way to develop games in a way that keeps the code portable and organized.

Lets define the components to the MVC design pattern with respect to games:

Model : the state of an object in the game
View : the visible representation of the model
Controller : the behavior of a model, modifies the state of an object

Simple enough!

So why is this cool? Your Model classes are completely portable, decoupled from a graphics library. The Views are the only classes aware of the graphics library, so for each graphics library you have View implementations for every Model type in your game. The portability of controllers is entirely dependent on the purpose of the controller. A controller could be for AI (portable), or could be for user input (not so portable).

So, how can we represent these as interfaces?


public interface Model {
   public void update( UpdateState state );
   public void draw( DrawState state );
   public int getController();
   public int getView();
}
public interface View<M> {
   public void draw( M model, DrawState state );
}
public interface Controller<M> {
   public void update( M model, UpdateState state );
}

And the all important registries:


public class ViewRegistry {
    private static int nextId = 0;
    private static View[] views = new View[128];
    public static int newView() {
      return nextId++;
    }
    public static void setView(int id, View view) {
      views[id] = view;
    }
    public <M extends Model> static View<M> getView(int id) {
      return (View<M>)views[id];
    }
}

public class ControllerRegistry {
    private static int nextId = 0;
    private static Controller[] controllers = new Controller[128];
    public static int newController() {
      return nextId++;
    }
    public static void setController(int id, Controller controller) {
      controllers[id] = controller;
    }
    public <M extends Model> static Controller<M> getController(int id) {
      return (Controller<M>)controllers[id];
    }
}

Not too bad, lets create the BaseModel class to tie some things together before further explanation


public class BaseModel implements Model
{
   public void update( UpdateState state ) {
     ControllerRegistry.getController( getController() ).update( this, state );
   }
   public void draw( DrawState state ) {
     ViewRegistry.getView( getView() ).draw( this, state );
   }
}

Cool! Now lets explain…

Essentially when a model is being drawn, it gets the View from the ViewRegistry, and the view actually handles the drawing. So why have the draw method in the Model code? In case the implementing class has custom drawing code!

This logic also applies to the controller.

So when you start your game, you register all your views so your models can be drawn and register your controllers so your models can be updated.

Lets look at an example:


public class Sprite extends BaseModel {
   public static final int VIEW = ViewRegistry.newView();
   public static final int CONTROLLER = ControllerRegistry.newController();   

   public float x, y, velx, vely;
   public float w, h;
   
   public int getView() {
     return VIEW;
   }
   public int getController() {
     return CONTROLLER;
   }
}
public class SpriteView implements View<Sprite> {
   public void draw( Sprite model, DrawState state ) { 
     // draw sprite here
   }
}
public class SpriteController implements Controller<Sprite> {
   public void update( Sprite model, UpdateState state ) {
     model.x += model.vx * state.dt;
     model.y += model.vy * state.dt;
   }
}

// Before the game starts
ViewRegistry.setView( Sprite.VIEW, new SpriteView() );
ControllerRegistry.setController( Sprite.CONTROLLER, new SpriteController() );

Well look at that!

Now you can create a SpriteView for LWJGL, JOGL, Java2D, Java3D, etc.

A few things you could do:

  • The model implementation could return a class level variable view/controller so sprites could have different views depending on their state or purpose.
  • Create a generic PhysicsModel with position, velocity, and acceleration getters, and all you need is one PhysicsController and anything that implements PhysicsModel could use it! (Sprite, ParticleSystem, etc)

A note: Controllers could be morphed into components, so Models can have multiple components opposed to one (a controller for physics, a controller for spatial database, a controller for steering behaviors, etc).

I hope this pattern encourages you to design your game for portability whether you plan on porting or not!

I find this design to be deeply confused, with redundant responsibilities between layers such as View’s draw method depending on a Model passed in, a draw method on the Model itself, and above all no concept of model change listeners. It doesn’t resemble MVC in any definition I would give it.

Other than the format itself, which I’ve bitched long and often enough about, another problem I have with this particular sub-forum is that the pages in here take on some kind of air of authority … in large part due to the format.

For more reference, Mario’s MVC design.

Some comments (there are too many MVC variants, so I just give my own opinion)

Usually events are delivered to the view class by the OS or runtime, because that’s the only OS dependant component in this pattern. The view should transform the OS/runtime events to logic events and forward them to the controller.

I don’t think the model should know the controller. Information flow:

model >---update---> view

view >---events---> controller

controller >---modify---> model


Also, make the view an interface to have a better separation of game data and display logic.

Model change listeners are bothersome to manage, and in my opinion not necessary when it comes to games (I’ve used the passive approach opposed to the active). My views and controllers are simple and straightforward, pass in a model and draw it or update it. I like the idea of saving memory by sharing view instances between models. MVC is a fairly open ended pattern and the way I use is acceptable, you are expecting me to use it the way you’ve seen it before, which is typical.

I agree with the draw method on the Model itself, but it’s a nice shortcut when your managing a list of Model’s to just iterate the list and call draw on it.

Having said that, this is still an incomplete tutorial… I have a few things added in my implementation. I didn’t mean for this to be an all encompassing tutorial which babies you through all of the necessary code to make it efficient - that’s something I’ll do at a later date I’m sure. Other things I do:

  • Add activate() and deactivate() to View interface. When getView is invoked in ViewRegistry, if the request view was the last one to be gotten, do nothing. If the request view is different then deactivate the previous and activate the requested view. (helps you do things like batch drawing by design). At the end of a frame you need to deactivate the last view and clear that variable so the first view on the next frame is activated.
  • Create a ViewData interface that the model has reference to. This is passed to the View via the model. When a model is created it calls allocData() : ViewData on the View and saves it until the view changes or the model is removed from the game (which calls freeData(ViewData)). This really helps when implementing views for a GL like OpenGL which has view data like ID’s and other state information.

From:

Also, why do you use global registries in your example? I find it kind of obscure, since one cannot see in the example what the methods do. And it’s inflexible becuase you reference them through the class name, and not an instance, so you can’t use interfaces there to abstract interface from implementation.

This approach honestly has nothing to do with MVC, except that you have classes named Model, View and Controller.

[quote]I didn’t mean for this to be an all encompassing tutorial which babies you through all of the necessary code to make it efficient - that’s something I’ll do at a later date I’m sure.
[/quote]
The condescending attitude is a bit of a disappointment.

My implementation is as passive as it gets, I don’t value the point in communicating actively between the components. My communication occurs per frame by passing in the model to the View/Controller. This is how I communicate a change in state, since in a Game you draw/update your Model every frame anywho.

The whole point to the global registries is so the graphics library you choose can hook into the game by registering a view implementation to a view ID.

No abstraction necessary, not sure what you’re getting at here. If you could provide a counter-code example perhaps as to why this is bad design?

You could be right, and maybe I’ve stretched it too far… I still think I’m well within the boundaries of calling this a passive MVC implementation. Otherwise I guess I should further develop this article and call the pattern something else to avoid future confusion.

I guess I should clearly define the purpose of said tutorial so I can establish expectations for the readers, my apologies.

if you want your view implementation to inherit from class A and still be a view, you can only do it if the view is defined as interface


public class RichSpecialView 
    extends MyBaseClass
    implements ViewInterface
{

}

You can get around it by using delegates, but I still think the view should be an interface rather than a base class.

Also, I would make the registries objects. Maybe some day you want a model to register with two different view types at the same time, then you can only do that if they are instances, and not classes. Well you can, but you must refer them by name, and can’t pass another registry type than the ones known at compile time. It works, but you lose the benefit of OOD here, and it’s a rigid design which limits the re-usability of the code. Re-use is something that triggered the whole pattern idea (patterns came from reverse engineering existing systems while searching for common (aka re-usable) designs/modules. Making such a design tightly linked to components (by referring to their names directly) contradicts the pattern idea - you don’t provide a pattern anymore, but a framework (and a rigid one instead of a flexible one at that).

This is a pretty valid approach actually, and passing in models is the essence of what web apps call “MVC” – but I’ve never been comfortable calling those MVC either. Sun agreed and started calling it “Model-2” instead, but the term never caught on. Anyway, that still doesn’t allow for view-specific logic on Model, because Controller is supposed to mediate in such a design so it can transform the model appropriately, and Model remains ignorant at all times of how it’s used.

I’m still not convinced at MVC’s use in games. Except maybe for dialogs, game UIs just dont seem to be candidates for role separation of content from presentation. Maybe if you were to show something like minesweeper using this design?

I was just about to say: why? I can’t see that it addresses any concern.

I guess I should clearly define the intended purpose of the View class next time, it is merely used for rendering a model and nothing else! If it extends another class, it better be a view. The whole point of the view is to decouple the graphics library you’re using from the game code.

Perhaps, but we’re falling into the argument “maybe you’ll want to do this!” which is a never ending argument that always leads to more and more code to decouple everything from everything… the more this happens the more we sacrifice efficiency and readability. As much as I like to lie to myself, there is no perfect design that can encompass everyone’s needs or desires.

Other than that, there is only ONE reason I can envision more than one view type… if you are rendering to a stencil buffer, or for picking, or reflection/refraction effects, etc. I could agree with you then, so this is something I’ll think about incorporating in some manner. I can’t imagine why you would want to draw the same Model in the same position two different ways, sounds like you need to combine them into one view implementation! (or maybe have chained view rendering or w/e).

This can be a pattern and a framework, for one is theory and the other is implementation.

This is also as decoupled as needed, my model has no concept of what’s drawing it or what’s controlling it other than these IDs it has which are merely used to hook an implementation in. I could be using Java2D, LWJGL, a mouse, a joystick, etc. I don’t know how you’re considering any of this coupled.

The active MVC pattern I don’t think has a use in games, then again I could be making up what I think to be a “passive MVC implementation” when really it’s something slightly different.

I think using MVC for minesweeper is overkill, I never like putting patterns in things that don’t require them =P Although I’m sure you agree, but it would be a game type that could use MVC “properly”

If you’re talking this pattern, it addresses the concern of separating your game logic from the graphics library you’re using. We need this separation when we want to network the game or port it over to another system easily.

I suggested minesweeper because it’s a trivial game that could fit on the pastebin. If you have another example, feel free – perhaps something in Haxel uses it? A design without a sample is a solution looking for a problem.

If this is MVC, then libgdx’s setup can be called an MVVM implementation as well, with WorldRenderer being View, the different Screen’s as ViewModels, and then you have your entities on the side as Model.

They’re just patterns. You’re free to shape them to your will, as long as you keep the fundamentals correct. With the MVC pattern being described in different ways by different people, and with its very basic structure, it is an easy target for vandalism. The implementation displayed here is more or less legit, though not a clean one.

I can only kinda repeat what the others said: this is not a MVC design where controller knows model and view, and views their model, but giving relations from model to view and controller kills the whole MVC concept with its clear responsibilties.

Maybe what you actually want to have is just a sprite class with a rendering delegate to be able to work for Java2d, OpenGL, etc.
If you need custom drawing code, inherit from those delegate to add it there but it does not belong into the model.

[quote=“ClickerMonkey,post:12,topic:40768”]
MVC isn’t the right pattern for that. You want to look into the bridge pattern rather in that case:

It allows to decouple your game from OS/runtime/library specific code and exchange the concrete implementation easily while your game code remains completely unchanged.

I don’t like the bridge pattern it seems like the user has to pass in the implementation they want, which I don’t want. They should just create a circle and based on the platform/graphics library specified at startup it knows exactly what implementation to use (hence the ViewRegistry).

I’m still going to stick firmly in the dependency injection camp. This allows you to separate functionality into services (thus divorcing engine or even object-specific logic from business logic). After converting my game over to fully implement the DI and repository patterns, adding things is no longer difficult (difficulty of n instead of n^n). MVC is very useful when it comes to business web apps, I find it is a bit tedious and verbose for the linear nature of games though.

Well, the MVC method is quite interesting. However, applying it to games is very challenging. The biggest problem is that 2 of the main parts of the MVC, the view and the controller, is bound to the programming language that it is in. The portability is only able to be applied to the model, and for small games, the model is usually only a few hard coded objects.

I think it may have an application to bigger projects; If you are able to represent your object data in text files. You read the model text files into the viewer, and have the controller act upon the model. You will be able to have a… well… slightly similar function that MVC requires. The problem is that updates to the model need to be instant in order for games to run fluently. So, the model will still need to be stored in 2 places (in the text files, and in RAM).

All-in-all, it seems that the MVC model is really not too portable. It might be a good way to organize code, but the controller and the viewer is bound to the API. This means it’ll eventually be a lot of work to port code as you’ll have to rewrite it for each system. It is the same thing as writing the same game over and over again for C, C++, Java, Python…

Pretty good for organization, but definitely can’t see it being a portable time saver.

I guess you’re missing the point then, most of the code in a game is logic, math, data, structure, etc. A small percent is actual rendering and handling input (in my experience at least). This enables all the above mentioned code portable, and the only parts you need to port over are the graphics and input.

I’m not using portable in the sense that you don’t need to convert code, because you do, I’m just saying if you need to convert to a different language you don’t have the graphics and input code embedded in with the rest of the game. Yes if you completely convert over to another language you need to convert everything. Keeping everything decoupled in this sense does make it easier!