[ACCEPTED]-How can you organize the code for a game to fit the MVC pattern?-model-view-controller

Accepted answer
Score: 57

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

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

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

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

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

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

Score: 19

You're getting along there. basically, ask 13 yourself the question "which code would 12 change if I had to change some part of the 11 program?"

If it would change the way it 10 looks without changing basic data, then 9 it's in the view. If it is data that could 8 be viewed in many ways, it's the model. And 7 if it's how you play, then it's the control.

So 6 if it's whether you draw an "axe" with two 5 blades or one, it's view. If it's how many 4 hit points damage you inflict with an axe, it's 3 model. And if it's whether you swing the 2 axe by typing "s" or by right clicking, it's 1 control.

Score: 8

I feel with you I remember when I first 41 discovered MVC I tried to cram everything 40 into it. I did indeed make a game that utilized 39 MVC pattern. What I have found later though 38 was that what I did was overkill. I tried 37 to fit pretty much every single class I 36 made into one category in MVC.

What I suggest 35 is to read "Design Patterns" by the gang 34 of four. There are a lot of useful patterns 33 besides MVC. Sometimes it doesn't make any 32 sense to use MVC at all. Especially for 31 games I am not sure if MVC is such a good 30 idea. The reason being that you don't want 29 to display a game object in many different 28 ways (views), but you want to reuse a drawing 27 code for many different types of game objects.

For 26 my own 2D game engine I used the strategy pattern 25 quite actively. The game objects, like the 24 player and the monsters I called a Sprite. I let 23 the drawing of the sprite be handled by 22 a strategy pattern. That is when I called sprite.draw() I would do something 21 like this:

class Sprite {
  void draw() {
    this.view.draw(this.currentPosition, this.currentOrientation);
  }

  Point  currentPosition;    // Current position of this sprite
  double currentOrientation; // Facing angle of sprite
};

The benefit of this approach is 20 that you can share a view object between 19 several sprites. Because typically there 18 will be a lot of e.g. monsters which will 17 look the same but which will be a different 16 positions and possibly behave different.

So 15 behavior I would also use a strategy pattern 14 which would be a object which contains code 13 describing behavior. That way I can apply 12 the same behavior to several monsters at 11 different location. So each frame I would 10 call an update() function to update position orientation 9 and what monster does.

class Sprite {
  void setUpdateAction(Action action) {
    this.updateAction = action;
  }

  void update(double start_time, double delta_time)
  {
    this.prevPosition = position();  
    advance(delta_time); // Advance to next position based on current speed and orientation

    this.updateAction.execute(this, start_time, delta_time);
  }

  Action updateAction;
};

There are loads of 8 variations of this. In my current implementation 7 I have even separated out currentPosition, speed, orientation and advance() into 6 a separate object called MotionState. This is so I 5 can build a search trees of possible positions 4 and orientations when doing path searching 3 algorithms. Then I don't want to carry with 2 me information about how to behave each 1 update or how sprite should be drawn.

Score: 3

The MVC concept of centralizing user interaction 22 logic is a good model for game development.

I've 21 done a little work with Flash game development. Here is 20 an article about object pools in Flash. The 19 concept is cross-platform and may give you 18 some ideas.

You're right to be concerned 17 with all the stuff going on at one time. Depending 16 on your game design, your game loop can 15 have a lot to deal with. This is where 14 you'll learn all the dirty optimization 13 tricks, often the hard way :)

There are many 12 ways to organize your code- one option might 11 be to write a GameManager class as a Singleton. All 10 game objects tie back to it for management 9 and user interaction. The GameManager handles 8 all user input and dispatches messages to 7 its object pool. You can use interfaces 6 to define common communication patterns 5 between game objects and the GameManager.

As 4 far as performance optimization goes, threading 3 is very powerful. Asynchronous operation 2 can ensure that you're not wasting those 1 precious cycles.

Score: 1

All of your listeners and handlers need 5 to go inside the Controller class, state 4 of the objects on screen (e.g. position, color, etc.) should 3 be a part of your Model classes and whatever 2 code that is drawing things on screen will 1 be part of the View.

Score: 1

My way of thinking of MVC is as MDUC
Model
Display
User-input 14 Controller

The model contains the domain 13 model objects
The display shows the current 12 state and behaviour of the domain model 11 objects on-screen.
The user-input controller 10 handles all the user inputs.

It's exactly 9 the same pattern, but the names are just 8 ever so slightly more descriptive, so I 7 find what responsibilities each part of 6 the pattern has is clearer, and so the meaning 5 of the pattern is more memorable.

Once you 4 see that you are splitting data and model 3 operations from displaying, from the user's 2 inputs, it's easier to see where to group 1 what in your own code.

More Related questions