# [java] Check my understanding...

This topic is 4613 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

##### Share on other sites
from my what i have seen in programming (2 CPP classes, 1 java class) if you have more than one of the same type of object (multiple orcs or bullets) the easiest way to program them is to have one set class for that type and then have an array of them. This makes the code a lot nicers than having orc1, orc2, orc3. Yes you would have something like Entity.bullets.fireball in Java just remember that inorder to have it you yourself must program it

##### Share on other sites
Quote:
 am going to go ahead and say that from what I have seen, LWJGL seems to be the closest to what I think my needs are. However, one thing is bothering me about the LWJGL things that I have seen. It appears that the LWJGL game programmers almost strictly do not use Java's objects during their main loops. In fact, all of the tutorial material I saw seemed to have a particularly annoying limitation. What I need to know is do I have my head on straight about this.

Well have you looked at full code for any real LWJGL games ? Small demos and examples don't count, of course they will put everything into a single source file just for ease of learning. Personally my LWJGL engine, which is currently interfacing with the TrueAxis physics engine is mostly object-oriented. I have an EntityManager, with respective StaticEntity, DynamicEntity classes. From a file I will load positions/orientations of all the objects in my scene and create a DynamicEntity for each, as well as creating a StaticEntity for the "world" geometry. Then I add these all to my EntityManager singleton, which is really just a wrapper around (not an array *gasp*!) a LinkedList. With a LL you get cheap adds, cheap iteration+ (semi-)cheap deletes, and NO resizing.

Is this the kind of object-oriented system you think LWJGL is forbidden from? it certainly works quite well for me.

The thing is, LWJGL is made to be as small, fast, and portable as possible. For this reason it doesn't have a huge codebase with a bunch of OOP mumbojumbo. Basically, it is up to you to come up with a clever scheme of scene management.

I think maybe a large part of the phobia of objects is the garbage-collecting system. Most people think that they should avoid at all costs ever calling "new" during your game loop. The problem is that people that get locked into these coding styles for "performance" are actually getting more and more outsmarted by each new JVM.

##### Share on other sites
Yes, I understand that, but the problem with Arrays is that they are fixed. Unless I am totally missing something, you can't change the number of objects involved very easily. For example, suppose you are using a Roguelike type of game. You want to have random level generation (you know, one of those things where it runs one of those dungeon tunnelers to hollow out a bunch of rooms, and then populates them with Slimes and Torches and crap.) In that environment, just as an example, it is very difficult to put a cap on the number of things you'll want to have. How many Orcs is enough? 50, 100, 250? Also, wouldn't the memory be occupied regardless? I am not trying to be an http://www.gamedev.net/community/forums/topic.asp?topic_id=326558, but I am ready to move on to games just a bit more complex than Space Invaders.

I'll lay it out on the table. I have successfully made a playable (althought I must confess I never polished it) Tetris, space invaders, asteroids kind of stuff. I really can't learn too much else that way. My next step is more complex 2D single player fare. Not talking Civilizations or anything like that, nothing with an advanced AI yet. I am thinking of trying to write a platformer, and then after that I would like to attempt to make a 2D graphical Roguelike. So while I am being slightly ambitious, this is nothing completely insane here. And for the record, I will probably re-write Tetris and such in Java before moving on to anything more complex. I realize people with huge, noobish visions are a dime a dozen, I just wanted to make sure I was clear that I have a HUGE sense of reality going on here, I am only one person, and a n00b at that.

Here, let me just show you some vaguepseudocode for what I mean by dynamic.

Main loop start
{
do that timing thingie to see how much time has passed
run as many game logic loops as necessary(based on timer millisecs)
run one screen flip
{
process various game logic, see if input keys were hit etc
blah blah blah
....
check to see if game condition calls for spawning anything. If it does then spawn
....
for each Entity.enemy check their status, collisions etc
during the check of each entity allow for dynamic deletion of enemy
}
}

What I am referring to are the various methods people use to achieve this effect. I.E. having an unsorted, not specifically named list you can sort through, add to, and remove things from TOTALLY dynamically, without resorting to, for example, having "ghosts" of enemies that you turn on and off, but that still occupy memory.

##### Share on other sites
This isn't a Java specific thing- you're getting "game programming" confused with "engine programming"

Game programming is nice and intuitive. You spend your time writing things like you describe:

if(!endOfLevel)   Engine.spawn(new HammerOrc());else   Engine.spawn(new Boss());...if(playerHit){   if(playerWearingArmor)      player.damage(damage / armorAmmount);   else      player.damage(damage);}

Engine programming is difficult and mindnumbing.

