http://robowiki.net/w/api.php?action=feedcontributions&user=71.36.111.22&feedformat=atomRobowiki - User contributions [en]2022-10-06T00:10:03ZUser contributionsMediaWiki 1.34.1http://robowiki.net/w/index.php?title=GuessFactor_Targeting_Tutorial&diff=2221GuessFactor Targeting Tutorial2008-06-03T01:26:57Z<p>71.36.111.22: ripped the tutorial from the old wiki</p>
<hr />
<div>The Guess Factor Targeting Tutorial by Kawigi<br />
<br />
GuessFactorTargeting is a simple idea and is also one of the most effective and practical targeting algorithms used in Robocode. This tutorial will go over how to make a simple GuessFactorTargeting gun, based loosely on code from FloodMini, who sports one of the most effective versions of the algorithm to date.<br />
<br />
This tutorial is meant for people who already have an understanding of the Robocode API and know how to use non-blocking (setXXX) calls effectively.<br />
<br />
How it works<br />
<br />
Many people already know what GuessFactorTargeting is all about, and they can probably skip this part. It was thought up by Paul Evans and first implemented in his fine robot, SandboxLump. He explains the algorithm [here]. However, some features of the original implementation were overly complex and possibly even less effective for one-on-one in today's competitive environment.<br />
<br />
The philosophy and assumption we make for GuessFactorTargeting is that our enemy is moving randomly in some way or another (in PatternMatching, we wouldn't be assuming that). The direction we need to shoot is the sum of several random decisions made by our enemy. One nice thing about sums of random values is that they tend to show statistical trends. The trick to GuessFactorTargeting is to find out which direction we should shoot each time we fire, and in the future, we fire in the direction that was correct the most often.<br />
<br />
Guess Factor Targeting Terminology<br />
<br />
GuessFactor - a direction that may be fired in. Usually people talk about GuessFactors normalized over the maximum escape angle, where shooting directly where we see our target is GF 0.0, shooting as far ahead of our target as they could possibly get by the time our bullet would reach them is GF 1.0, and firing just as far behind them is GF -1.0. Note that to find this, we need to know what the maximum angle is as well as whether they are moving around us to the right (clockwise) or to the left (counter-clockwise).<br />
<br />
MovementProfile - The combination of directions we could fire and the frequency that each direction is correct is what people refer to as the bot's "profile". Using tools like FloodGrapher, RoboGrapher and SmogPainter, you can actually view the profile of a give bot from saved data of other robots.<br />
<br />
RollingAverages - Also called moving averages and some other things. Basically a way of favoring newer data over older data. A guess-factor gun can be awful against a robot that changes its movement unless it uses rolling averages, however, for simplicity, I probably won't implement them in this tutorial.<br />
<br />
Segmentation - Sometimes we can get more relevant data by splitting it up on some parameters, rather than just looking at the general profile.<br />
<br />
VirtualBullets - An object that tracks where a bullet would be if it were fired along a certain trajectory and finds out if it would hit at that trajectory or not. These were used in all of the earliest guess factor guns to analyze the bot's MovementProfile.<br />
<br />
Waves - Most current robots that use GuessFactorTargeting use Waves to find the bearing that they should have shot at, as an alternative to using several VirtualBullets. These are a little more efficient in general, and can also be modified slightly to give the exact same results as VirtualBullets (tracking ALL angles that would have hit, rather than just the median). This tutorial will use a Wave implementation.<br />
<br />
Getting started<br />
<br />
First of all, I'm going to assume you already have a robot with some kind of Movement and Radar where the radar scans your enemy at least most of the time. Check other parts of the wiki for more information on that before continuing if you don't understand it. Let's start by implementing the wave bullet, since finding out what direction we should have used at any time is at the core of this algorithm.<br />
<br />
The data we need to do our work is basically these:<br />
<br />
* the location we are firing from<br />
* the time we fired<br />
* what clock direction our opponent is moving in relative to us (1 for clockwise, -1 for counterclockwise)<br />
* where GuessFactor 0 is (i.e. - the direction to our target at firetime)<br />
* the power (really the speed) of the bullet<br />
* where to return the "answer" to. <br />
<br />
import java.awt.geom.*;<br />
import robocode.util.Utils;<br />
<br />
public class WaveBullet<br />
{<br />
private double startx, starty, startBearing, power;<br />
private long fireTime;<br />
private int direction;<br />
private int[] returnSegment;<br />
<br />
public WaveBullet(double x, double y, double bearing, double power, int direction, long time, int[] segment)<br />
{<br />
startx = x;<br />
starty = y;<br />
startBearing = bearing;<br />
this.power = power;<br />
this.direction = direction;<br />
fireTime = time;<br />
returnSegment = segment;<br />
}<br />
<br />
Now let's add a few useful utility functions that will come in useful:<br />
<br />
public double getBulletSpeed()<br />
{<br />
return 20-power*3;<br />
}<br />
<br />
public double maxEscapeAngle()<br />
{<br />
return Math.asin(8/getBulletSpeed());<br />
}<br />
<br />
It may not be obvious why the max escape angle is asin(8/bulletspeed) regardless of distance or any other considerations, but that is the furthest angle our enemy can theoretically be relative to where they were when we fired. More discussion on why this is the case is elsewhere on the wiki. If you ever get more than that, it is usually due to the discrete tick-based physics of robocode (i.e. - you can't hit someone with a bullet at time 7.5, so it will hit them at 8 and they will have gone just a little bit further), and due to imperfect data (especially missed scans).<br />
<br />
Now let's get into the most significant part of our code - this method will check if the wave has hit the enemy. If it hasn't, it will simply return false. If it has, it will figure out what GuessFactor the enemy is at, find the appropriate index into the returnSegment and increment it. Then it will return true if it hit. Return true signifies that the wave should no longer be tracked.<br />
<br />
public boolean checkHit(double enemyX, double enemyY, long currentTime)<br />
{<br />
//if the distance from the wave origin to our enemy has passed the distance the bullet would have traveled...<br />
if (Point2D.distance(startx, starty, enemyX, enemyY) <= (currentTime-fireTime)*getBulletSpeed())<br />
{<br />
double desiredDirection = Math.atan2(enemyX-startx, enemyY-starty);<br />
double angleOffset = Utils.normalRelativeAngle(desiredDirection-startBearing);<br />
double guessFactor = Math.max(-1, Math.min(1, angleOffset/maxEscapeAngle()))*direction;<br />
int index = (int)Math.round((returnSegment.length-1)/2*(guessFactor+1));<br />
returnSegment[index]++;<br />
return true;<br />
}<br />
return false;<br />
}<br />
}<br />
<br />
...and that's the end of our WaveBullet? class. Now we need to use it in our robot. First we need to create some sort of structure to store them in. I think an ArrayList or Vector is most appropriate. To make PEZ happier, I'll declare it as a generic List and then initialize it as an ArrayList. Note that if you have multiple threads that may want to access the list, you'll want to use a Vector instead, because ArrayLists aren't thread-safe. So this goes somewhere in your global variable declarations:<br />
<br />
List waves = new ArrayList();<br />
<br />
Note that it's not static, because I don't want to update artifact waves in the next round if I can avoid it. And some other things we will need for this:<br />
<br />
static int[] stats = new int[31]; //31 is the number of unique guessfactors we're using<br />
int direction = 1;<br />
<br />
Now the fun work goes into creating and updating these waves in our onScannedRobot method.<br />
<br />
public void onScannedRobot(ScannedRobotEvent e)<br />
{<br />
...<br />
(other onScannedRobot code)<br />
...<br />
double absBearing = getHeadingRadians() + e.getBearingRadians();<br />
//find our enemy's location:<br />
double ex = getX() + Math.sin(absBearing)*e.getDistance();<br />
double ey = getY() + Math.cos(absBearing)*e.getDistance();<br />
<br />
//let's process the waves now:<br />
for (int i=0; i<waves.size(); i++)<br />
{<br />
WaveBullet currentWave = (WaveBullet)waves.get(i);<br />
if (currentWave.checkHit(ex, ey, getTime())<br />
{<br />
waves.remove(currentWave);<br />
i--;<br />
}<br />
}<br />
<br />
double power = Math.min(3, Math.max(.1, /* some function */));<br />
//don't try to figure out the direction they're moving if they're not moving, just use the direction we had before<br />
if (e.getVelocity() != 0)<br />
if (Math.sin(e.getHeadingRadians()-absBearing)*e.getVelocity() < 0)<br />
direction = -1;<br />
else<br />
direction = 1;<br />
int[] currentStats = stats; //This seems silly, but I'm using it to show something else later<br />
WaveBullet newWave = new WaveBullet(getX(), getY(), absBearing, power, direction, getTime(), currentStats);<br />
<br />
Now we've processed our waves and created a new one for the current scan. Now it would be useful to use our data to actually aim. Note that this is exceptionally fast and we can get away with doing it every scan without a major performance hit:<br />
<br />
int bestindex = 15; //initialize it to be in the middle, guessfactor 0.<br />
for (int i=0; i<31; i++)<br />
if (currentStats[bestindex] < currentStats[i])<br />
bestindex = i;<br />
<br />
//this should do the opposite of the math in the WaveBullet:<br />
guessfactor = (double)(bestindex-(stats.length-1)/2)/((stats.length-1)/2);<br />
double angleOffset = direction*guessfactor*newWave.maxEscapeAngle();<br />
setTurnGunRightRadians(robocode.util.Utils.normalRelativeAngle(absBearing-getGunHeadingRadians()+angleOffset));<br />
<br />
Now we want to fire. If the firing actually happens, we add the new wave bullet to our ArrayList.<br />
<br />
if (setFireBullet() != null)<br />
waves.add(newWave);<br />
}<br />
<br />
And that pretty much concludes the onScannedRobot method, as well as the code of a basic unsegmented guessfactor gun. Of course, this gun won't be overly effective against most opponents. In order to make it more effective, it is best to "segment" this data depending on the situation, rather than using just a single 1-dimensional array of ints. For instance, it's fairly normal to segment on either distance or projected bullet flight time (distance / bulletSpeed). If you want to segment on distance every 100 pixels, you could change your declaration for the stat buffer to this:<br />
<br />
int[][] stats = new int[13][31];<br />
<br />
... then you need to change one line in your onScannedRobot method, where you declare the array currentStats:<br />
<br />
int[] currentStats = stats[(int)(e.getDistance()/100)];<br />
<br />
Now stats from different distances will no longer be stored together. Experiment with different segmentation axes to see what works well. For a little discussion on effective segmentation schemes, look at the discussion on SegmentedData/Segments.</div>71.36.111.22