Skip to content

Instantly share code, notes, and snippets.

@peterjaric
Created December 5, 2012 20:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save peterjaric/4219033 to your computer and use it in GitHub Desktop.
The Tricky Tracker
//FightCode can only understand your robot
//if its class is called Robot
var Robot = function(robot) {
};
var D = {
enemyIds: [],
enemyPositions: {}
};
function addEnemy(robot) {
var i;
var exists = false;
for (i = 0; i < D.enemyIds && !exists; i++) {
exists = D.enemyIds[i] === robot.id;
}
if (!exists) {
robot.log("id: " + robot.id);
D.enemyIds.push(robot.id);
D.enemyPositions[robot.id] = [];
}
}
Robot.prototype.onIdle = function(ev) {
var robot = ev.robot;
robot.ahead(200);
robot.turn(90);
adjustCannon(robot);
};
Robot.prototype.onScannedRobot = function(ev) {
var robot = ev.robot;
var enemy = ev.scannedRobot;
addEnemy(enemy);
updateEnemyPosition(enemy.id, enemy.position);
robot.fire();
adjustCannon(robot);
};
function updateEnemyPosition(id, position) {
if (D.enemyPositions[id].length > 1) {
D.enemyPositions[id].pop();
}
D.enemyPositions[id].push(position);
}
function predictEnemyPosition(id) {
// Stupid implementation
var positions = D.enemyPositions[id];
return positions[positions.length - 1];
}
function adjustCannon(robot) {
var i, dx, dy, angle, pos, deltaAngle;
var bestDeltaAngle = 360;
robot.log(D.enemyIds);
for (i = 0; i < D.enemyIds.length; i++) {
pos = predictEnemyPosition(D.enemyIds[i]);
dx = pos.x - robot.position.x;
dy = pos.y - robot.position.y;
angle = Math.atan2(dy, dx) * 180 / Math.PI;
deltaAngle = robot.cannonAbsoluteAngle - angle;
if (Math.abs(deltaAngle) < Math.abs(bestDeltaAngle)) {
bestDeltaAngle = deltaAngle;
}
}
robot.rotateCannon(bestDeltaAngle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment