-
Notifications
You must be signed in to change notification settings - Fork 0
Vectors and Targeting
On this page, we provide some sample code for finding the closest opponent on the field. In the playAction
method, you are provided with the field, your own team, and the player you're controlling, but the only way to get access to the opponent players is through the field object. For this code, we make no assumptions about what type of match we're playing—it could be duel, free-for-all, or team.
Here's the code:
@Override
public Action playAction(Field field, Team team, Player player) {
Player opponent = findClosestOpponent(field, team, player);
// use getLogger().info to log messages
getLogger().info("Closest opponent: " + opponent.getSymbol());
getLogger().info("Location: " + opponent.getLocation());
return null;
}
private static Player findClosestOpponent(Field field, Team ownTeam, Player self) {
Vector ownLocation = self.getLocation();
Player closestOpponent = null;
double shortestDistance = Double.POSITIVE_INFINITY;
// iterate over all teams
for (Team team : field.getTeams()) {
// skip own team
if (team.equals(ownTeam))
continue;
// iterate over all opponents on other team
for (Player opponent : team.getPlayers()) {
// calculate opponent's location and distance
Vector opponentLocation = opponent.getLocation();
double distance = distance(ownLocation, opponentLocation);
// update closest opponent if this one is closer
if (distance < shortestDistance) {
shortestDistance = distance;
closestOpponent = opponent;
}
}
}
// return the closest opponent
return closestOpponent;
}
private static double distance(Vector loc1, Vector loc2) {
// translation vector from loc1 to loc2
Vector translation = loc2.subtract(loc1);
// magnitude of translation vector is distance
return translation.getMagnitude();
}
Note that this code doesn't actually perform any action; it is meant as a starting point for targeting.
In the findClosestOpponent
method, we iterate over the teams using a for-each loop. Inside that for-each loop, the continue
statement allows us to ignore our own team in the iteration.
Then, within that loop, we iterate over the players of that team. Thus, all of the players on the field that are not on our team will be iterated over.