Skip to content

Instantly share code, notes, and snippets.

@earlwlkr
Created November 30, 2016 10:43
Show Gist options
  • Select an option

  • Save earlwlkr/a5ff48098df2dcd5610eea2bf7c18acf to your computer and use it in GitHub Desktop.

Select an option

Save earlwlkr/a5ff48098df2dcd5610eea2bf7c18acf to your computer and use it in GitHub Desktop.
var occupiedCastles = [];
var pickedWrenches = [];
function play(state) {
var wrenches = state.wrenches;
var others = state.others;
for (var i = 0; i < state.bots.length; i++) {
var bot = state.bots[i];
if (attackIfNearEnemies(bot, others)) {
console.log('attackIfNearEnemies');
continue;
}
if (occupyCastle(bot, state.castles)) {
console.log('occupyCastle');
continue;
}
if (bot.wrenches >= 3) {
bot.build();
} else {
var closestWrenchIndex = findUnpickedClosestWrench(bot, wrenches);
if (closestWrenchIndex >= 0) {
if (bot.x === wrenches[closestWrenchIndex].x
&& bot.y === wrenches[closestWrenchIndex].y) {
bot.collect();
pickedWrenches.push(wrenches[closestWrenchIndex]);
} else {
bot.moveTo(wrenches[closestWrenchIndex]);
}
} else {
bot.moveTo({ x: bot.x + 1, y: bot.y + 1 });
}
}
}
}
function occupyCastle(bot, castles) {
var index = -1, minLength = 100;
for (var i = 0; i < castles.length; i++) {
if (!hasItem(occupiedCastles, castles[i])) {
var distance = getLength(bot, castles[i]);
if (distance === 0) {
occupiedCastles.push(castles[i]);
return true;
}
if (distance < minLength) {
minLength = distance;
index = i;
}
} else if (castles[i].x === bot.x && castles[i].y === bot.y) {
return true;
}
}
if (index === -1) {
return false;
}
if (castles[index].x === bot.x && castles[index].y === bot.y) {
occupiedCastles.push(castles[index]);
} else {
bot.moveTo(castles[index]);
}
return true;
}
function attackIfNearEnemies(bot, enemies) {
if (bot.wrenches < 2) {
return false;
}
for (var i = 0; i < enemies.length; i++) {
var distance = getLength(bot, enemies[i]);
if (distance === 1) {
bot.attack(enemies[i]);
return true;
}
}
return false;
}
function findUnpickedClosestWrench(bot, wrenches) {
var index = -1, minLength = 100;
for (var i = 0; i < wrenches.length; i++) {
if (!hasItem(pickedWrenches, wrenches[i])) {
var distance = getLength(bot, wrenches[i]);
if (distance < minLength) {
minLength = distance;
index = i;
}
}
}
return index;
}
function hasItem(arr, item) {
for (var j = 0; j < arr.length; j++) {
if (arr[j].x === item.x && arr[j].y === item.y) {
return true;
}
}
return false;
}
function getLength(first, second) {
return Math.sqrt((first.x - second.x) * (first.x - second.x)
+ (first.y - second.y) * (first.y - second.y));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment