Robocode:onScannedRobot 的精度

Robocode: precision of onScannedRobot

我写了一个相对简单的AdvancedRobot,它转动雷达并记录所有敌人的速度。最终,我注意到机器人会在不应该错过的情况下错过。我从 Robocode/Graphical Debugging wiki 复制了代码并进行了测试。这是代码(Wiki 目前已关闭):

// The coordinates of the last scanned robot
int scannedX = Integer.MIN_VALUE;
int scannedY = Integer.MIN_VALUE;

// Called when we have scanned a robot
public void onScannedRobot(ScannedRobotEvent e) {
    // Calculate the angle to the scanned robot
    double angle = Math.toRadians((getHeading() + e.getBearing()) % 360);

    // Calculate the coordinates of the robot
    scannedX = (int)(getX() + Math.sin(angle) * e.getDistance());
    scannedY = (int)(getY() + Math.cos(angle) * e.getDistance());
}

和事件处理程序:

// Paint a transparent square on top of the last scanned robot
public void onPaint(Graphics2D g) {
    // Set the paint color to a red half transparent color
    g.setColor(new Color(0xff, 0x00, 0x00, 0x80));

    // Draw a line from our robot to the scanned robot
    g.drawLine(scannedX, scannedY, (int)getX(), (int)getY());

    // Draw a filled square on top of the scanned robot that covers it
    g.fillRect(scannedX - 20, scannedY - 20, 40, 40);
}

"filled square"绝对不在机器人上面。下面显示了几个屏幕截图。看起来精度取决于距离,但我不确定。这是预料之中的,还是我做错了什么?

我想我知道问题出在哪里了。似乎没有记录;如果我错了,请post一个link。 ScannedRobotEvent 报告相对于 前一个 机器人航向的方位,即最后一次 StatusEvent 命中时的航向。考虑到这一点大大提高了我的机器人的准确性。

发生这种情况的一个原因是 onScannedRobot 事件的传递被延迟,直到 higher priority 事件完成处理。特别是,如果更高优先级的事件处理程序执行旋转 body 的命令,则该命令将在调用 onScannedRobot 之前执行,导致时间提前、机器人移动以及机器人的航向改变。

由于延迟事件传递会导致各种问题,我建议永远不要在事件处理程序中执行命令。相反,事件处理程序应该简单地检查、考虑信息并将信息存储在字段中,以便主循环做出反应。这使主循环能够在执行某项操作之前查看所有可用信息,并智能地 select 考虑到收到的全部信息,哪个操作最合适。例如,它可以查看前面的机器人撞击事件,结合雷达检测到从后面接近的对手,并确定侧向躲避比通常向后方躲避更有希望......