Skip to content

Instantly share code, notes, and snippets.

@Ravaelles
Created March 25, 2016 20:56
Show Gist options
  • Save Ravaelles/6c89e779c7bae2002645 to your computer and use it in GitHub Desktop.
Save Ravaelles/6c89e779c7bae2002645 to your computer and use it in GitHub Desktop.
private static Unit getMineralFieldToGather(Unit worker) {
// Get nearest base for this unit
Unit base = Select.ourBases().nearestTo(worker.getPosition());
if (base == null) {
return null;
}
// Get minerals near to our main base and sort them from closest to most distant one
List<Unit> minerals = (List<Unit>) Select.minerals().inRadius(12, base.getPosition()).listUnits();
if (!minerals.isEmpty()) {
// Count how many other workers gather this mineral
Map<Unit, Integer> workersPerMineral = new HashMap<>();
Collection<Unit> ourWorkersInRange = (Collection<Unit>) Select.ourWorkers().inRadius(12, base.getPosition()).list();
// for (Unit otherWorker : ourWorkersInRange) {
// if (otherWorker.isGatheringMinerals()) {
// Unit mineralMined = otherWorker.getTarget();
// if (mineralMined != null) {
// //increments the number of workers in this mineral
// int previousNumber = (workersPerMineral.get(mineralMined) == null ? 0 : workersPerMineral.get(mineralMined));
// workersPerMineral.put(mineralMined, previousNumber + 1);
// //minerals.changeValueBy(mineralMined, 1);
// }
// }
// }
for (Unit mineral : minerals) {
for (Unit ourWorker : ourWorkersInRange) {
Unit mineralMinedByWorker = ourWorker.getTarget();
if (ourWorker.isGatheringMinerals() && mineral.equals(mineralMinedByWorker)) {
workersPerMineral.put(mineralMinedByWorker, (workersPerMineral.containsKey(mineral) ?
workersPerMineral.get(mineralMinedByWorker) : 0) + 1);
}
else {
if (!workersPerMineral.containsKey(mineral)) {
workersPerMineral.put(mineral, 0);
}
}
}
}
// Get least gathered mineral
Unit leastGatheredMineral = null;
int minimumWorkersPerMineral = 1000;
for (Entry<Unit, Integer> workersAtMineral : workersPerMineral.entrySet()) {
if (workersAtMineral.getValue() < minimumWorkersPerMineral) {
minimumWorkersPerMineral = workersAtMineral.getValue();
leastGatheredMineral = workersAtMineral.getKey();
break;
}
}
// This is our optimal mineral to gather near given unit
return leastGatheredMineral;
} // If no minerals found, return nearest mineral
else {
return Select.minerals().nearestTo(base.getPosition());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment