Difference between revisions of "XanderFramework"

From Robowiki
Jump to navigation Jump to search
m (→‎Xander Drives: extra note about compound drive)
(Reworking this page)
Line 1: Line 1:
 
The Xander framework is an AdvancedRobot framework that makes it easy to build new bots by combining different guns, radars, and drives.  It is based on an abstract class named AbstractXanderBot that extends AdvancedRobot.  For a gun, drive, or radar to be used in the Xander framework, it has to implement the corresponding interface Gun, Drive, or Radar.
 
The Xander framework is an AdvancedRobot framework that makes it easy to build new bots by combining different guns, radars, and drives.  It is based on an abstract class named AbstractXanderBot that extends AdvancedRobot.  For a gun, drive, or radar to be used in the Xander framework, it has to implement the corresponding interface Gun, Drive, or Radar.
  
= Xander Components =
+
= Xander Framework =
 +
The Xander framework is a framework on which Robocode robots can be built.  This section details the core framework.
 +
== Base Robot Class ==
 +
Xander robots extend the '''AbstractXanderBot''' class.  The '''AbstractXanderBot''' class contains basic robot setup code and a basic processing loop. 
 +
 
 +
The basic setup code performs as follows:
 +
*  If it's the first round...
 +
**  Create new configuration and call the configure(Configuration) method.
 +
*  Otherwise...
 +
**  Get configuration from the ''static resource mananger''
 +
*  call methods setAdjustGunForRobotTurn(true), setAdjustRadarForGunTurn(true), and setAdjustRadarForRobotTurn(true)
 +
*  apply robot styling
 +
*  initialize ''robot history'' and ''bullet history''
 +
*  create or load radar, drive, and gun
 +
*  call initalizeForNewRound(AbstractXanderBot) on all static resources
 +
*  create ''radar controller'', ''drive controller'', and ''gun controller''
 +
*  call drive and gun initialize(...) methods
 +
 
 +
The basic processing loop performs as follows:
 +
*  Query radar for target
 +
*  If no target is locked...
 +
** Tell drive to drive without a target
 +
*  Otherwise...
 +
** Tell drive to drive with given target
 +
** If target is disabled...
 +
*** Fire on target with Head-On gun
 +
** Otherwise...
 +
*** Fire on target with main gun
 +
* Notify turn listeners of turn event
 +
* call execute()
 +
 
 +
A Xander robot ''must'' implement the following methods:
 +
*  Radar createRadar() - creates the radar
 +
*  Drive createDrive() - creates the drive
 +
*  Gun createGun() - creates the gun
 +
 
 +
In addition, a Xander robot may optionally override the following methods:
 +
*  void configure(Configuration) - allows basic configuration of the robot to be changed
 +
*  RobotStyle getRobotStyle() - provides robot styling options like robot colors
 +
*  void doFinishingMoves() - moves to perform after winning a round
 +
 
 +
== Controllers ==
 +
Radars, guns, and drives query and control the robot through ''controller'' classes.  The controller classes all extend a basic '''AbstractController''' class.  The '''AbstractController''' class provides access to most of the robot's getXxx methods, while the specific controllers for radar, gun, and drive provide further access to the corresponding setXxx methods.  This approach help to prevent components from doing operations that are outside their area of responsibility, and also prevents components from calling the basic '''Robot''' control methods, or any methods that would immediately cause a turn to end.
 +
 
 +
== Robot History ==
 +
Robot history is available through the '''RobotHistory''' class, and is accessible via the '''AbstractController''' class.  Robot history for a particular point in time is stored in a ''robot snapshot'' via the '''RobotSnapshot''' class.  Each turn, a new snapshot for itself is generated and stored in the history.  Each scan, a new snapshot for the scanned robot is generated and stored in the history.  Robot history allows the robot to look back at snapshots of itself and it's opponents back a set number of turns and scans.  How far back it goes can be configured by overriding methods in the '''AbstractXanderBot''' class, but in future versions this will be configurable through the '''Configuration''' class.
 +
 
 +
== Bullet History ==
 +
Bullet history provides information on enemy bullets fired.  Information about a fired bullet is stored as a '''BulletWave'''.  Bullet history is available through the '''BulletHistory''' class, and is accessible via the '''AbstractController''' class.  The bullet history also keeps track of the opponent's hit ratio.  Any component wishing to be informed of enemy bullet fired events can register itself as an with the bullet history as a '''BulletWaveListener'''.
 +
 
 +
The '''BulletWaveListener''' interface:
 +
<pre>
 +
public interface BulletWaveHitListener {
 +
 
 +
/**
 +
* Action to perform when a bullet wave is created.
 +
*
 +
* @param event          the bullet fired event
 +
* @param bulletWave    the bullet wave created
 +
*/
 +
public void onBulletWaveCreated(BulletFiredEvent event, BulletWave bulletWave);
 +
 +
/**
 +
* Action to perform when a bullet wave passes our location.
 +
*
 +
* @param bulletWave  bullet wave that passed our location
 +
*/
 +
public void onBulletWaveHit(BulletWave bulletWave);
 +
 +
/**
 +
* Action to perform when hit by a bullet.
 +
*
 +
* @param bulletWave  matching wave for bullet we were hit by
 +
*/
 +
public void onHitByBullet(HitByBulletEvent event, BulletWave bulletWave);
 +
 +
/**
 +
* Action to perform when bullet wave is obsolete and has been removed from history.
 +
*
 +
* @param bulletWave  wave that is removed from history
 +
*/
 +
public void onBulletWaveDestroyed(BulletWave bulletWave);
 +
}
 +
</pre>
 +
 
 +
== Radar ==
 +
== Drive ==
 +
== Gun ==
 +
== Events ==
 +
 
 +
= Xander Framework Components =
 +
Most of these components are not considered part of the Xander framework core; they are more accurately thought of as components built for the Xander framework.  Exceptions to this are '''CompoundDrive''' and '''CompoundGun''', which are part of the basic Xander philosophy, and the '''HeadOnGun''', as it is used by a Xander framework core class and must therefore be considered part of the framework.
 
== Xander Radars ==
 
== Xander Radars ==
 
=== BasicRadar ===
 
=== BasicRadar ===

Revision as of 15:08, 19 June 2011

The Xander framework is an AdvancedRobot framework that makes it easy to build new bots by combining different guns, radars, and drives. It is based on an abstract class named AbstractXanderBot that extends AdvancedRobot. For a gun, drive, or radar to be used in the Xander framework, it has to implement the corresponding interface Gun, Drive, or Radar.

Xander Framework

The Xander framework is a framework on which Robocode robots can be built. This section details the core framework.

Base Robot Class

Xander robots extend the AbstractXanderBot class. The AbstractXanderBot class contains basic robot setup code and a basic processing loop.

The basic setup code performs as follows:

  • If it's the first round...
    • Create new configuration and call the configure(Configuration) method.
  • Otherwise...
    • Get configuration from the static resource mananger
  • call methods setAdjustGunForRobotTurn(true), setAdjustRadarForGunTurn(true), and setAdjustRadarForRobotTurn(true)
  • apply robot styling
  • initialize robot history and bullet history
  • create or load radar, drive, and gun
  • call initalizeForNewRound(AbstractXanderBot) on all static resources
  • create radar controller, drive controller, and gun controller
  • call drive and gun initialize(...) methods

The basic processing loop performs as follows:

  • Query radar for target
  • If no target is locked...
    • Tell drive to drive without a target
  • Otherwise...
    • Tell drive to drive with given target
    • If target is disabled...
      • Fire on target with Head-On gun
    • Otherwise...
      • Fire on target with main gun
  • Notify turn listeners of turn event
  • call execute()

A Xander robot must implement the following methods:

  • Radar createRadar() - creates the radar
  • Drive createDrive() - creates the drive
  • Gun createGun() - creates the gun

In addition, a Xander robot may optionally override the following methods:

  • void configure(Configuration) - allows basic configuration of the robot to be changed
  • RobotStyle getRobotStyle() - provides robot styling options like robot colors
  • void doFinishingMoves() - moves to perform after winning a round

Controllers

Radars, guns, and drives query and control the robot through controller classes. The controller classes all extend a basic AbstractController class. The AbstractController class provides access to most of the robot's getXxx methods, while the specific controllers for radar, gun, and drive provide further access to the corresponding setXxx methods. This approach help to prevent components from doing operations that are outside their area of responsibility, and also prevents components from calling the basic Robot control methods, or any methods that would immediately cause a turn to end.

Robot History

Robot history is available through the RobotHistory class, and is accessible via the AbstractController class. Robot history for a particular point in time is stored in a robot snapshot via the RobotSnapshot class. Each turn, a new snapshot for itself is generated and stored in the history. Each scan, a new snapshot for the scanned robot is generated and stored in the history. Robot history allows the robot to look back at snapshots of itself and it's opponents back a set number of turns and scans. How far back it goes can be configured by overriding methods in the AbstractXanderBot class, but in future versions this will be configurable through the Configuration class.

Bullet History

Bullet history provides information on enemy bullets fired. Information about a fired bullet is stored as a BulletWave. Bullet history is available through the BulletHistory class, and is accessible via the AbstractController class. The bullet history also keeps track of the opponent's hit ratio. Any component wishing to be informed of enemy bullet fired events can register itself as an with the bullet history as a BulletWaveListener.

The BulletWaveListener interface:

public interface BulletWaveHitListener {

	/**
	 * Action to perform when a bullet wave is created.
	 * 
	 * @param event          the bullet fired event
	 * @param bulletWave     the bullet wave created
	 */
	public void onBulletWaveCreated(BulletFiredEvent event, BulletWave bulletWave);
	
	/**
	 * Action to perform when a bullet wave passes our location.
	 * 
	 * @param bulletWave   bullet wave that passed our location
	 */
	public void onBulletWaveHit(BulletWave bulletWave);
	
	/**
	 * Action to perform when hit by a bullet.
	 * 
	 * @param bulletWave   matching wave for bullet we were hit by
	 */
	public void onHitByBullet(HitByBulletEvent event, BulletWave bulletWave);
	
	/**
	 * Action to perform when bullet wave is obsolete and has been removed from history.
	 * 
	 * @param bulletWave   wave that is removed from history
	 */
	public void onBulletWaveDestroyed(BulletWave bulletWave);
}

Radar

Drive

Gun

Events

Xander Framework Components

Most of these components are not considered part of the Xander framework core; they are more accurately thought of as components built for the Xander framework. Exceptions to this are CompoundDrive and CompoundGun, which are part of the basic Xander philosophy, and the HeadOnGun, as it is used by a Xander framework core class and must therefore be considered part of the framework.

Xander Radars

BasicRadar

Basic radar scan the field, and locks onto the first target it finds. Target can switch if another robot happens to be closer and drives through the scan beam.

Xander Guns

Xander guns must implement the Gun interface.

AntiMirrorGun

Specifically for targeting opponents who use a mirroring drive strategy. Must be used in combination with the AntiMirrorDrive.

BSProtectedGun

A wrapper for other guns that provides support for counteracting bullet shielding.

CircularGun

This gun is for targeting opponents that drive in circles. If the opponent does not appear to be going in circles, this gun will not fire on the target.

HeadOnGun

Head-on shots.

LinearGun

This gun is for targeting opponents that drive in a straight line. It fires on the opponent based on the opponents current speed and heading. It does not attempt to determine whether the target is actually moving in a straight line or not.

StatGun

This gun is a "guess factor" gun that relies on statistics to determine how to aim. If will not fire until there are sufficient stats to make a good guess. It relies on a Segmenter to determine how to categorize the statistics it collects (Segmenter is a separate interface).

AdvancedStatGun

Extends the StatGun, adding the capability of using an AdvancedSegmenter such that multiple combinations of segmenters can be used on the fly.

CompoundGun

Combines two or more other guns. Compound gun delegates gunning to other guns based on a GunSelector. By default, a CompoundGun uses the FirstAvailGunSelector.

GunSelector

Compound guns can be set up with different gun selection modules. At present, I have two available gun selection modules:

  • FirstAvailGunSelector - original behavior before gun selectors, this one just hands off to the first gun it finds that claims it can fire at the target.
  • HitRatioGunSelector - this gun selector looks at gun hit ratios and bullets fired for each gun to determine which gun to fire with.
  • VirtualHitRatioGunSelector - this gun selector looks at virtual hit ratios to determine what gun to fire with.

Xander Drives

Xander drives must implement the Drive interface.

AntiMirrorDrive

Drive specifically for use with opponents who use a mirroring drive strategy. This drive must be used in combination with the AntiMirrorGun.

BasicSurferDrive

This drive is an adaptation of the Wave Surfing drive used in the BasicGFSurfer robot.

CompoundDrive

A drive that combines multiple other drives.

DriveSelector

Interface that provides the means for selecting between drives.

OrbitalDrive

This drive approaches the target using linear targeting and then, when it range, orbits around the target, changing direction periodically. It originally also used "inverse gravity bullet avoidance", although this is no longer the case; this feature was an early experimental feature of the framework, and has since been removed in favor of tracking bullet "waves" without predicting the firing direction.

RamboDrive

This drive attempts to ram the enemy. It can be configured so that it does not approach the enemy in a straight line, but the effectiveness may still be limited against the better bots out there.

RamEscapeDrive

For getting away from needy robots who always want a hug.

StatDrive

This drive is a Wave Surfing drive of my own design. Similar to the StatGun, it supports using a segmenter, and a compound drive segmenter is available to combine the effects of multiple drive segmenters.

AdvancedStatDrive

Extends the StatDrive, adding the capability of using an AdvancedSegmenter.

Segmentation

Drives and guns now use a single set of segmenters. Basic segmenters must implement the Segmenter interface. Current available segmenters include:

  • AdvancedCompoundSegmenter - implements the AdvancedSegmenter interface, which in turn extends the Segmenter interface. This is the most advanced form of segmenter that combines multiple other segmenters in a way where different combinations of those segmenters can be used independently. It is used by the AdvancedStatDrive and AdvancedStatGun.
  • CompoundSegmenter - A segmenter that combines multiple other segmenters. The combined segmenters are always analyzed together in combination.
  • BulletSpeedSegmenter - segments on bullet speed
  • BulletTravelTimeSegmenter - segments on bullet travel time
  • DefenderAccelerationSegmenter - segments on defender acceleration
  • DefenderSpeedSegmenter - segments on defender speed
  • DistanceSegmenter - segments on distance between robots
  • LateralVelocitySegmenter - segments on lateral velocity
  • NullSegmenter - provides no segmentation (a segmenter with only a single segment).
  • RelativeDirectionSegmenter - segments on whether opponent appears to be orbiting clockwise or counter-clockwise.
  • WallSmoothingSegmenter - segments on whether it appears defender will have to wall smooth clockwise, counter-clockwise, both directions (in corner), or not at all.

Xander Utilities

DriveHelper

The DriveHelper can be used by drives or guns to assist with driving issues such as dealing with "back-as-front" and predicting drive paths.

Logging

The Xander framework provides basic logging services loosely based on the Log4J logging model. Though not nearly as configurable as Log4J logging, it is much more advanced than just using System.out.print statements.

Xander logs have the following levels, in order of significance:

  • DEBUG - Debugging messages.
  • INFO - Informational messages. This is the default logging level.
  • WARNING - Warning messages.
  • STAT - Statistics messages. These are meant to be messages that are useful during development, but also of interest for a finished robot.
  • ERROR - Error messages.

Log levels are defined by the nested Enum named Level in the Log class (e.g. the level INFO would be accessed via Log.Level.INFO)

Logging consists of two classes: Logger and Log. Each class can have it's own Log. A Log is created by the Logger.

A Log can currently be created in a manner similar to as follows:

public class ExampleClass {

	private static final Log log = Logger.getLog(ExampleClass.class);

}

Once created, it can be used by calling the appropriate methods of the Log class as in the following example:

	log.info("This is an informational message.");

Similar to Log4J, log messages will only be printed if the level of the message is at or above the level set in the Log. By default, all Logs are at level INFO. This can be changed globally on startup through the Logger class, or on a Log by Log basis.

The main Xander robot class, AbstractXanderBot, provides a protected method getDefaultLogLevel() for setting the global logging level on startup. Robots using the Xander framework can override this method to change the default logging level for all Logs.

Mathematics

Circular

This class contains methods specific to circular targeting. These methods are available outside the CircularGun because it is possible that other components may have use for calculating circular paths.

Linear

This class contains methods specific to linear targeting. These methods are available outside the LinearGun because it is possible thar other components may have use for calculating linear paths. For example, a drive may be interested in approaching an opponent using a linear intercept path.

MathUtil

This class provides generic math helper functions. Most are targeted at solving Robocode problems, but are still usable in a more generic sense.

RoboPhysics

This class provides constants and methods that are only useful within the context of Robocode. Some of what it provides is obsolete due to various additions to the Robocode API over the last few years -- specifically the Robocode Rules and Utils classes -- but I leave it there for posterity.

Xander Code Examples

Radars, Gun, and Drives

Radars, Guns, and Drives all follow a similar pattern. Each must implement an interface. The methods defined in the interfaces provide a controller as an argument. Controllers are actually wrappers for the main robot class that limit exposure of main class methods to only those methods they should be allowed to call. For example, a Gun is allowed to call methods to turn the gun, but is not allowed to call methods that would turn the radar or robot body.

As an example, below is the Gun interface. However, note that it will likely change before the Xander framework is considered complete:

/**
 * Interface to be implemented by XanderBot gun classes.
 * 
 * @author Scott Arnold
 */
public interface Gun {

	public String getName();
	
	public void initialize(GunController gunController);
	
	public boolean canFireAt(String robotName, GunController gunController);
		
	public void fireAt(String robotName, GunController gunController);
	
}

At present, Controllers are recreated at the beginning of each round. It is primarily for this reason that the initialize(...) method is provided.

Main Robot Class

As an example of how the Xander framework is used, below is the source for the main robot class of XanderCat 2.0.

/**
 * 1-on-1 robot built on the Xander framework.  Also suitable for melee.
 * 
 * @author Scott Arnold
 */
public class XanderCat extends AbstractXanderBot {	
	
	@Override
	protected Level getLogLevel() {
		return Log.Level.INFO;
	}

	@Override
	protected Radar createRadar() {
		return new BasicRadar(this, 45, 5);
	}

	@Override
	protected Drive createDrive() {
		return new OrbitalDrive(this, 200, 40, 0.5f);
	}

	@Override
	protected Gun createGun() {
		FiringProfile firingProfile = new FiringProfile(
				1.0d, 500d, 3.0d, 150d, 0.5d, 450d, 700d);
		Segmenter segmenter = new CompoundSegmenter(
				new BulletTravelTimeSegmenter(getName(), 12, getBattlefieldBounds()),
				new RelativeDirectionSegmenter(10));
		return new CompoundGun(
				new StatGun(this, firingProfile, 1000, 10, 30, segmenter, true),
				new CircularGun(firingProfile), 
				new LinearGun(firingProfile));
	}

}

Handling Static Data

In order to remember information from one battle to the next, it is necessary to save that information in some static variable or object. However, this would seem to cause problems if you want to pit a robot against itself, or if you want to run two different robots off of the same base framework classes. This would seem to be a problem because suddenly you have two or more distinct robots sharing certain static resources, when each robot should have it's own unique set. However, Robocode uses a separate class loader for every robot, putting each robot in it's own isolated sandbox. This means static variables are not shared among robots.

The Xander framework attempts to adhere to good object oriented practices; declaring variables or objects as static to preserve them between rounds is considered contrary to this. Therefore, the Xander framework provides a static resource manager. The static resource manager is a singleton that stores objects in a static Map. Whenever a variable or object needs to be kept or retrieved from round to round, the static resource manager instance is obtained, and then the variable or object is stored or retrieved from it.

The static resource manager supports storing two different kinds of objects, which are referred to as resources and properties:

  • A resource is something like a radar, drive, or gun, that there will only be a single instance of. Resources must implement the StaticResource interface. Resources are retrieved by their class.
  • A property is meant to be a simple value such as an Integer or a String. Properties are stored and retrieved by key values. A key value must be a String.

Resources

Resources must implement the StaticResource interface. The StaticResource interface serves two purposes. First, the Xander framework detects any radar, drive, or gun that implements StaticResource, and will automatically register that component with the static resource manager. This means simply by implementing the interface, you are assured that your entire component will be treated in a static manner. Second, it requires the object to implement an initializeForNewRound(...) method, in order for that object to do any between round cleanup. Cleanup could potentially be done elsewhere, but requiring a seperate method in the interface serves as a good reminder to anyone implementing StaticResource that they need to think about any state that should be cleaned up between rounds.

Generally speaking, you shouldn't need to register or lookup resources, as only radars, drives, and guns are meant to be resources, and they are automatically handled by the Xander framework.

Registering a Resource

StaticResourceManager srm = StaticResourceManager.getInstance();
srm.register(myResource);

Looking Up a Resource

StaticResourceManager srm = StaticResourceManager.getInstance();
MyResource myResource = srm.getResource(MyResource.class);

Properties

Properties are more free-form. They are intended to be simple values, like Strings, but the static resource manager does not place any hard restrictions on what is stored. Properties must be stored and retrieved by a String key value. The key value can be any unique String the programmer chooses.

Storing a Property

StaticResourceManager srm = StaticResourceManager.getInstance();
srm.store("myKey",myProperty);

Looking Up a Property

StaticResourceManager srm = StaticResourceManager.getInstance();
MyProperty myProperty = srm.getProperty("myKey");