Hey guys, I've only recently started learning java (self teaching for around half a year) so that I could create this game I thought up. It was basically thrown together, but is still the only java program I've made so far, so I would like to finish it up. Currently, the code is approximately 5000 lines, but the more I look at it, the more it looks as if I could have written it better from the beginning. (I looped through all my arrays at least 50 times every frame).

So my question is, "How would I go about optimizing my code"? Right now, it is only one main applet class, with a class for every single unit, and a building class. I would like to break up the huge paint method into different classes, but am unsure of how the best way to do this would be, as well as how to pass variables efficiently from one class to the next.

Also, I wanted to know if it is possible to make a png image a different color or rotate it, as there are multiple factions, and I wanted to make all their units and buildings their color.

Lastly, I was wondering how I could make effective unit movement. As of now, all movement is calculated using distance, which requires me to loop through the whole map, except this does not work well. There are some units which should not be able to cross water, or go across a pit, but using my method they just disappear and reappear somewhere else.

I have tried to solve all these problems independantly, but was unable to come up with a solution. Here are some pics of the current build:

the only java program I've made so far... ...it looks as if I could have written it better from the beginning.

This is probably true! It may well be a good idea to start from scratch, based on what you've learned so far. Everybody's first go at code always ends up like spaghetti. Think MVC - Model, View, Controller and try to keep the code for these independent of eachother.

IMO, if it's only 5000 lines and it's an early project, it screams for a rewrite from scratch, esp. since it will probably come out to less than half the length on a fresh rewrite. I'd go as far as to say that even once your experienced, 5000 line prototypes should almost always be rewritten before going further, since you can create a big-picture design that reflects what worked and didn't work in the prototype.

Refactoring is what you do when you're in one of the following situations:a) you got everything mostly right the first time through, and just need to clean house a bitb) you've dug yourself too deep into the project to do the rewrite that it really needs

Don't end up in situation b) if you can help it. No matter how great at refactoring you are, it's hard to "save" a project (by which I mean bring it to the point where it's fairly easy to extend it further) if it's gotten too crusty. We've all been there more times than we'd like to admit, and most corporate code-bases are there in perpetuity, and it's a nasty mess that nobody likes to clean up after.

With small game projects you should be able to stay in category a) as long as you rewrite early and refactor often.

The best time to clean up your mess is right after you have made the mess (or you notice a mess made by somebody else - if you need to maintain it, it's also your problem and responsibility to fix it). It's like keeping your living room clean - if every time you go through the room, you take something which is not in its right place and move it to where it belongs (take an empty glass to the kitchen etc.), you will never need a bulldozer to take down the room. The same is with code. If you refactor all the time (right when the code begins to smell - every couple of minutes right after some small changes), you will never need to rewrite everything (or if you think it like this - by refactoring you rewrite everything in so small steps that the system works all the time).

Don't end up in situation b) if you can help it. No matter how great at refactoring you are, it's hard to "save" a project (by which I mean bring it to the point where it's fairly easy to extend it further) if it's gotten too crusty.

This is not necessarily so bad. Many games will have O(n^2) efficiency when it comes to the main loop, where n is the number of entities in the world. This is typically as a result of a brute force method of determining proximity (each entity checks every other entity), which is certainly not optimized but in many games it's completely unnecessary to do something more efficient.

Sort of on the same line as what I said above, an old adage comes to mind. "If it ain't broke, don't fix it." Computers are fast enough these days that you can get away with a lot, especially with a game as simple as yours. That being said, one of the best things about learning to program is finding yourself in situations exactly like the one you're in now. You're looking back and a completed project and wondering how you could program something so badly. But that's a really great thing, because it means you've learned a lot and improved dramatically. And if you go back and rewrite it then that means you learn even more. So if you're going to rewrite it, don't do it for the sake of optimization, do it to learn. You could just as soon spend that time starting another project to get something else under your belt.

Right now, it is only one main applet class, with a class for every single unit, and a building class. I would like to break up the huge paint method into different classes, but am unsure of how the best way to do this would be, as well as how to pass variables efficiently from one class to the next.

My paint method is usually very tiny, something like this:

1 2 3 4 5 6 7 8 9

publicvoiddraw(){background.draw(0,0,screenWidth,screenHeight);

for (inti = 0; i < entities.size(); i++)entities.get(i).draw();

player.draw();}

So basically the background is always in the back and the player is always in the front. But really all I'm doing is referencing other draw methods, except for the background which we're assuming is an actual image. Each Entity should have their own draw() method where they are responsible for drawing themselves based on their own position, dimensions, current image, etc.

Also, I wanted to know if it is possible to make a png image a different color or rotate it, as there are multiple factions, and I wanted to make all their units and buildings their color.

There are a number of ways to do this. I'm not sure if this is the best way in Java2D, but you can just iterate over the raster of the BufferedImage you want to tint and then directly apply tinting values to each pixel. Messing with rasters is pretty fast so you shouldn't need to worry about speed as long as you're not tinting it every single timestep.

Lastly, I was wondering how I could make effective unit movement. As of now, all movement is calculated using distance, which requires me to loop through the whole map, except this does not work well. There are some units which should not be able to cross water, or go across a pit, but using my method they just disappear and reappear somewhere else.

You should try A*. Check out Kevin Glass's A* tutorial, it's pretty good: http://www.cokeandcode.com/pathfinding Also just do a search on the forums for A*. I might be misunderstanding what you're saying, by the way... I'm not exactly sure what "calculated using distance" means. It sounds like you're just setting them to their new possible position immediately, but then I don't see why you'd be iterating over the entire map.

Thanks for the tips guys, but dang is that a lot of reading . I know what I'll be doing this weekend. Rewriting the entire applet seems like the best option at this point, but it just seems like such a waste of code. That entity idea is great though, so I'll implement it the next time I work on a game. Would it look something like:

As for loading resources, would you guys just make some kind of resource class, that just loads every sound and image when its instantiated, and then pass that on to every other entity method, along with the Graphics? The reason my original main applet class was so long was because of resource management. One last thing, theres a class for every single unit, so that all their actions can be made unique from unit to unit. Every unit also has a unique shooting sound, so I'm not sure what to do about that either. Should I just do:

1 2 3 4 5 6 7 8 9

if (unitinstanceofCombatTank){combatTankFire.stop();combatTankFire.play();}elseif (unitinstanceofMedic){medicHeal.stop();medicHeal.play();}//... And so on, for all 20 units?

Sorry I have never played with sound in applet, but i have one suggestion for the drawing part

If your gameMap is fairly small, then just use a single big image for the map. (you can generate the terrain at loading time)If the gameMap is much bigger than the screen, then you should only draw thepart which is visible on the screen.

I made my own ImageManager class to handle my resource loading, and I've used it for practically every game I've ever made (since creating the class). It's simple, adaptable, and "safe," as in it will always do its best to get you some kind of image onto the screen, rather than throwing exceptions or breaking your game. It also preloads every image only once.

/** * Fetches all images for the passed list and places them in the map. * @param images The names of the images to be loaded. */publicstaticvoidpreloadImages(ArrayList<String> images) {for (inti = 0; i < images.size(); i++)preloadImage(images.get(i)); }

/** * Loads a single image into the map. Generally this will only be called by preloadImages(). * Duplicates will not be added twice - therefore if it's a question preload an image again. * @param name The name of the image to fetch. * @return Returns whether or not the image was actually loaded. */publicstaticbooleanpreloadImage(Stringname) {if (!map.containsKey(name)) {map.put(name,newSprite("Images/"+name));returntrue; }returnfalse; }

/** * Unloads all of the specified images from the map. * @param images A list of the keys of the images. */publicstaticvoidunloadImages(ArrayList<String> images) {for (inti = 0; i < images.size(); i++)unloadImage(images.get(i)); }

/** * Unloads the specified image from the map. * @param name The key of the image to unload. */publicstaticvoidunloadImage(Stringname) {map.remove(name); }}

I usually couple this with giving every Entity a preloadAll() method, which they can use to tell the ImageManager what it should preload. That way once at initialization you just loop through all your Entitiy's and call preloadAll(). Then later on you just access the image with ImageManager.getImage().

As for having GameMap extend Entity, you can do that if you like but I wouldn't. Instead it's more like this:

Basically an Entity is something that can exist in your world / GameMap / whatever you want to call it. It doesn't really make sense for the GameMap itself to be an Entity. Instead, it contains entities and gives them access to other entities if they need it.

Well, it's been a while, but I think I've accomplished enough work on this to post an update. As I stated in my first post, this is my first game, so I would like to post what I have so far and see if anyone can run it. It's an applet, so even though a program might function inside an IDE, it might crash outside of one, which is why I would like some users to test it. However, I don't have a website, so would like some suggestions about how to put it up for download.

Here's a screen shot:

Regarding the actual game programming, however, I also have a couple of questions that I've had difficulty finding the answers too. As of now, there are no objectives of any sort, because I wanted each map to be dictated by various triggers encoded into the map. For example, there could be triggers not just for Mission Victory/ Mission Defeat, but instead, stuff that would also allow scripted events to happen, like if a marine is brought to location 2,2, a moving tank appears for, say, player 1.

Has anyone ever implemented a system like this, or something similar?

Also, I'm drawing a complete blank with how to code TBS ai. I suppose it only has to be calculated once, but I'm not sure what exactly goes into making a fully functioning ai, that will move units, build structures, and finally end its turn.

I'm really excited about this game, and can't wait to finish up the complete version! By the way, if any of you are curious, this game was completely rewritten from the ground up. The old version was scrapped a few days after demonpant's post, which made me realize just how much my code was repeating itself just to perform a simple task. It's currently 6000 lines of uncommented code, and like 8k commented.

What I would do on the site is to do a search for "free web hosting." You will probably want some sort of site and it's as good a time to get started as any. Make sure they allow jar files for uploading. The game looks very nice from the screen shot.

For cause/effect stuff and special triggers, looking into using javac inside your game. (I believe you can use the Runtime class...) It can compile and run external Java code, so you can basically just write Java "scripts" and then run them for each level, or you can make your own scripting language and then just turn it into Java, then compile that.

Also, I wanted to know if it is possible to make a png image a different color or rotate it, as there are multiple factions, and I wanted to make all their units and buildings their color.

The way I do this is to say that anything which is really absolutely grey (R=G=B) gets recoloured and anything else is left alone. This allows you to change just e.g. the flag or the uniform. The OO Java-approved way of doing this would be an RGBImageFilter:

I am using a similar approach in my project, and it works extremely well. I often get beaten by the AI . In short, you have a list of priorities to your units - it tries to do first what's on top of priorities list, if it cannot do it, it tries the next .

-----

pjt33, thanks man ! Lucy I read this topic. I was thinking a nice way to do this coloring stuff in my game but never thought of a decent way . I was trying stuff like RGB >200 and stuff like that but there were a lot of undesired coloring . I think absolute gray will work fine ... (tough it'll be a pain in the ass coloring all my sprites ..)

Hmm.. This seems like it could work, or at least something that could be built off of, so thanks for the link. I'll try implementing it some time next week. (Gotta study for the actual computer science AB exam first!)

To pjt33:Yeah, that's exactly how I'm doing my spriting stuff too. At first I used a color image method that would merge two colors together, but this would also effect the color black (which should always stay black to give something its outline), so I decided on grayscale. However, this forces you to do everything pixel by pixel, which does take forever. Now that I think of it, however, it could be possible to convert an image to grayscale using a filter, and then run it through this method. I'll go try it now.

If any of you are curious, here is what the marine idle animation looks like before its colored:And then colored:

EDIT:Grayscale on non-hand drawn images doesn't work that great. They only look decent when the saturated image has the same color as the original image.Original:Randomly colored:

Right now I'm trying to implement triggers, and would like some input on the following way of doing it. Essentially, the trigger class runs all Action objects stored in it if all Condition objects are met. So it would perform some sort of loop through the set of conditions, and if all were met, then it would loop through all actions, running each one.

So, a Condition could be something like... having the least amount of funds, having the most units in total, bringing exactly 3 units at a certain location, and an Action could be something like give player $50, create a unit for the player, etc.

However, in order to do something like that, you would have to have some sort of Parameter objects for each Condition. For example, in the following condition (Current Player) brings (at least) (5) (Infantry) to Location (Bring units here!), all the things in the parenthesis should be parameters. As they are not numbers, though, I'm not sure how to construct it so it works like that. I suppose there could be a Quantity extends Parameter object, which could have final ints like AT_LEAST, EXACTLY, AT_MOST, and then an actual value. Which means that a condition must be able to call a parameter with some sort of a value, say, an int, which should return true if that value meets the conditions, or false other wise.

And for the (infantry) parameter, there could be a UnitParameter, which returns true if a unit its sent meets the data it was initialized with.

It seems like that would most likely be the exact same thing that should be done with Action objects, so perhaps both of them should extend some super class. Not sure though.

Oh yeah, and for (bring units here!) there could be an Area object, with data types such as a starting point (2,2) and an ending point (5,5), as well as a name. This would work for testing if an object is in those bounds, but I'm not sure how it would work for creating objects in those bounds.

So, what do you guys think? Any suggestions before I try to implement this?

So, a Condition could be something like... having the least amount of funds, having the most units in total, bringing exactly 3 units at a certain location, and an Action could be something like give player $50, create a unit for the player, etc.

The reason to use generics for something like this is that now you can also define a Condition<Enemy>, or a Condition<Tile>, or anything you'd like. You'll still have to manually manage the various lists of conditions and which arguments to apply to them (type erasure means that you can't pull the things in brackets out at runtime), which will probably happen in your Trigger class.

I'll be perfectly honest: for stuff like this, Java is a poor language, so no solution will be perfect or clean (and I make no claims that the above suggestion is the best, in fact, it may be severely flawed in some way, I just threw it together very quickly). What you really asking is to send a piece of code as a parameter to a function, and unless/until Java gets closures this is very messy. It's very easy to meander down a path where you end up simulating a functional language within Java, and I'd strongly suggest that if you find that happening, you either embed a scripting language into your game (Javascript integrates pretty well, I've heard) or write key parts of it in Scala, Clojure, JRuby, or some other functional language that can interop decently with Java.

Thanks for the info. Lol i never knew you could call this() within a class.

I tried to do something similar to your framework, except with all the Actions and Conditions being defined in different classes. It did seem like I was writing a language inside a language, but there were only four different Parameter classes needed to define all the functionality needed, which were Quantity, PlayerParam, UnitParam, and Area, so it wasn't that big of a deal. The main classes were implemented like so:

Parameter:

1 2 3 4 5 6 7 8 9

packageCremelianWars.Triggers;

/*A parameter is used to test various pieces of data that are sent to Condition objects.*/publicinterfaceParameter{

/*Tests of a given player has accumulated a certain amount of funds: ----------------------------------- Requires PlayerParam, Quantity Tests Player */publicclassAccumulateextendsCondition{PlayerParamactivePlayer;QuantitycompQuantity;

Basically, this implementation just cascades tasks to break them up into smaller and smaller segments, them being trigger -> condition -> Parameter. But because all of the conditions deal with different things, it seemed like a good idea to use an ArrayList of objects. Since that's the case, though, its almost impossible to make these function within some sort of a loop, since they all have variable needs. Typing them out isn't easy either. I tried implementing the system, and it took a good deal of work to make the system perform a simple task, which looked like this:

Which brings me to my next point of how to use them in a map editor. I suppose there could be a toString method associated with each, as well as a buildFromString method, so the user could type them in. XML would probably work better, but the map is already loaded using a similar method dealing with break chars. So, does there need to be some sort of a static factory method to create these, or do you guys see another way?

Oh yeah, and in the above piece of code, below the comment:"//Creates the conditions from the parameters",The compiler displays that its illegal to pass those three Parameters to the Control Condition. It would probably be beneficial if there was someway around this, as to allow for more generic objects to be passed.

/**Tests if a player has a certain amount of units: ----------------------------------- Requires UnitParam, PlayerParam, Quantity Tests GameMap

This method loops through the game map, getting every location, testing if the unit it contains meets the test of the unit parameter, and if it does, adding it to a total, which is then tested against a quantity. */

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org