MVC LUA GUI FTW!!!

Wednesday, February 20, 2008

This is a more technical post but don't run away!

When designing a game (or any application) we tend to want to separate the graphical user interface (GUI) from the game logic. A way of doing this is called Model-View-Controller (or MVC). Here is a summery of what this means:

MODEL: This is the code and data that controls your game. An example could be setting the color of the player.
VIEW: This is your GUI. An example is a GUI widget to select a color and a button to apply that color to the player.
CONTROLLER: This is what ties the MODEL and the VIEW together. It is some logic that takes the color selected from the GUI and applies it to the Player in game.

The reason for doing this is that is separates the MODEL from the VIEW. This means we can easily change the VIEW without changing the MODEL and vice versa by only changing the CONTROLLER. And most the time we don't even need to change the CONTROLLER.

Here is the way I am handling this:
MODEL: In C++ I have code that sets a player's color Player::SetColor(colorVal)
VIEW: Using Navi, we have created a simple GUI to pick a color. This has some code in JavaScript that gets called when you change the color which sends an event telling us the color has changed and what color it changed to.
CONTROLLER: This is where Lua comes into play. Lua is the CONTROLLER that receives this event from the VIEW. The Lua code calls the C++ code Player::SetColor(colorVal) with the color from the event. This modifies the MODEL which changes the color of the player on screen.

It might seem complicated but it actually simplified things greatly and allows us to change one aspect of the game without affecting other things.

3 comments:

Gorion said...

MVC is one of the best practices you really always should apply. It makes your job allot easier :D.

Brian Cronin said...

I agree. I believe that a separation between all game systems is important. Whether you use MVC or not.

The GUI shouldn't have to know anything about how the game sets the color of a hat in the same way that the physics engine shouldn't know how a position gets sent over the network.

The next post I am going to write will deal with abstract communication between different game systems/objects.

Anonymous said...

We use pretty much the same model for our game and it has worked out great.. of course instead of lua we use actionscript but it has allowed us to be rather flexible.

One of the nice thing about MVC is you can change the Model and Controller with out really ever having to change the view... as long as the interface is the same which really makes things less of a pain in the ass.