Jump to content

  • Log In with Google      Sign In   
  • Create Account

Game Architecture/Design Pattern?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
17 replies to this topic

#1 Alejandro   Members   -  Reputation: 142

Like
2Likes
Like

Posted 20 February 2013 - 10:29 AM

Hello,

 

I want to know if there are any game architectures that are recommended, well, actually I don't know if I can call them architectures or design patterns.

 

Basically what I want to know is how do you structure your games at a logical for example I tend to the following.

 

I create an object named GameMaster, this object controls the game (enemies, ambient, etc) and knows the state of everything in the game, the control is done through Managers, for example EnemieManager, AmbientManager, etc. This managers don't communicate directly, the communication has to go throught the GameMaster.

 

In a more plactical way say we have the following:

 

class GameMaster
{
	Player player;
	EnemyManager enemyManager;
	GameStatus status;

	void update()
	{
		if(enemyManager.enemies == 0)
		{
			status = GameStatus.EndGame;
		}

		if(status == GameStatus.EndGame)
		{
			player.stopInteraction();
		}
	}

	void draw()
	{
		drawString(status);
	}
}

 

Sure, the managers can also have control of a few elements... what I see in some friends code is more like...

 

class Player
{
	GameStatus status;

	void update()
	{
		if(status == GameStatus.EndGame)
		{
			player.stopInteraction();
		}
	}
        
        void draw()
        {
                drawString(status);
        }
}

class EnemiesManager
{
	Player player;
	int enemies; 

	void update()
	{
		if(enemies == 0)
		{
			player.status = GameStatus.EndGame;
		}
	}
}

So my doubt are, what is better? what is worse? are there any architecture/patterns for structuring the objects in the videogames?.

 

I follow the GameMaster pattern because it's easier to me to structure things like this, but maybe this is not the best pattern...

 

 

Any literature on the topic is appreaciated wub.png


Edited by Alejandro, 20 February 2013 - 10:32 AM.


Sponsor:

#2 EWClay   Members   -  Reputation: 659

Like
4Likes
Like

Posted 20 February 2013 - 11:46 AM

I like this book:

http://www.gameenginebook.com/

There's a link to a sample chapter at the bottom which is quite interesting.

#3 HappyCoder   Members   -  Reputation: 2670

Like
4Likes
Like

Posted 20 February 2013 - 12:27 PM

The more general you can make the core of your game the more flexible it will be. Also, you should try to minimize what certain classes know about each other. For small game projects this usually wont become an issue but as a game grows if your design has problems it will become very difficult to if you want to do something that Let me just point out a couple of things that I would reconsider in your design.

First, when I think of design and what objects know about each other, I like to think of it as a tree. Objects only know about their branches, but branches shouldn't know what object is their parent nor should they know about their sibling branches. This cannot be the case all the time but try to follow this as much as you can. So you may have a game manager class that knows about the enemies and the player but the they don't know about the game manager class nor do they know about each other.

Keeping that in mind your end game logic is handled in your enemy manager. Keep that logic in the game class. I would add a method to the EnemyManager that checks to see if all enemies are dead and returns a boolean instead of having the game manager check the integer value directly. Classes should not know about the internal workings of each other. They shouldn't access data members directly, instead they should interact through method calls.

I wouldn't have your enemies know about the player, rather I would create an interface, perhaps you could call it EnemyTarget. Add methods to the EnemyTarget interface such as getting the target location and whatever other information you need from it and have the player implement that interface, then when you create the EnemyManager you can pass it the player class, but the enemies don't know it is the player, they just know it as their target. This adds flexibility to your game and would allow enemies to target other objects, if you later decide you want to do that. Also, avoid the temptation of setting the player state and other data in the player class, rather use the interface to send method calls to the player and have the player handle updating its damage and state, for example.

interface EnemyTarget
{
    Point getPosition();
    void applyDamage(int amount);
    // anything else applicable here
}

class Player implements EnemyTarget
{
    Point getPosition()
    {
        return position;
    }

    void applyDamage(int amount)
    {
        hitPoints -= amount;
        if (hitPoints <= 0)
           status = PlayerStatus.Dead;
    }
}

