[newbie] How do you structure your game?

First of all, I have to say I am pretty impressed with jME. I had no idea Java could do such sweet graphics. We did some light Java3D in school a few years back, but we just used the native java3d api.



So, onto my question. How do you structure your classes, which has what responsibility?



I was thinking that if I want to create a shoot'em up game I have a SpaceShip class. The SpaceShip itself loads its model and has a method named getNode() which returns a Node, not a big surprise :D, that you add to rootNode (in a World class, or similar).



Then I get to user input, it doesn't make all that much sense to me that the spaceship class listens directly to input. I was thinking that the spaceship has a "thrust", "turn" and similar methods and a different class handles when those methods are called.



I know the java syntax, but I've never tried to make an object oriented game. All my previous games are nothing bigger than Tetris.

Take a look at the very useful Flag Rush Tutorial here:



http://www.jmonkeyengine.com/wiki/doku.php?id=flag_rush_tutorial_series_by_mojomonkey



It will get you up and running quick!

Thanks :slight_smile: I only read that tutorial previously and must have skipped where the Vehicle class was made. Skimming = bad  :stuck_out_tongue:

If you are willing to try a more elaborate architecture, so you can have more flexibility in the long run, google for “game object component system” or somethink alike.



Here are some hints (the first is my approach to the concept):



http://sertao3d.blogspot.com/2008/01/data-driven-game-development.html

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

http://www.gamearchitect.net/Articles/GameObjects1.html



If you want to use these ideas, I’d be happy to send you the current version of the framework.

Perick, thank you for these links. Would you possibly consider sharing the 'current version of the framework' with even more starting developers? 

I

if you feel it is solid enough perhaps it should go to jme demos SVN? what do you think core-dump?

I recall reading a thread before where you (Perrick) elaborated on this kind of approach. Im wondering one thing after reading your blog though; the approach you use will mean a game might have tens, if not hundreds of gamestates running. I'd imagine this might kill performance since I recall a gamestate having some overhead, ofcourse I could be wrong. Could you elaborate on this point in particular? :slight_smile:

Mindgamer said:

if you feel it is solid enough perhaps it should go to jme demos SVN?

it sounds a bit complex to fit into the jme-demos category but if you think it would be a good addition just give me a message :)

Not a lot of game states, but probably a lot of game objects…



Trying to make an UML diagram here:



GameManager <>


GameState <>
GameObject <>
Component
Singleton              (1-4 simultaneous)          (20-250?)            (1-5 per object)

Think as a GameState as the PlayingGameState + HUDGameState (may be defined as a gameObject) + (intermitent) InGameMenuState... This is the most you'll probably get simulateneously. You can define hundreds of game states but probably only one or two instantiated (and populated with game objects) at the same time.

When I post the examples to download it'll become more clear.

This is a (kind of) consolidated design in commercial titles and engines, the other being the bloated GameObject hierarquy (I think most of you are aware of the limitations of inheritance vs. composition)

Just to put everything in numbers, lets consider a small RPG (location) game with:

GameState 1 ("playing scene"):
TerrainPage - 1 game object X 2 components (visual and physics)
Trees  - 20 objects X 2 components (visuals and physics)
Buildings - 10 objects X 2 components (visual and physics)
NPCs- 15 objects X 4 components (visual, animation, dynamicPhysics and AI)
Player 1 object X 6 components (visual, animation, dynamicPhysics, inputController, inventory and CameraController)
HUD 1 objects X 4 components (life, ammo, armour, crosshair)

This will lead us to a game state comprising of 6 objects and 122 (counted right?) components, but only 60 of them actually being updated (those that make npc, player and hud game objects). Thats NOTHING for the JVM to traverse...

Most of the scene graph in locked (such as trees and terrain). I didn't test this exact composition, but I use to simulate flocking behaviour (100+ dynamic game objects) in this framework with very good results, remebering that the bottleneck in my case is actually the cpu-based flock algorithm ( O(n^2) complexity, n being the number of game objects - boids ), not the game objects architecture.

I expect to have cleared some things. I wrote a paper about the dependency injection scheme I implemented in it and want to make it public as soon as I get clearance (or denial) from the conference chairs.

EDIT: Just to make it clear - From my perspective as a former (8+ years experience) Java enterprise developer, sooner or later you'll have to go for a more elaborate architecture like this, UNLESS you're just learning bits from graphics programming and not really trying to make a complete game. Even if you're just fast prototyping, reusable components give you the freedom to FOCUS on the NEW MECHANICS (custom input controller, new AI, new components for scripted objects), which is the basis of innovation.
Darklord said:

The approach you use will mean a game might have tens, if not hundreds of gamestates running. I'd imagine this might kill performance since I recall a gamestate having some overhead, ofcourse I could be wrong. Could you elaborate on this point in particular? :)


I will quote Core-Dump from this thread :) :
I can't think of any reasons for not having 10 or 50 GameStates, they basically just have their own root node and name, so there is not much overhead.


Also concerning the object structure - I assume HamsterOfDeath uses something very similar in his hhexen. I remember (I think from this thread) how he described that he can give any ability to any object and combine them in any way. Sounds at least in some aspects like the Entity Systems described in the articles you linked to.
I assume HamsterOfDeath uses something very similar in his hhexen.

Yes, I think so. I

i'm really interested in seeing this as i'm currently migrating a ui toolkit to an aggregation model…

if you ever need volunteers for testing/code monkeying…

Hi Perick,



I've downloaded your sample code previously and played around with it a bit. I think it's quite clean and neat to use. I can quickly put something together with minimum effort.



I noticed that you created a wrapper GameState class which extends DebugGameState and contains camera, audioSystem, physics and gameObjects. In your example I think you only instantiate one such GameState defined in caatinga.xml. I think this is what you describe as a PlayerGameState which is sort of a master state.



However if I wanted to instantiate extra GameStates, not all of them would need camera, audio, physics etc. then I assume I would need to define my own GameState config right? I'm thinking along the lines of using multiple separate states for Menus, Background, SkyBox etc similar to MonkeyMahjong.



Also based on your experience, what was the reason you decided to use your own configuration/injection logic instead existing frameworks say, Spring?



+1 on sharing your latest framework code. I would be very interested also.

Ok,



Q0:

I would need to define my own GameState config right?


Wrong…:slight_smile: You are not supposed to extend GameState or GameObject. You just compose game states with game objects and (if creating a prototype with some kind of new mechanics) implement 1-3 custom components to use in this task, extending AbstractComponent. The vast majority of requisites can be caught by reusable components and that's another goal.



Right now there are only ~20-30 reusable components already implemented, but I have a lot of them "in my mind", such as: HUD components (with customizable size, looks, textures), switcher component (switch game states based on another game object component boolean condition), activator component (to activate and deactivate game objects and components based external conditions), lots of menu components (GUI comonents declared in XML)… The list is enormous. If you think it's good enough of an architecture for you, we can start sharing the code and make it a community-driven framework, specially the reusable components implementation.



Q1: About multiple game states:

You can define as many as you want in separate XML files. You should have noticed that you can also define types in separate XML files and use them (extend, instantiate) in other type definitions or to define objects inside the game states. To switch from state to state you can use the GameManager.start(String stateName); method (not sure if the old version already has it, but I promise to post the new one today).



Q2: Where should I call that method so?

For each master state (play level game state) I tend to use a "battle-manager" game object (not visible, no VisualComponent) with a single BattleComponent (with custom simulation script) for the sole purpose of observing the simulation state (if the finished condition is met, such as end of battle, killing of the boss and collected everything, etc). If the finished condition is met, I call GameManager.start(nextState)…

String nextState is an attribute (being customizable via XML of course) in the BattleComponent class.



I'm actually designing flexible communication methods between objects. Dependency injection is only one of the features I'm using to this purpose.



Q3: About custom made dependency injection.

I've used Spring in other contexts and also evaluated Guice for this task. But after a while I saw that a single annotation (@Inject) and a single injection method (~10 lines of code) did the job, integrated with the Builders I had to implement anyway. So I think using a framework like Spring would be just over-engineering, and actually it wouldn't work "off-the-shelf" because both frameworks inject the dependencies by instantiating them at the same time. Because of the circular characteristics of game objects dependencies I needed to first instantiate ALL game objects and their components, and after that, INJECT the dependencies between them.



I didn't want to implement a lot of useless classes just to adapt my design to spring or guice. Instead I wrote 15 lines of code that did the job.

Just uploaded a new version of gcore… Full source code + two running examples:



1 - Fantasy farm boid simulation with player + cats, dogs and mice (you can shoot the by pressing the left mouse button and pulling your sling-mouse, the releasing the button)

folder serta3d, init.Demo



2 - Lunar lander - prototype for controlling a landing space ship with forces, pressing SPACE

folder lunarLander, executable class,don´t remember the name… There are only two, on Component (ThrustController) and the Main class.



http://www.ic.uff.br/~epassos/gcore.zip



Looking forward to new comments on this thread.

Thanks for clarifying Perick, that's definitely alot of food for thought. I'll be sure to download your latest version later on.



I think I understand your design now. Whereas most StandardGame implementations separate game logic via multiple GameStates, i.e. MenuState, BackgroundState, CameraState etc, you separate your logic via Game Components so they become MenuComponent, TerrainComponent, HUDComponent instead. Then you combine them all together inside a single Player Level State. Just a thought, it might be helpful to rename your "GameState" to "PlayerGameState" or something to avoid confusion with the built-in JME GameState.



I was thinking of making a few modifications of my own, your xml based GameState configuration would perfect to specify a hierachical GameStateNodes tree structure in a simple readable format. A GameState tree is quite handy if you want to update or remove multiple states at a time, however in your architecture there will only be 1-2 GameStates running at a time, so do you see any use for implementing support for GameStateNodes?



I'll definitely share any useful code I come up with. So far I've just been modifying your config files so that it's a ninja running around instead of a dwarf…

Wel, I see your point about nested game states (nodes) and I agree, it'd be nice to have such a tree structure so we could start/pause/destroy them with a single call from an activationComponent. I can code the parser and builder parts in maybe ~15 minutes. Put on the priority list.



There's nothing in gcore saying you should not structure your playing scenario with multiple simultaneous states (one for scene, one for hud, etc etc)… I just have to finish the dependency injection between game objects from multiple states. This way a hud game object can be an "observer" on another game object component (player health component) from a different game state (master playing scene).



I think I'll have some time this week to refactor some things and develop new features, nested states are on the way.

Tried out your latest version. Sert3d runs around 60 fps on my AMD dual core 2.0GHz laptop with Window Vista. Tried compiling again jme 2.0 alpha and ran into all sorts of Enum related compilation errors  :stuck_out_tongue:



On the topic of simultaneous states, it'd really helpful if the GameState's injection/xml config parsing logic could be moved out into a GameStateFactory. That way all the jmex GameStates such as CameraGameState, LoadingGameState and any user written GameStates could remain portable and be plugged into the injection framework without any GCore-specific constructors such as:


public GameState(StateConfig map)



With nested states, the main Player State can become a tree consisting of CameraState, PhysicState, HUDState etc injected as children States running simlutaneously. Add a GameStateFactory in there would mean all GameStates will still work independently in a non-GCore game since the injection/XML parsing logic are separated from the GameStates themselves. Let me know what you think? Looking forward to the nested states enhancements also.  XD

Would it be possible to get some low level idea of how the framework actually creates objects from the components. I've done some browsing around at dependency injection articles and looked at the demo code and it is about as clear as mud at this point. I've got a notion that it uses reflection to create the objects dynamically from the component classes, but thats about it. Also, is there any documentation on the code itself (package definitions, uml, or possibly a sequence diagram)?



From what I do understand of it (from the article links you posted) the component method seems like a very flexible and extensible architecture and is particularly well suited for game objects. It would be nice to understand the framework a bit better though before spending a lot of time integrating the code I currently have working into it.



(side note: it might be beneficial to move this conversation to its own thread, this idea certainly deserves its own)

(side note #2: I noticed in your demo with the dwarf that it is possible to use the ball-launcher to launch your character into the air)