public void spawn(Entity e){   Tree worldTree = Engine.getWorldTree();   Vector3df origin = e.getOrigin();   for(Enumeration e = worldTree.getNodes(); e.hasMoreElements){      Node n = (Node)e.nextElement();         if(n.isFound(origin))      n.Insert(e);   else if(n.hasChildren()){         Node parent = n;         while(parent.hasChildren()){            Node[] children = parent.getChildren();            for(int i = 0; i < children.length; i++){               if(children.isFound())                  children.Insert(e);            }         }    }    else       Throw new EngineException("Entity location not found in world tree.  Invalid coordinates!");}

Ok, so, that was completely fictional. However, it still makes sense. Spawning and manipulating Entities in a game world is potentially very very complex stuff! This is the case in any language you use.

No language has a built in game Engine. There are 3rd party engines available for Java (JMonkeyEngine, JOgre, AgentFX, etc) and C++ (Ogre, Irrlicht, Genesis3D, etc)- but these exist only because somebody took the time to do all the dirty stuff.

As far as creating/destroying objects during the loop- there are issues with this sort of thing in any language if you don't know what you're doing. Typically though, these are the worries of someone writing an engine- trying to prevent memory leaks and hiccups. If all you're doing is creating/destroying Orcs and such, this won't be a problem. If you're optimizing your particle engine to prevent it from garbage collecting 5000 particles every second, then this might be a concern :D

Java 1.5 is very good at these sort of things though- Don't worry about creating/destroying objects in the main loop.

##### Share on other sites
(From c++ point of view) To add to memory leaks you also tend to worry about memory fragmentation.

##### Share on other sites
So which of these extensions are Engines, and which are the things that you use to build engines? Is LWJGL an engine? While I may become interested in engine development at some point, my inclination right now is that I would like to learn more about actual game design. Which java setup would be the best for diving right in(with a solid understanding of Java itself of course) and making stuff happen?

Just to be clear, I am not looking for a glorified RPGMaker2000 type of thing. I don't want any assumptions to be made as far as the games BEHAVIORS, I want to to ALL of that myself. I don't want built in systems for HP/MP. I really just want a way so that I can focus maybe 30% on Java and 70% on the game logic itself.

Of those 3RD party engines you listed(and I am not saying this to be lazy, I Know I can easily Google them all, I am asking you because you seem more experienced than I) which(if any) would be perfect for focusing purely on 2D game design, preferably for running on a windows/Linux desktop in fullscreen? (Note that when I say 2D, I mean 2D from my perspective. I don't have any problem with ones that do 2D sprites as 3D flats as opposed to per-pixel) I am not saying this to avoid googling, just wondered if any of them were "dead on" for my needs.

EDIT: Fresh off Google> http://goldenstudios.or.id/products/GTGE/ I wonder if this is what I am looking for?

##### Share on other sites
The big ones (JOgre, JMonkeyEngine) might be too big for what you want.

I'd suggest GTGE (http://www.goldenstudios.or.id/).
- The creator frequents these boards so you can get some nice help from him.

I havn't used it myself, but from looking at it, it'll probably be best thing to bring you to the "30/70% ratio" you want. However, without knowing what type of game you're shooting for I fear that "30/70" might be wishful thinking. 1:1 might be more realistic for a simple game.

A step from that is Java2D itself- which is just using the Java graphics library in conjunction with an applet or frame. This is probably too loose though. However- Java2D is a great progession from GTGE once you've gotten some game logic under your belt. Especially because GTGE is written in Java2D.

Also, to help you organize your thoughts about engines/game logic. Here is a nice tutorial by kevGlass http://www.cokeandcode.com/info/tut2d.html I've sent a few of my friends there who were wishing to learn about Java game programming.

Good luck!

##### Share on other sites
Well my 30/70 thing was just talking out of my butt :) I appreciate the help on this thread, now I better get back to getting the rest of plain ol' Java under my belt so I can start into this.

##### Share on other sites
If you want to make a game, not the basic stuff, then yes, GTGE is what you looking for!
This is very true especially when you say you want to make 2D game, cos GTGE is focusing on 2D game development.
Then you can indeed focus 30% on Java and 70% on the game logic/game design.

And GTGE can also use OpenGL mode (both LWJGL and JOGL supported), but the basic GTGE will only using Java2D, that way GTGE can make pure 2D game without the need of any other library instead of Java SDK of course.
The beauty thing is to port from GTGE Java2D to GTGE OpenGL via LWJGL/JOGL, the game only need to change 2 lines of code roughly, and the game is already in OpenGL world.
Basically GTGE use OpenGL mode only for performance wise, but not closed for mixing 3D objects in 2D ;)

Now here is the list of GTGE features :
http://goldenstudios.or.id/products/GTGE/

And the most important thing is, GTGE is actively developed with the best support I can say.

Any question? :)