class EnemiesManager
{
    EnemyTarget target;
}
Also, don't have your player modify the GameStatus, have the player only modify its own status and have the game manager check the player status and have it determine what to do from there. This would make it easier to change the behavior when the player dies.

Another point I would like to make is to separate the code that handles drawing, from code that handles collision detection, from the code that handles the game logic. It appears you are doing a text adventure so this may not directly apply but lets say for example we have a character in our scene. Rather then having that one character class have a draw, update, and collision detection code. Break them up. Create a scene graph where you can add objects you want to draw to it and that part of the code only handles drawing the scene. Then add a collision space where you can add objects for collision detection. Then you create a player class that ties these things together. The player class creates a sprite and inserts it into the scene graph, the player creates a collision shape and adds it to the collision scene. Then whenever you update, you ask the collision space for any contacts the player is making in the scene, update accordingly, then change the position of player in the scene graph and the collision space. The details of this can vary but the important thing is that you have separate parts of code that don't know about each other meaning you could take out that subsystem and have it work independently of the rest of the code.

#4 Dan Violet Sagmiller   Members   -  Reputation: 896

Like
2Likes
Like

Posted 20 February 2013 - 03:02 PM

I think what you have is pretty good.  However, instead of making your update check specific information about how many enemies there are, I would recommend creating a statically available boolean called shutDown = false;  (or an enum for GameState)  Then what ever might decide to shut off your game can just call the variable change for it.  Your update method won't check each area for reasons to shut down then.  Instead it just checks the one value.

 

But the key issue, is performance vs maintainability.  Your engine, 3D rendering, timing handlers, etc... should be performance based.  I.e. forgo easier to maintenance architectures for architectures that employ speed.  This for instance might be to use arrays instead of dynamic lists, pointers (bark bark) instead of copies and static references instead of lookups.  The layers of code that manage logic such as AI, level details, and mob generations would be best in a more manage able code approach.  I.e. highly structured code, preferring clearly named abstraction over direct but vague variable references.  Also larger separations of object code, to help organize data, instead of compressing more code purpose into one location.  Also preferring Dynammic easy to use lists, instead of additional code required for locked array sizes.

 

I see no problem in having a split in your architectures layout, as long as it is easy to distinguish where one stops and the other begins.  If your using an existing engine, like XNA, Unity, DirectX even, then you'll probably want all your code to be a logic oriented architecture (more maintainable)

 

That being said, I typically create an interface called "IModifier" (having .Modify()) and another called and "IPaintable". (having .Paint(View/Paint Object reference))

Then my main class will have a List<IModifier> Modifiers.  My update method does any generic things it needs to, like initializing the mouse coordinate variable, or keyboard variables, but then just calls ForEach(IModifier mod in Modifiers) mod.Modify();

And of course having a second loop that removes any objects marked for removal  (either another static list, or a flag on each game object to mark them for deletion)

 

I'll usualyl wrap that code up into a layer to manage its own cleanup.

 

The IModifable/IPaintable interfaces are a form of an Object Based Decorator Pattern.  Which I've found highly useful.  I typically create different Lists for managing different sets of objects, like playershots, enemy shots, enemies, stars, etc...  Then each object also gets a List inside for all its modifiers.  Modifiers would include things like friction, reactToMoustMovement, Gravity, TakeImpactFromEnemyShots, TakeImpactFromPlayerShots, etc...   Anytime I create an object, I simply create a generic GameOBject, set the image and position, and other variables, then apply a bunch of decorators to do what ever things it needs to.  Makes for something inredibly easy to manage.  

 

 

I'll also say that I'm sure there are many architectures that can work, I think the key is learning which to apply for your case that won't damage your performance.  Don't look for one perfect architecture.  Look for options, and figure out in what circumstances each work.  

 

I recommend looking through this to start out: Wikipedia's Software Design Pattern's List (the list is a page or two down, and broken apart a bit)


Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

My Game(s), Warp Wars is in early development and can be found here: http://blog.WarpWars.Net.


#5 Nercury   Crossbones+   -  Reputation: 770

Like
2Likes
Like

Posted 20 February 2013 - 03:38 PM

I "found" another way to look at variables: instead of imagining them as container, I think of them as things that change how my functions behave.

 

So instead of focusing on making variables accessible, think of them as evil/good things that can influence behavior of your code.

Think of function arguments as a scope for something to happen. Think of different arguments as another scope for something else to happen.

Think of a class as an environment which changes how ALL functions in it behave.

 

I found that thinking this way helps to keep number of available variables for my code to minimum, because I start thinking more about the reasons I am introducing yet another field for class. Do all functions inside REALLY need to know about it? Maybe passing it as parameter when actually needed is just cleaner.

 

The main principle one should follow is separation of concerns. Think of controller/view/model - separating concerns of getting data, displaying data, and data itself.

However, design patterns are just ways to organize the code and communicate this organization. Never try to fit something into a design pattern, that often does not work by the book :). Most likely it needs adjustments for your project.



#6 Alejandro   Members   -  Reputation: 142

Like
0Likes
Like

Posted 21 February 2013 - 12:32 AM

Thank you very mucho for all your comments, I liked the idea on Performance vs Maintainability, also because a lot of the code I do is also read by other team members so it's important to have maintanable code

 

I'll take a look at the Game Engine book

 

Until know there's no clear best one, it appears as everyone has different approaches, that's what I am searching, how people create the architecture of the code.

 

Does anyone has an example on how MVC pattern will work in a videogame? particulary on Unity blink.png



#7 Nercury   Crossbones+   -  Reputation: 770

Like
0Likes
Like

Posted 21 February 2013 - 01:52 AM

Thank you very mucho for all your comments, I liked the idea on Performance vs Maintainability, also because a lot of the code I do is also read by other team members so it's important to have maintanable code

 

I'll take a look at the Game Engine book

 

Until know there's no clear best one, it appears as everyone has different approaches, that's what I am searching, how people create the architecture of the code.

 

Does anyone has an example on how MVC pattern will work in a videogame? particulary on Unity blink.png

 

No idea about unity, but:

- You can think about your game state Update function as Controller.

- You can think of your Draw as View.

- You can think of your game objects as Model.

 

The main point here is to never Draw from Controller or Model, never Update game state from View, keeping game-state related things only in Model.

Separation of Concerns.


Edited by Nercury, 21 February 2013 - 01:55 AM.


#8 Dan Violet Sagmiller   Members   -  Reputation: 896

Like
0Likes
Like

Posted 21 February 2013 - 07:41 AM

You can think about your game state Update function as Controller.

 

Update functions, and components in general in most cases.  

 

 

Does anyone has an example on how MVC pattern will work in a videogame? particulary on Unity

 

The MVC pattern is good for games, but I tend to find a stronger blur between Model and Controller.  Separating the code is good, and I'll do that in most things I do, but I'm not going to let MVC stand as a permanent requirement, when sometimes it just makes more sense to have some data and logic floating intermingled for performance needs.  I.e. if you keep the MVC model, would typically require an impact controller to loop through all the game objects for collisions with particular objects.  But then you also have Momentum controllers, AI controllers, gravity controllers, etc...  Each one needing to loop through your gameobject list to make changes.  Or, you could blur the Model-Controller, and add an update function to the game object that takes care of all the same logic, but this structure requires only one loop through the game objects.  

 

MVC is good, but games some times need more efficiency.  

 

(I should include that I certainly think MVC is possible in game development, and that it can be done elegantly in many situations.  For a web app or forms app, I will typically impliment MVC, MVVM or a similar model.  For games, while while still defaulting to MVC, I just don't lock myself to it.  I don't step away from it without good reason either)


Edited by Dan Violet Sagmiller, 21 February 2013 - 07:55 AM.

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

My Game(s), Warp Wars is in early development and can be found here: http://blog.WarpWars.Net.


#9 larspensjo   Members   -  Reputation: 1541

Like
0Likes
Like

Posted 21 February 2013 - 07:47 AM

- You can think about your game state Update function as Controller.
- You can think of your Draw as View.
- You can think of your game objects as Model.

 

I agree, but maybe with a little twist:

- The Controller handles all input from keyboard, mouse, timers and OS signals.

