Skip to content

Instantly share code, notes, and snippets.

@NeatMonster
Created September 17, 2015 16:32
Show Gist options
  • Save NeatMonster/0e856e6a323566f7e157 to your computer and use it in GitHub Desktop.
Save NeatMonster/0e856e6a323566f7e157 to your computer and use it in GitHub Desktop.
package fr.neatmonster.plugin;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class EntityOwnership implements Listener {
private static final double MAX_DISTANCE = 5;
private final Map<UUID, Location> history = new HashMap<>();
private final Map<UUID, Set<UUID>> relations = new HashMap<>();
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(final PlayerInteractEvent event) {
if (event.hasBlock() && event.hasItem() && event.getItem().getType() == Material.MONSTER_EGG)
history.put(event.getPlayer().getUniqueId(), event.getClickedBlock().getLocation());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCreatureSpawn(final CreatureSpawnEvent event) {
final UUID ownee = event.getEntity().getUniqueId();
if (event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
final Location location = event.getLocation();
UUID owner = null;
double minDistance = Double.MAX_VALUE;
for (final Entry<UUID, Location> entry : history.entrySet()) {
final double distance = location.distance(entry.getValue());
if (distance < minDistance && distance < MAX_DISTANCE) {
owner = entry.getKey();
minDistance = distance;
}
}
if (owner != null) {
if (!relations.containsKey(owner))
relations.put(owner, new HashSet<UUID>());
relations.get(owner).add(ownee);
history.remove(owner);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityTarget(final EntityTargetEvent event) {
final UUID ownee = event.getEntity().getUniqueId();
if (event.getTarget().getType() == EntityType.PLAYER) {
final UUID owner = event.getTarget().getUniqueId();
if (relations.containsKey(owner)) {
final Set<UUID> ownees = relations.get(owner);
if (ownees.contains(ownee))
event.setCancelled(true);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment