Robocode 高手的秘诀: 因数避墙法(factored wall avoidance)
2009-12-21 00:00:00 来源:WEB开发网添加因数避墙法
我们需要添加的最后一个方法是 adjustHeadingForWalls() 方法。
这个方法的前面一半根据机器人和墙的靠近程度选择 安全的 x 和 y 的位置(机器人当前的 x 或 y 位置,或者如果机器人靠近墙,则就是中心点)。方法的后面一半则计算距离“安全点”的方位,并把这个方位和依机器人离墙远近得到的预想方向都作为因数考虑在内。
可以使用 WALL_AVOID_INTERVAL 和 WALL_AVOID_FACTORS 常量来调整机器人对墙的担忧程度。
清单 3. 避墙法方法private static final double WALL_AVOID_INTERVAL = 10;
private static final double WALL_AVOID_FACTORS = 20;
private static final double WALL_AVOID_DISTANCE =
(WALL_AVOID_INTERVAL * WALL_AVOID_FACTORS);
private double adjustHeadingForWalls(double heading) {
double fieldHeight = getBattleFieldHeight();
double fieldWidth = getBattleFieldWidth();
double centerX = (fieldWidth / 2);
double centerY = (fieldHeight / 2);
double currentHeading = getRelativeHeadingRadians();
double x = getX();
double y = getY();
boolean nearWall = false;
double desiredX;
double desiredY;
// If we are too close to a wall, calculate a course toward
// the center of the battlefield.
if ((y < WALL_AVOID_DISTANCE) ||
((fieldHeight - y) < WALL_AVOID_DISTANCE)) {
desiredY = centerY;
nearWall = true;
} else {
desiredY = y;
}
if ((x < WALL_AVOID_DISTANCE) ||
((fieldWidth - x) < WALL_AVOID_DISTANCE)) {
desiredX = centerX;
nearWall = true;
} else {
desiredX = x;
}
// Determine the safe heading and factor it in with the desired
// heading if the bot is near a wall
if (nearWall) {
double desiredBearing =
calculateBearingToXYRadians(x,
y,
currentHeading,
desiredX,
desiredY);
double distanceToWall = Math.min(
Math.min(x, (fieldWidth - x)),
Math.min(y, (fieldHeight - y)));
int wallFactor =
(int)Math.min((distanceToWall / WALL_AVOID_INTERVAL),
WALL_AVOID_FACTORS);
return ((((WALL_AVOID_FACTORS - wallFactor) * desiredBearing) +
(wallFactor * heading)) / WALL_AVOID_FACTORS);
} else {
return heading;
}
}
汇总
其余的工作很容易。我们可以使用目前的导航算法,将得出的结果送入 adjustHeadingForWalls() 方法来避开墙。
为了保持简单,示例机器人要求方向改变为零,从而试着沿直线移动。
清单 4. 避墙法方法public void run() {
while(true) {
setTurnRightRadiansOptimal(adjustHeadingForWalls(0));
setAhead(100);
execute();
}
}
关于它就是这样了。简单,但有效。
更多精彩
赞助商链接