- The Model knows about the game state and all objects in it. It is not real-time. It has input functions called by the Controller that will trig actions and update the time.

- The View asks the Model about its state, and draws it accordingly. The View will also take orders from the Controller, e.g. toggling between first person and third person or showing/disabling a chat window.


Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#10 Dan Violet Sagmiller   Members   -  Reputation: 896

Like
1Likes
Like

Posted 21 February 2013 - 10:38 AM

The Controller handles all input from keyboard, mouse, timers and OS signals.

 

Typically the controller is also the place for handling all logic.  If you look at the MVC Wiki page, it shows the Controller as manipulating the model.

 

 

The Model knows about the game state and all objects in it. It is not real-time. It has input functions called by the Controller that will trig actions and update the time.

 

'real-time' has to do with the total time it takes for something to get back to the user in a way that they don't perceive a lag between their interactions and what they see, including all model changes.  I can't think of a game where the MVC as a whole is not in real time, unless your talking about a save/load button, or the start of a level.  But typically once going, the model/controller/view all act as one real-time responsive unit.

 

The View asks the Model about its state, and draws it accordingly.  The View will also take orders from the Controller, e.g. toggling between first person and third person or showing/disabling a chat window.

 

Your right about the view asking the model for the state, but typically the toggling between 1st/3rd Person Perspectives would also be stored as model data.  You should see the controller as the implementer of change, not as a constant updater of things that aren't changing.  I.e. something happens and the controller will change the state, view state being included in the model.


Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

My Game(s), Warp Wars is in early development and can be found here: http://blog.WarpWars.Net.


#11 larspensjo   Members   -  Reputation: 1541

Like
1Likes
Like

Posted 22 February 2013 - 01:10 AM

Typically the controller is also the place for handling all logic.

The concept "all logic" is quite wide. So I must state I disagree with your statement, as much of the game logic goes into the model. This statement does not help anyone how to implement a MVC pattern.

 

I can't think of a game where the MVC as a whole is not in real time

 

As a whole, usually, yes. But, I would argue that the Model isn't real-time. The View will need to know about FPS, and have the responsibility of making sure the player get feed back in real time. And the Controller definitely has real time requirements, even for turned based games (laggy mouse responses can kill any game).

 

The model will need to know about time, that is usually the case. Especially if it manages physical modelling. But it is enough to have an input function to the Model where it is told the current time, or the delta time since last call. For example, it will be possible to slow a game to slow motion by simply giving a down scaled time to the Model. The Model doesn't need to know that the game is currently in slow motion mode. Thus, the Model should not be concerned about real-time requirements. And the Model should usually not have to care about the CPU power.

 

Of course, there are complications depending on what type of game it is. The model must not use too much CPU, or the View and Controller may no longer fulfill the requirements. Some games, like chess, may have a complicated relation to time. That is, the model is allowed to use a limited real time to find the next move. But even in that case, I would delegate the real-time responsibility to outside of the Model.

 

typically the toggling between 1st/3rd Person Perspectives would also be stored as model data.

I disagree again. This is a typical example where the Model should not be involved. However, the Model will need to support the View with information needed to show data in both 1:st person and 3:rd person, but the Model shall not know, or care, whether the game is currently in any of these specific modes. There are always exceptions, of course.


Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#12 Rakilonn   Members   -  Reputation: 421

Like
1Likes
Like

Posted 22 February 2013 - 02:29 AM

I think it's worth to mention the component based architecture which is quite attractive.

Basically it says that your main classes are containers of components and components are behaviors or features (like "Render", "Collide", "Controllable").

It's a way to avoid the duplication problem of the inheritance and big base classes.

 

However even if it solves the problem of the inheritance, it brings new problem (as the communication between components) but at least your code is more independent and intuitive.

 

A very nice article:

http://gameprogrammingpatterns.com/component.html

 

and also:

 

http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy

 

http://en.wikipedia.org/wiki/Composition_over_inheritance

 

Also please note that there are many different ways to implement this solution but the idea stays the same : you create some components which represent behaviors or features and you create your final object by assembling the components you need.


