How to structure the game code?

Hey monkeys,

whenever I code a big project, I question myself in which class some code should be written.
I’ll try to explain my question with an example:

We have a spatial in our world. When it moves into a certain area, we want to notify the main server.
Also we want to play a sound. This sound is different depending on the score player 1 has.
This usually leads to some code like this in the control class:

[java]
mainClass.getNetworkManager().sendMessage(message);
boolean sound1 = mainClass.getStateManager().getState(GameState.class).getScoreManager().getPlayer1Score();
if (sound1) {
mainClass.getSoundManager().playSound(“sound1”);
} else {
mainClass.getSoundManager().playSound(“sound2”);
}
[/java]

I hope you see the inconveniences:

  1. I need to navigate through a lot of getters to get to the actual info I need right now.
  2. I need to pass the mainClass object to every class that does something outside its own boundaries.

It’s not like I’ve run into problems because of this, but I wondered wether there is a ‘better’ way to do it.
The whole thing seems messy since everything is using data and methods from all over the place.

Thanks for any ideas for a better approach or structure!

1 Like

If you extend (or copy and extend) Lemur’s BaseAppState you could just call getState() directly instead of all of the indirection. You also have more direct access to Application… you would rarely need to address your main class directly.

That being said, your design seems like it might be upside down as it seems to heavily mix game objects with scene graph objects… this will also lead to these issues since normally separate concerns become stretched across every class as it tries to do multiple jobs.

You don’t need to call a lot of getters and setters like that, you should use the class constructor to assign those objects to your class’ field variables, like “public MyClass(NetworkManager netManager, ScoreManager scoreManager);”
and if your class implements AppState, it will have access to the app object as well. Also, you have to avoid using if statements as much as you can, and delegate specific responsabilities to specific classes, imagine if you had hundreds of sounds, and if you manage every sound by each if statement…you would have to face big maintenance problems. It seems the Chain of Responsability design pattern is very suitable for your problem, you should take a look at it.
Btw you should study more java before your start doing games. You may also like to take a look at the good object oriented programming techniques of the Design Patterns.

1 Like
@pspeed said: If you extend (or copy and extend) Lemur's BaseAppState you could just call getState() directly instead of all of the indirection. You also have more direct access to Application... you would rarely need to address your main class directly.

That being said, your design seems like it might be upside down as it seems to heavily mix game objects with scene graph objects… this will also lead to these issues since normally separate concerns become stretched across every class as it tries to do multiple jobs.

ok, so the BaseAppState is a beginning.

I try not to mix game objects and scene graph objects too much, but sometimes some event needs to be handled through a control (or at least I think thats the best way).
I think the main issue is that most functionalities and data is distributed throughout the game. I also use ‘managers’ very much. For example I have a manager for the sound. So whenever I want to play a sound I have to call mainClass.getSoundManager().
But can one make it better?

@glaucomardano said: You don't need to call a lot of getters and setters like that, you should use the class constructor to assign those objects to your class' field variables, like "public MyClass(NetworkManager netManager, ScoreManager scoreManager);"
Yeah, I though of that, but to me it seemed even more cumbersome, since I need to assign two to four values rather than just the main class.
@glaucomardano said: Also, you have to avoid using if statements as much as you can, and delegate specific responsabilities to specific classes, imagine if you had hundreds of sounds, and if you manage every sound by each if statement....
I really don't know what you mean by this... Did you think of soundManager.playSound("someName")? I'd do that with switch...
@glaucomardano said: Btw you should study more java before your start doing games.
Ok, I have to say that is a bit vague... It's not like some message pops up "you have now learned enough java for games. congrats, level 2" Also before I program something I don't know what I need to know beforehand. I'll have to think and learn in the process.

But thanks for the links to the design patterns.
Without having looked into them that much it seems like they propose a better structure.

1- Well, it seems you have a lot of Manager, so I may ask you if you already have a Manager interface, which you could have your app class to hold a Map of managers (like it does for the states as well), and you just call: app.getManager(YourDesiredManager.class). Also, you have a state called GameState, that holds the ScoreManager, but every app state is already a game state, since app states are global states, so I wonder why you have a lot of managers instead of having them as app states as well.

2- Yes, but doing this with switch is the same as doing with if statements, it’s not a good practise. You should have for example, classes which track the player score, and depending on its score, those specific classes play specific sounds.

3- But a game is not just “something”, it’s much more than you think it is, there are a lot of concepts and techniques involved. Btw I wish you good luck :)!

And about the design patterns, you don’t need to know their names, or what they do, but they help us to think more object oriented, and avoid to have design mistakes like that.

1 Like

Hello there!

TL;DR: Model-View-Presenter and the Law of Demeter could help you out to structure your code better :slight_smile:
This posts trys to explain the two in a very simple manner:

If you are writing a “big” project, you might want to consider using the Model-View-Presenter Pattern.
(http://stackoverflow.com/questions/1317693/what-is-model-view-presenter)

To explain it very simplified, you create 3 packages: Model, Presenter, View.
Model only communicates with the Presenter, and the View only communicates with the Presenter.
Thus, the Presenter is the “communication” interface between Model and View.

What is in Model and View?
Model: Logic. The games entire logic is here. Path finding, turn logic, combat system, everything.
View: The UserInterface. All Input and Output.

Up there you sent a message to the server (Model Logic) and then play a sound (View Output)
It may seem wierd at first, but I would never ever want to code a big object oriented project or game without Model-View-Presenter.

And if you have a Server, you might want to see your project as two projects:

Client: Model-View-Presenter #1

Client-Server: Model-View-Presenter #2.
View = Client, Model = Server, Presenter = You have one Presenter on Client and one on Server.
These are your communication interfaces. In jMonkey, they will probably use spidermonkey as their backend
My team has successfully used such a nested MVP in a GWT based online project.

The other tip I would like to give you: Law of Demeter.
I didn’t know this name until now, but the law was tought to us during programming course at university:
“Only talk to your neighbours”.
This means, in OOP, to never to “ManagerA.getB().getC().doStuff()”
You import ManagerA. So you only want to use the public methods (aka the interface) of ManagerA.
Because if the methods of C are changed, you have a problem in your ManagerA class. You must make changes in many areas.
With the Law of Demeter in place, you only have to change that in the class C.

Lets say you write a method like ManagerA.doStuff(). Internally, ManagerA will simply call “getB().doStuff”.
B will only implement “getC.doStuff()”. This is a chain of responsibility and can become cluttered easily.
If this happens, look at your code structure. Is there too much distance?
Then again, we are in Java and the Java compiler cleans stuff like this up quite well.

I hope it was understandable. If not, feel free to ask and I will explain it better.
It’s hard to explain stuff to programmers I don’t know, as I do not know their background knowledge in software engineering & design patterns.
(btw this book is a gold mine if you want to learn more about design pattern, such as MVP http://www.amazon.com/Design-Patterns-Elements-Object-Oriented-ebook/dp/B000SEIBB8)

2 Likes
@glaucomardano said: Also, you have a state called GameState, that holds the ScoreManager, but every app state is already a game state, since app states are global states, so I wonder why you have a lot of managers instead of having them as app states as well.
Hm, I never thought of that. I always viewed AppStates as something you attach or enable when you need it and the Managers as something that needs to be accessible all the time. I think you may be right that those Managers should be AppStates as well.
@glaucomardano said: You should have for example, classes which track the player score, and depending on its score, those specific classes play specific sounds.
I don't know... What if I need to adjust the volume for every sound? Do I have to tell every single class that plays sounds to adjust the volume?
@glaucomardano said: 3- But a game is not just "something", it's much more than you think it is, there are a lot of concepts and techniques involved. Btw I wish you good luck :)!
Don't worry, I fully understand that there is much work and complex stuff involved and don't want to make Assassins Creed or something :wink: Last year I made a multiplayer game with procedural terrain and biomes without jME but rather with lwjgl and my own shaders. Through the development of that I got a picture of the mass and complexity involved in making games. The problem is that I learned pretty much everything on tutorials on my own whenever I needed some functionality. I never really delved into game architecture or software structure. But thanks for your help and support :wink:
@zanval88 said: If you are writing a "big" project, you might want to consider using the Model-View-Presenter Pattern.

I see how it makes sense to separate logic from user I/O and I read some descriptions of the pattern, but I still have a few questions:
1. Why exactly do we need the Presenter? If it’s just there for communication between Model and View, why can’t we call Model methods in View directly?

2. Doesn’t the pattern only move the problem? Since networking and score are essentially game logic, would I not just fall back into code like
[java]
int score = model.getScoreManager().getScore();
model.getNetworkManager().sendScore(score);
[/java]
I’d only handle I/O stuff through the View by calling the Presenter methods. The organization of the game logic wouldn’t change, would it?

3. How exactly do I integrate the scene graph with the concept? When I add a spatial to the rootNode it’s essentially output since it appears in the scene. But isn’t it game logic as well since the controls of that spatial possibly change the game even without the user doing anything?

Thanks for the infos and links!

I don’t know… What if I need to adjust the volume for every sound? Do I have to tell every single class that plays sounds to adjust the volume?

Are you talking about adjusting the volume for every sound as a whole? Doesn’t the sound manager already do it? If it doesn’t, you could store the name of every sound in a list, and whenever you set the game volume, you iterate this list, and set their volume.

tbh I don’t know wether there is a jME functionality for setting the overall volume.
It was just an example. Therefore I’ll still need some kind of overall manager for the sounds, additionally to the sounds in the classes which play them. I guess thats a viable option as well.

@glaucomardano said: Are you talking about adjusting the volume for every sound as a whole? Doesn't the sound manager already do it? If it doesn't, you could store the name of every sound in a list, and whenever you set the game volume, you iterate this list, and set their volume.

I think he has a sound manager now and someone was suggesting not having one.

Centralizing sounds is not a bad thing. The audio renderer will let you set the volume of every sound but it doesn’t let you partition them into music versus effects, etc…

@pspeed said: I think he has a sound manager now and someone was suggesting not having one.

Centralizing sounds is not a bad thing. The audio renderer will let you set the volume of every sound but it doesn’t let you partition them into music versus effects, etc…

I thought @glaucomardano suggested it by saying he would let every class play its sounds directly.

Yes, since every sound is played according to the player score, it would remove the if statements. About the sound manager, I remember that it had a bug (maybe 1 year ago), that whenever you tried to set the global volume, it didn’t work, you had to set the volume for every sound individualy (maybe it’s fixed now, I don’t know).
Edit: or you could center this functionality as @pspeed said, in a score state app (or controller), by tracking the player score, and playing sounds according to its score. Btw you have to make your classes as much small as you can, and having each class to take care of its paper.
Edit 2: Sorry, not sound manager, but audio renderer :P.

@m41q said: I thought @glaucomardano suggested it by saying he would let every class play its sounds directly.

I kinda got that also, but it contradicts all of their other advice, so, I assume they had something else in mind. What that is? No clue!

As for the sound management, if the sound if being triggered by an event with the player score, the trigger should be be managed by the ScoreManager and you should never have to call:
[java]
blah.skippy.wham.getScroeManager().getPlayer1Score()
// Or
mainClass.getSoundManager().playSound(“soundX″);
[/java]

This is an interesting “principle” but essential question:

A- The pattern!!

MPV: Model View Presenter is the two way of
MVC Model View Controller; where Presenter is the middle-man, the mediator between Model and View know and get notificated by both Model and View.

worth to note:
even some part of JME3 assemble MPV, it’s not the whole!
also for a game, apply MPV is quite annoying and also tricky!

Talk about MVC first: Assume you know about web
from Wikipedia Web framework - Wikipedia
Push-based vs. pull-based

Most MVC frameworks follow a push-based architecture also called “action-based”. These frameworks use actions that do the required processing, and then “push” the data to the view layer to render the results.[5] Struts, Django, Ruby on Rails, Symfony, Yii, Spring MVC, Stripes, Play, CodeIgniter, and Struts2[6] are good examples of this architecture. An alternative to this is pull-based architecture, sometimes also called “component-based”. These frameworks start with the view layer, which can then “pull” results from multiple controllers as needed. In this architecture, multiple controllers can be involved with a single view. Lift, Tapestry, JBoss Seam, JavaServer Faces, and Wicket are examples of pull-based architectures.

MVC Push was born in the world of “none frequent” and not suite well for kind of application almost done update every-frame. So there is some kind of Event,Action embed on it.
MVC Pull in another hand, suite better for “frequent update” and assume that View is the one trigger the update call.

Back to real-time game, if you not making a chess game, almost you “are doing” a pull based MVC, or apply this pattern privately. Here is the twist: Actually in JME3, you are doing both, that’s why it look like MVP!

In JME3 we almost see the things work like this, the “almighty” Cycle:
https://wiki.jmonkeyengine.org/legacy/doku.php/jme3:advanced:update_loop

1 Input listeners respond to mouse clicks and keyboard presses – Input handling
2 Update game state:
Update overall game state – Execute Application States
User code update – Execute simpleUpdate() method
Logical update of entities – Execute Custom Controls
3 Render audio and video
Application States rendering.
Scene rendering.
User code rendering – Execute simpleRender() method.
4 Repeat loop.

So you see : “push” the data to the view layer to render the results, also “pull” results from multiple controllers as needed.

In fact the most things can be considered as Model here actually the “SceneGraph” and the View should be its rendered result and the user’s input only! The Controls or the Presenter can be “AppState”, “Control”, anything hooks between update step, in simpleUpdate().

As my exprience, apply MVC to real-time application not usually help greatly but sounds very confused and blury. It can help if you too familiar with it anyway, but be careful or you break the MVC contract easily and make it not useful. You can blindy apply it without concerning of consequence, but that don’t make any sense.

B-The central
Now talking about the long “getManager().getSubManager().getItsManagedObject().doSomeThing()”
Consider asking your self this when you code:

  1. Can singleton help?
  2. Can hierarchy actually help?
  3. How secure is your application, is it a game or anything else?
  4. How perfomance sensitive your game is?

For this particular example, related to “Law of Demeter” that @zanval88 mentioned is about “communicating range scope” and “hiding information”, appear as “encapsulation” and “reference” in Java.

  1. If all your Manager classes is public, and referenced every where chances that they can be Singleton (read more about singleton for its downside).
  2. If not, you should nest your Manager and its ManagedObject it arbitrary order and way. Consider this for a game, it’s almost always not necessary!
    2a) When you have your Managers and Object form a “tree” and obey a “cycle” or “protocol” or “common pattern”, may be contract them with an Interface or force them to extend the same base. [I DID this in my Atom framework!]
    2b) Actually while a lower (near the core) Manager are more powerful and can capture the whole process, the higher level Manager (extended Manager or sub manager) know better about detail and specific aspects. The split should be carefully thought first to avoid un necessary burden of too much Managers. Personally, I usually think about an interesting example about a society with many cops and few citizens to imagine about this balance.
  3. For part of the game, when security are most important but not the performance, or for external services. Long indirect call is the most appropriate method, because of the availability (something should be injected, lazy loaded…) and security (some protol given, real info is hidden from our view,…etc). Without a check of availability, chance that you have NPE all the time!
  4. For part of the game that need performance. I said “a big deal of performance” you should try “singleton” for final class (and bare with its other issuses) or bet in some other flatten type of reference (little bit worse performance - one level of indirect) should also be concerned:
  • array or list with an index. map via Class(Type) apear as Template in java … ex: StateManager.getState(ClassName.class).doSomething(); or even more abstract Central.get(“StateManager”).do(“ItsFunctionName”)!!!
  • evolve your hierarchy with EntitySystem paradigm