##### Share on other sites
Here's another vote for GTGE. Very intuitive to work with and the developer is extremely active and he loves when people use his engine. I've played around with it some and it sounds like the type of mix you might be looking for.

PS - java.util.ArrayList is a great construct for hanging onto collections. It deals with resizing when it needs to and has great benchmarks in later versions of java. I can dig up the benchmarked tests against LinkedList and a few other data types if you're interested.

##### Share on other sites
I'd be interested in those benchmarks, I was always under the impression that arrayList was slow for resizing because basically it created a new array and switches references, While with a linked list resizing was quick, but it uses more memory in the first place.

##### Share on other sites
I can't find the more recent one I was reading, but here's a slightly older one:

http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.html

Optimization techniques change over different versions of the VM though, so take it with a grain of salt. Bottom line though is, unless your looking to store TONS of info in one of these things, an ArrayList will certainly be fast enough for any of your needs. I think they're pretty straightforward to use too, personal preference :)

##### Share on other sites
Arrays are first class objects, it would be silly to don't use them.
It's true that creating and destroying object might be cheap on current VM, but OO isn't about creating and destroying objects, it's about object manipulation.

Quote:
 I had assumed (perhaps naively) that in a language like Java I would have a sort of Entity.bullets.fireball and Entity.monsters.orc.orc_with_hammer kind of thing going on. I remember reading that there was a sort of list you could create by using a built-in Java class so that I could cycle through dozens of unnamed orcs and fireballs or whatever I needed and simply process them every cycle

That list is named array. And yes you could use something.somethingElse.somethingElse Just if you need to write a some more speedy up game, you'd need to know something about pointer dereferencing, and "public" overhead. ("private" is more readily inlined)

Quote:
 How many Orcs is enough? 50, 100, 250? Also, wouldn't the memory be occupied regardless? I am not trying to be an

It's responsibility of a game developer to know it, not the language.
Component leaks might be more bad than caught array access out of bound Exception. (I recall on one in jEdit 4.2 beta2)

I remmember on one roguelike named Tyrant. Look at sourceforge.net for its code.

##### Share on other sites
Quote:
 Original post by tolsgThen BAM, all the Java game specific tutorials are using arrays and stuff! Yikes! No offense, but that seems to really call into question if I should bother using Java for my needs... I seriously would like to avoid the "Just use an array and an old fashioned procedural loop" because that won't teach me anything. I actually want to do this pretty much OOP, but apparently creating and destroying JAVA objects during the main loop of a game is not feasible? Let me ask this, would you normally create and destroy objects in the main loop in, say, C++? Is my understanding of how to use objects in games completely wrong?

There are basically 2 ways. The old fashioned procedural loop or event based. Usually you combine the approaches. Your events modify/create objects and your loop will render, make non-event updates, maintain timing.

As for arrays, Java has several built in data structures that you can use instead of arrays. Look at the java.util.List, java.util.Set, java.util.Map and java.util.Collection interfaces. Follow them the specific classes that implements them. You can find them all in the java.util.* package. Read them over to find out which one suits your needs.

##### Share on other sites
Tolsg, I might have missed it in the other posts, I kind of scanned over them before and was suprised that no one mentioned vectors! This is what you are looking for I believe as far as using a 'collection' of objects. Vectors in java work almost exactly the same as they do in C++. There are no fixed sizes, they can expand and shrink dynamically. In my opinion one of the best items in your tool belt. I haven't done and programming in 1.5 but I am willing to bet they are still included in the standard API.

##### Share on other sites
Quote:
 Original post by WrathnutTolsg, I might have missed it in the other posts, I kind of scanned over them before and was suprised that no one mentioned vectors! This is what you are looking for I believe as far as using a 'collection' of objects. Vectors in java work almost exactly the same as they do in C++. There are no fixed sizes, they can expand and shrink dynamically. In my opinion one of the best items in your tool belt. I haven't done and programming in 1.5 but I am willing to bet they are still included in the standard API.

Instead of Vectors I'd recommend ArrayLists. Vectors are slower because they're synchronized. Games typically run on one thread so there's no need for synchronization.

##### Share on other sites
I use ArrayLists mostly. They very rarely grow once you've profiled your game and worked out the maximum size they tend to reach.

run the game a few times, find out the peak size of entities, and change the code to

entities = new ArrayList(MAX_ENTITIES);

It'll still resize when it has to but it'll happen so rarely no-one's going to notice.

Quick word about object pools as well - I used to use object pooling a lot (it's especially useful for "expensive to construct" objects) but these days I'm just newing() happily away and letting the GC kill them off later and the amount of headaches it's saved me far outweighs the tiny <1% speed loss. Even particle effects can be done this way, and you can have hundreds of them spawned every frame.

Cas :)

##### Share on other sites
There is an article at IBM Developer Works about the Garbage Collector. It covers that very subject.