Edited by Rakilonn, 22 February 2013 - 02:32 AM.


#13 Kylotan   Moderators   -  Reputation: 3338

Like
6Likes
Like

Posted 22 February 2013 - 06:01 AM


The Controller handles all input from keyboard, mouse, timers and OS signals.

 
Typically the controller is also the place for handling all logic.  If you look at the MVC Wiki page, it shows the Controller as manipulating the model.


This is because the meaning of the controller has become lost over time.

Originally the controller was just the input handling part of the GUI - it would take input information and send it to the model, which performs the processing and changes its state. Then the view needs to be updated (perhaps notified by the controller that it needs to refresh) and that pulls the current state from the model.

Somewhere along the line people started treating the model as merely data and pushing more of the burden for changing the model into the controller, to the point where the controller is seen as the mediator between the data and the presentation. But that was not what MVC was intended to mean, nor how it was intended to be implemented. The idea is that both the controller and the view are interchangeable with other controllers and views, and the model encapsulates all the business logic and data without worrying about how it is getting its input or how it presents its output.

It's also worth noting that there can be multiple levels of 'model' in an app. The game data may constitute a model, with its own controller and view attached. But that view itself may contain its own model (eg. current position of objects on screen) which is maintained separately from its own presentation data. So it's important not to fall into the trap of dividing the app into 3 parts and wrongly merge unrelated things together, when really it's more about separating input and output from logic.

#14 Alejandro   Members   -  Reputation: 142

Like
0Likes
Like

Posted 30 March 2013 - 01:08 PM

As i see, there's no best pattern... though I like to use managers since it's easier to me to read the code like this.



#15 LorenzoGatti   Crossbones+   -  Reputation: 2709

Like
0Likes
Like

Posted 31 March 2013 - 03:01 PM

Your "managers" and GameMaster appear to be a rather arbitrary partitioning of game state, which can only cause needless and burdensome complications (for example, storing the GameStatus in two or more places and checking it redundantly).
 
Classes like EnemiesManager are inappropriate because using objects makes little sense:
  • There can be only one: no need to isolate different instances. On the other hand, game entities, like the individual enemies, could be objects (other sensible options exist).
  • There are no alternative implementations of a common interface; you are simply ripping out of GameMaster a part of the game logic that deals with enemies. Meaningful interfaces with (at least potentially) different implementation often include the "brains" of game entities (AI, user input and replay systems could control the exact same unit) or rendering (once you know what you need to draw, you can draw it in different ways).

Produci, consuma, crepa

#16 ApochPiQ   Moderators   -  Reputation: 15824

Like
2Likes
Like

Posted 31 March 2013 - 03:14 PM

You're all doing it wrong.

 

 

 

Design patterns and architectures are descriptions of how problems can be solved. They emphatically are not prescriptions of how to solve those problems in all future cases.

 

As soon as you start thinking of "the" design for some software, you have failed as a designer, architect, and engineer. There is no "the one right design" - ever. Even after you are done with your code, there is only "how I did it" versus "many other ways it could have been done."

 

 

Do not fall into the trap of exclusively and blindly using design habits, principles, patterns, guidelines, suggestions, recommendations, or anything else. Do not reach for some off-the-shelf solution to every design problem.

 

 

Use your brain and think about how best to solve the unique problem you are currently facing. Otherwise, you're not doing your job. Being lazy with your solutions will bite you eventually. Resist the urge to get stuck in a design rut.

 

 

 

In short: your question is broken. Un-ask it.



#17 Kylotan   Moderators   -  Reputation: 3338

Like
2Likes
Like

Posted 02 April 2013 - 03:25 PM

To be fair, I think "how do you structure your games" is a reasonable question, as is "are there any architecture/patterns for structuring the objects", because patterns would help describe the structure. I don't think it's true that overall game structure is a unique problem that needs every individual to work out independently how to solve it.



#18 ApochPiQ   Moderators   -  Reputation: 15824

Like
0Likes
Like

Posted 02 April 2013 - 08:28 PM

I'm not saying there's no value in studying other people's solutions; I'm saying that just lifting someone else's approach wholesale into an arbitrary new project is a recipe for disaster.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS