Secrets from the Robocode masters
My first robot was written as one large class file. Initially, this worked quite well, but as I added more smarts to my robot, it grew to the point where it became difficult to manage. I quickly realized that if I wanted a fighting chance against the top robots, I would have to come up with a better design.
The solution I came up with was to break the robot up into modular, reusable pieces, each managing a different aspect of the robot's behavior. I created one class each to control movement, radar, the gun, and aiming. I created classes to track information on an enemy robot and a class to store information on all enemy robots. Other classes soon followed.
My goal in writing each class was to make them as independent as possible, so I could reuse them in different robots, or change the overall design of the main robot class without having to rewrite scanning, movement, aiming, and other functionality.
Even with this modular design, there was still too much code cluttering the main robot class file. A good portion of the code simply knitted the various modules together, and it obscured what the robot was actually doing.
The solution? I created an Abstract robot class called
AbstractBot to hide the knitting code, standard initialization, and other nasty details.
AbstractBot class has several useful methods that simplify radar operation, movement, target selection, aiming, firing, and more. Now, instead of writing code to evaluate all possible targets, pick the best target, turn the radar, calculate how much energy to use, decide which move to make, and so on, I simply extend the
AbstractBot class and code something like:
EnemyBot target = pickTarget(); scan(target); ram(target); blast(target);
Or like this:
EnemyBot target = pickTarget(); scan(rammingBot); evadeRam(rammingBot); aimAndShoot(target);
It's obvious what the robot does, but not how it does it. The details are conveniently hidden in the
AbstractBot and other classes that control the radar, moving, target selection, firing, and so on. The code is much easier to read, and consequently, much easier to change. Mission accomplished. Now I just have to concentrate on beating Predator!
- Read all of the Secrets from the Robocode masters. This page will be updated as new tips become available.
- Robocode's creator, Mathew Nelson, maintains the official Robocode site. This should be the first stop for anyone serious about Robocode.
- "Rock 'em, sock 'em Robocode" (developerWorks, January 2002) disarms Robocode and starts you on your way to building your own customized lean, mean, fighting machine.
- In "Rock 'em, sock 'em Robocode: Round 2" (developerWorks, May 2002), Sing Li looks at advanced robot construction and team play.
- New to Java? Check out "Introduction to Java programming" (developerWorks, November 2004), a tutorial that steps you through the fundamentals of Java language programming.