This is only the things in the top of my head, this question I have been asked many times in many situation, by myself and colleagues, teamates. So I try to make it clear to my situation and also have some common usecases in it.

Please ask more, this is really essential anyway!

1 Like

I forget to answer the “How to structure the game code” question: :stuck_out_tongue:
C- The structure
I have a strong conceptual POV about video game, which affected by cinematography a lot. Because English is not my native language I can misunderstood the real meaning of the noun but I’ve tried to find the right words in decade.

This one is mine, maybe only me but noone else :stuck_out_tongue: :

So consider this 5 level of separation:

  • Main : The main entry, have everything only relate to this single game, single application. Also game specific Configs should be here
  • Core : The shared part can be used in almost every application share the same base
  • Stage : The ‘Stage’ is the base of entities, activites and events… It’s not nessesary care about the gameplay but the World, Camera, Light and Effects, Cinematic. Stage contain most of the underlying logic, and the actors.
  • GamePlay: The part care about the routine of the game, the player, characters, stories, items, gameactions, techtree… it’s make the game look more like a game than an normal software or a movie. Gameplay contain most of the interactive part.
  • State : Even your game routine can be modeled by something else not States, I introduced State to be more friendly with JME3’s AppState concept. I ultilized it and leveraged it, and you should also.

Others optional:

  • *Network : For network game, blending between state, sub-routine and arbitrary events is difficult and may require other kind of paradigm, that’s why is not in Stage, but elsewhere outside.
  • *Services: If your game use external services such as Web or IAP or something like that.
  • *UI: UI stand for user interface, almost everygame have user interfaces but not all, so it’s also optional
  • *Script: For scripting, in my application, I embed Groovy everywhere, but I also preseved a place to hold “tranditional” run-time script that only be awared and executed when the game is already running.
  • *Model: If you are in a company or from a strong “standard lized” Java workflow, it’s nearly you’ll come up with some Bean like this, but it’s kind of for normal software not a game.
  • *Generated: Also if you have to embed some XML or some generated sources
  • *DB: Of course Database and persistent solution can be here( if not better be in the Service section)

The directory :
src
–my.game.name
----main
----core
----state
----gameplay
----*network
----*services
----*ui
----*others
More detailed:
src
–my.game.name
----main
----|–Main.java
----core
----|–event
----|----AndroidTouchEvent
----|–config
----|----KeyBoardConfig
----|----SoundConfig
----|–cycle
----state
----|–InGameState.java (extends AppState)
----|–MenuState.java (extends AppState)
----stage
----|–SoundManager
----|–SelectManager
----|–world
----|----WorldManager
----|----Level
----|----Map
----|----Region
----|–fx
----|----EffectManager
----gameplay // Anything related to gameplay but not the stage
----|–controls
----|----CharacterControl (extends Control)
----|–ai
----|–entities
----|----Monster
----|----Projectile
----|–actions
----|–league

You can find a better example here in my game examples:
http://code.google.com/p/eurokick-jmegame/

Atom framework

I also used a lot of Managers.

Manager can has SubManagers, as a List or a Map (Hierarchy or not is not forced)

Manager can be extended or Singleton or DefaultInstance (can be getDefault() but not a singleton) here and there. Manager all “attend” in a “cycle” but not “obey”. They can implement ICycle to mark they executor as Obey stricly to the Cycle.

you can do Main.getManager(Class) if your Main support it, or doing the long reference getManager().getSubManager().

You can see it as a hybrid or “no contract yet” - “not stricted to” way of implementing to get “best of both world” out of:

  • singleton vs default vs linked instance
  • hierarchy vs flatten component base
  • cycle attend vs a random routine.

In this implementation, I also try to have a good balance between flexibility and usefulness, clearance and performance. In the near future, when my framework is proved to be statable and useful, I will release it fully.

1 Like