Big refactoring, small fixes

adopted a MVC class layout, broke up main class, started improving storage of data, fixed almost all ide code errors, updated gson version, renamed some files, fixed naming of config.yml
This commit is contained in:
J0nasL 2023-06-26 04:54:33 -04:00
parent a67b097726
commit 4e7f2e99ba
14 changed files with 826 additions and 591 deletions

3
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}

View file

@ -57,7 +57,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>

View file

@ -0,0 +1,22 @@
package io.github.J0hnL0cke.egghunt.Controller;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Announcement {
public static void announce(String message, Logger logger) {
List<Player> players = new ArrayList<>(Bukkit.getOnlinePlayers());
for (Player player: players)
if (player.hasPermission("egghunt.notify")) {
((CommandSender) player).sendMessage(message);
}
logger.info(String.format("Told %d players %s", players.size(), message));
}
}

View file

@ -0,0 +1,199 @@
package io.github.J0hnL0cke.egghunt.Controller;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.CompassMeta;
import io.github.J0hnL0cke.egghunt.Model.Data;
public class CommandHandler {
private static final String NOT_PERMITTED_MSG = "Insufficient permission";
private Data data;
public CommandHandler(Data data) {
this.data = data;
}
private boolean locateEgg(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.hasPermission("egghunt.locateegg")) {
String eggContainer = "";
switch (data.stored_as) {
case BLOCK:
eggContainer = "has been placed";
break;
case CONTAINER_INV:
eggContainer = "is in a "
.concat(data.loc.getBlock().getType().toString().toLowerCase());
break;
case ENTITY_INV:
eggContainer = "is in the inventory of ".concat(data.stored_entity.getName());
break;
case ITEM:
eggContainer = "is an item";
break;
default:
eggContainer = "does not exist";
break;
}
String egg_loc_str = ""; // make this empty so if egg does not exist, it remains blank
if (data.stored_as != Data.Egg_Storage_Type.DNE) {
Location egg_loc = data.getEggLocation();
// May occasionally produce a NullPointerException, assert that it wont
assert egg_loc != null;
int egg_x = egg_loc.getBlockX();
int egg_y = egg_loc.getBlockY();
int egg_z = egg_loc.getBlockZ();
String egg_world = egg_loc.getWorld().getName();
egg_loc_str = String.format(" at %d, %d, %d in %s", egg_x, egg_y, egg_z, egg_world);
}
sender.sendMessage("The dragon egg ".concat(eggContainer).concat(egg_loc_str).concat("."));
} else {
sender.sendMessage(NOT_PERMITTED_MSG);
}
return true;
}
private boolean trackEgg(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player, use /locateegg instead.");
} else {
if (sender.hasPermission("egghunt.trackegg")) {
Player player = (Player) sender;
// roundabout way of getting the item the player is holding in their hotbar
ItemStack held_item = player.getInventory().getItemInMainHand();
if (held_item.getType().equals(Material.COMPASS)) {
if (data.stored_as != Data.Egg_Storage_Type.DNE) {
Location egg_loc = data.getEggLocation();
if (player.getWorld().equals(egg_loc.getWorld())) {
CompassMeta meta = (CompassMeta) held_item.getItemMeta();
meta.setLodestoneTracked(false);
meta.setLodestone(egg_loc);
held_item.setItemMeta(meta);
sender.sendMessage("Compass set to track last known dragon egg position.");
} else {
sender.sendMessage("Not in the same dimension as the egg.");
sender.sendMessage(String.format("The egg is in %s.", egg_loc.getWorld().getName()));
}
} else {
sender.sendMessage("The dragon egg does not exist.");
}
} else {
sender.sendMessage(
"You must be holding a compass to use this command, use /locateegg instead.");
}
} else {
sender.sendMessage(NOT_PERMITTED_MSG);
}
}
return true;
}
private boolean getOwner(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.hasPermission("egghunt.eggowner")) {
if (data.owner == null) {
sender.sendMessage("The dragon egg is currently unclaimed");
} else {
sender.sendMessage(String.format("The dragon egg belongs to %s.",
get_username_from_uuid(data.owner)));
sender.sendMessage("Don't steal it!");
}
} else {
sender.sendMessage(NOT_PERMITTED_MSG);
}
return true;
}
private boolean toggleNotifications(CommandSender sender, Command cmd, String label, String[] args) {
// TODO: add notification toggle
// requires a permission plugin api or some code run at onEnable, onJoin, and
// onDisconnect to implement
return false;
/* if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
} else {
if (args.length == 0) {
String isNotifying = "OFF";
if (sender.hasPermission("egghunt.notify")) {
isNotifying = "ON";
}
sender.sendMessage(
String.format("Dragon egg notifications for %s are set to %s", sender.getName(), isNotifying));
} else if (sender.hasPermission("egghunt.togglenotify")) {
boolean currentPerm = sender.hasPermission("egghunt.notify");
boolean newPerm = true;// only need to initialize to prevent warning
boolean isValid = true;
String name = "";
String state = args[0].toLowerCase();
if (state.equals("on")) {
newPerm = true;
name = "ON";
} else if (state.equals("off")) {
newPerm = false;
name = "OFF";
} else {
sender.sendMessage(String.format("Unknown argument %s", state));
isValid = false;
}
if (isValid) {
if (currentPerm == newPerm) {
sender.sendMessage(String.format("Dragon egg notifications are already set to %s", name));
} else {
PermissionAttachment attachment = sender.addAttachment(this);
attachment.setPermission("egghunt.notify", newPerm);
attachment.remove();
sender.sendMessage(String.format("Dragon egg notifications have been set to %s", name));
}
}
} else {
sender.sendMessage(NOT_PERMITTED_MSG);
}
}
return true; */
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("locateegg")) {
return locateEgg(sender, cmd, label, args);
} else if (cmd.getName().equalsIgnoreCase("trackegg")) {
return trackEgg(sender, cmd, label, args);
} else if (cmd.getName().equalsIgnoreCase("eggowner")) {
return getOwner(sender, cmd, label, args);
} else if (cmd.getName().equalsIgnoreCase("eggnotify")) {
toggleNotifications(sender, cmd, label, args);
}
// if no command is found
return false;
}
public static String get_username_from_uuid(UUID id) {
return Bukkit.getOfflinePlayer(id).getName();
}
}

View file

@ -1,4 +1,4 @@
package io.github.J0hnL0cke.egghunt;
package io.github.J0hnL0cke.egghunt.Controller;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
@ -9,7 +9,6 @@ import org.bukkit.TreeType;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -21,15 +20,17 @@ import org.bukkit.event.inventory.*;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import io.github.J0hnL0cke.egghunt.Model.Configuration;
import io.github.J0hnL0cke.egghunt.Model.Data;
import io.github.J0hnL0cke.egghunt.Model.Data.Egg_Storage_Type;
import java.util.List;
import java.util.UUID;
@ -42,33 +43,25 @@ public class EggHuntListener implements Listener {
Stored entity is separate from the owner because the egg can be stored in any entity
(ex: held by a zombie or item frame), but only players can "own" the egg*/
static public Location loc;
static public Entity stored_entity;
static public Egg_Storage_Type stored_as=Egg_Storage_Type.DNE;
public enum Egg_Storage_Type {
ITEM,
BLOCK,
ENTITY_INV,
CONTAINER_INV,
DNE, //egg does not exist
}
static public UUID owner;
static public Logger logger;
static public FileSave config;
static public boolean egg_inv;
static public boolean resp_egg;
static public boolean resp_imm;
static public boolean reset_owner_after_tp;
static public boolean accurate_loc;
static public boolean drop_enderchested_egg;
static public World end;
private Logger logger;
private Configuration config;
private Data data;
public EggHuntListener(Logger logger, FileSave conf) {
EggHuntListener.logger = logger;
config=conf;
public EggHuntListener(Logger logger, Configuration config, Data data) {
this.logger = logger;
this.config = config;
this.data = data;
}
private static String get_username_from_uuid(UUID id) {
return Bukkit.getOfflinePlayer(id).getName();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onAutosave(WorldSaveEvent event) {
//TODO: save data when autosave happens
}
// Handle egg removal and drop upon player logoff
//TODO: check if item spawn and item drop are overlapping, and check which can be replaced
@ -86,7 +79,7 @@ public class EggHuntListener implements Listener {
// Drop it on the floor and set its location
Item egg_drop = event.getPlayer().getWorld().dropItem(player.getLocation(), new ItemStack(Material.DRAGON_EGG));
setEggLocation(egg_drop, Egg_Storage_Type.ITEM);
setEggLocation(egg_drop, Data.Egg_Storage_Type.ITEM);
}
}
@ -196,7 +189,7 @@ public class EggHuntListener implements Listener {
setEggLocation((Entity) others.getHolder(), Egg_Storage_Type.ENTITY_INV);
} else if (others.getType().equals(InventoryType.ENDER_CHEST)) {
//force any eggs in the ender chest to be dropped
if (drop_enderchested_egg && player.getGameMode()!=GameMode.CREATIVE) {
if (config.getDropEnderchestedEgg() && player.getGameMode()!=GameMode.CREATIVE) {
ItemStack egg=others.getItem(others.first(Material.DRAGON_EGG));
egg.setAmount(1);
Location player_loc=player.getLocation();
@ -204,7 +197,7 @@ public class EggHuntListener implements Listener {
Item i=player_loc.getWorld().dropItemNaturally(player_loc, egg);
console_log(String.format("%s has the dragon egg in their ender chest, dropping it on the ground...", player.getName()));
console_log("Set ignore_echest_egg to \"true\" in the config file to disable this feature.");
setEggLocation(i, stored_as);
setEggLocation(i, data.stored_as);
}
} else {
setEggLocation(others.getLocation(), Egg_Storage_Type.CONTAINER_INV);
@ -259,16 +252,16 @@ public class EggHuntListener implements Listener {
public void onSpread(BlockFromToEvent event) {
if (event.getBlock().getType().equals(Material.DRAGON_EGG)) {
Block block;
if (accurate_loc) {
if (config.getAccurateLocation()) {
block=event.getToBlock();
console_log("The egg teleported, location is set to show location after teleport");
} else {
block=event.getBlock();
console_log("The egg teleported, location is set to show location before teleport");
}
if (reset_owner_after_tp) {
if (owner!=null) {
announce(String.format("The dragon egg has teleported. %s is no longer the owner.", egghunt.get_username_from_uuid(owner)));
if (config.resetOwnerOnTeleport()) {
if (data.owner!=null) {
announce(String.format("The dragon egg has teleported. %s is no longer the owner.", get_username_from_uuid(data.owner)));
resetEggOwner(false);
}
}
@ -324,11 +317,11 @@ public class EggHuntListener implements Listener {
}
}
//if the dragon is killed, respawn the egg
if (resp_egg) {
if (stored_as.equals(Egg_Storage_Type.DNE)) {
if (config.getRespawnEgg()) {
if (data.stored_as.equals(Egg_Storage_Type.DNE)) {
if (event.getEntityType().equals(EntityType.ENDER_DRAGON)) {
//dragon is killed
if (end.getEnderDragonBattle().hasBeenPreviouslyKilled()) {
if (config.getEndWorld().getEnderDragonBattle().hasBeenPreviouslyKilled()) {
spawnEggBlock();
}
}
@ -336,19 +329,18 @@ public class EggHuntListener implements Listener {
}
}
//old block= blockState.getBlock().getType()
//new block= blockState.getType()
//stop portals from removing the egg
@EventHandler(priority = EventPriority.MONITOR)
public void onCreatePortal(EntityCreatePortalEvent event) {
//not specific to any particular creation reason because multiple events could cause the egg to be removed (obby platform regen, gateway portal spawning, stronghold portal activation)
boolean egg_affected=false;
//not specific to any particular creation reason because multiple events could cause the egg to be removed (obby platform regen, gateway portal spawning, stronghold portal activation)
boolean egg_affected=false;
Location l = null;
List<BlockState> blocks=event.getBlocks();
console_log(String.format("blocks: %s",blocks.toString()));
for (BlockState blockState: blocks) {
console_log(String.format("Block update at %s: from %s to %s",config.serializeLocation(blockState.getLocation()),blockState.getBlock().getType(),blockState.getType()));
console_log(String.format("Block update at %s: from %s to %s", data.serializeLocation(blockState.getLocation()),blockState.getBlock().getType(),blockState.getType()));
if (blockState.getBlock().getType().equals(Material.DRAGON_EGG)) {
egg_affected=true;
l=blockState.getLocation();
@ -437,29 +429,34 @@ public class EggHuntListener implements Listener {
//TODO: 1.17: also exclude bundles
// stop players from echesting the egg or storing it in a shulker box
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryMoveConsider (InventoryClickEvent event) {
InventoryType inv=event.getInventory().getType();
if (event.getWhoClicked().getGameMode()!= GameMode.CREATIVE && (inv.equals(InventoryType.ENDER_CHEST) || inv.equals(InventoryType.SHULKER_BOX))) {
//check if the item clicked was the egg
if (event.getCurrentItem()!=null) {
if (event.getCurrentItem().getType().equals(Material.DRAGON_EGG)) {
event.setCancelled(true);
console_log(String.format("Stopped %s from moving egg to ender chest",event.getWhoClicked().getName()));
}
}
//Don't allow hotkeying either
if (event.getClick().equals(ClickType.NUMBER_KEY)) {
ItemStack item=event.getWhoClicked().getInventory().getItem(event.getHotbarButton());
if (item!=null) {
if (item.getType().equals(Material.DRAGON_EGG)) {
event.setCancelled(true);
console_log(String.format("Stopped %s from hotkeying egg to ender chest",event.getWhoClicked().getName()));
}
}
}
public void onInventoryMoveConsider(InventoryClickEvent event) {
InventoryType inv = event.getInventory().getType();
if (event.getWhoClicked().getGameMode() != GameMode.CREATIVE) {
if (inv.equals(InventoryType.ENDER_CHEST) || inv.equals(InventoryType.SHULKER_BOX)) {
//check if the item clicked was the egg
if (event.getCurrentItem() != null) {
if (event.getCurrentItem().getType().equals(Material.DRAGON_EGG)) {
event.setCancelled(true);
console_log(String.format("Stopped %s from moving egg to ender chest",
event.getWhoClicked().getName()));
}
}
//Don't allow hotkeying either
if (event.getClick().equals(ClickType.NUMBER_KEY)) {
ItemStack item = event.getWhoClicked().getInventory().getItem(event.getHotbarButton());
if (item != null) {
if (item.getType().equals(Material.DRAGON_EGG)) {
event.setCancelled(true);
console_log(String.format("Stopped %s from hotkeying egg to ender chest",
event.getWhoClicked().getName()));
}
}
}
}
}
}
//stop players from pushing the egg into a shulker using a hopper/hopper minecart
@EventHandler(priority = EventPriority.HIGHEST)
public void onPushConsider (InventoryMoveItemEvent event) {
//nice try, but it won't work
@ -474,7 +471,7 @@ public class EggHuntListener implements Listener {
//TODO: figure out if this is still needed
@EventHandler(priority = EventPriority.HIGHEST)
public void onConsiderEntityDamageEvent(EntityDamageEvent event) {
if (egg_inv) {
if (config.getEggInvincible()) {
Entity entity=event.getEntity();
if (entity.getType().equals(EntityType.DROPPED_ITEM)) {
ItemStack item = ((Item)entity).getItemStack();
@ -488,11 +485,11 @@ public class EggHuntListener implements Listener {
//Helper methods
//When a portal is updated, check if the egg will be replaced
public static void checkPortalBlocks(){
private void checkPortalBlocks(){
//Check end platform
Location l1=new Location(end,102,48,2);
Location l2=new Location(end,98,51,-2);
Location res=checkBlockMaterialFromLocation(end,Material.DRAGON_EGG,l1,l2);
Location l1=new Location(config.getEndWorld(),102,48,2);
Location l2=new Location(config.getEndWorld(),98,51,-2);
Location res=checkBlockMaterialFromLocation(config.getEndWorld(),Material.DRAGON_EGG,l1,l2);
if (res!=null) {
portalOverwriteEgg(res);
}
@ -500,11 +497,11 @@ public class EggHuntListener implements Listener {
}
public static void portalOverwriteEgg(Location res) {
private void portalOverwriteEgg(Location res) {
res.getBlock().setType(Material.AIR);
console_log("Prevented egg overwrite with a portal");
resetEggOwner(true);
if (egg_inv) {
if (config.getEggInvincible()) {
spawnEggItem(res);
} else {
eggDestroyed();
@ -512,7 +509,7 @@ public class EggHuntListener implements Listener {
}
//Checks various blocks for the given material
public static Location checkBlockMaterial(World w, Material m, int x1, int x2, int y1, int y2, int z1, int z2) {
private static Location checkBlockMaterial(World w, Material m, int x1, int x2, int y1, int y2, int z1, int z2) {
for (int x=x1; x<x2; x++) {
for (int y=y1; y<y2; y++) {
for (int z=z1; z<z2; z++) {
@ -525,76 +522,81 @@ public class EggHuntListener implements Listener {
return null;
}
public static Location checkBlockMaterialFromLocation(World w, Material m, Location l1, Location l2) {
private static Location checkBlockMaterialFromLocation(World w, Material m, Location l1, Location l2) {
return checkBlockMaterial(w,m,l1.getBlockX(),l1.getBlockY(),l1.getBlockZ(),l2.getBlockX(),l2.getBlockY(),l2.getBlockZ());
}
//Calls CheckBlockMaterial with deltas
public static Location checkDeltaBlockMaterial(World w, Material m, int x, int dx, int y, int dy, int z, int dz) {
private static Location checkDeltaBlockMaterial(World w, Material m, int x, int dx, int y, int dy, int z, int dz) {
return (checkBlockMaterial(w, m, x, x+dx, y, y+dy, z, z+dz));
}
public static void resetEggOwner(boolean announce) {
private void resetEggOwner(boolean announce) {
if (announce) {
if (owner!=null) {
announce(String.format("%s no longer owns the dragon egg", egghunt.get_username_from_uuid(owner)));
if (data.owner!=null) {
announce(String.format("%s no longer owns the dragon egg", get_username_from_uuid(data.owner)));
}
}
console_log("Reset egg owner");
owner=null;
config.saveData();
data.owner=null;
data.saveData();
}
public static void setEggOwner(Player player) {
private void setEggOwner(Player player) {
console_log(player.getName().concat(" has the egg."));
String formatStr;
//check if ownership switched
//need redundant code so owner getting the egg again doesn't unnecessairly update the db
if (owner!=null && !player.getUniqueId().equals(owner)) {
announce(String.format("%s has stolen the dragon egg!", player.getName()));
owner=player.getUniqueId();
config.saveData();
} else if (owner==null){
announce(String.format("%s has claimed the dragon egg!", player.getName()));
owner=player.getUniqueId();
config.saveData();
//make sure owner has actually changed so getting the egg again doesn't unnecessairly update the db
if (data.owner != null && !player.getUniqueId().equals(data.owner)) {
formatStr = "%s has stolen the dragon egg!";
} else if (data.owner == null) {
formatStr = "%s has claimed the dragon egg!";
} else {
return;
}
//update owner and announce to players
data.owner=player.getUniqueId();
data.saveData();
announce(String.format(formatStr, player.getName()));
}
public static void setEggLocation(Location egg_loc, Egg_Storage_Type store_type) {
loc=egg_loc;
stored_entity=null;
stored_as=store_type;
private void setEggLocation(Location egg_loc, Egg_Storage_Type store_type) {
data.loc=egg_loc;
data.stored_entity=null;
data.stored_as=store_type;
console_log(String.format("The egg has moved to block %s as %s", egg_loc, store_type.toString()));
config.saveData();
data.saveData();
}
public static void setEggLocation(Entity entity, Egg_Storage_Type store_type) {
loc=null;
stored_entity=entity;
stored_as=store_type;
private void setEggLocation(Entity entity, Egg_Storage_Type store_type) {
data.loc=null;
data.stored_entity=entity;
data.stored_as=store_type;
console_log(String.format("The egg has moved to entity %s (%s) as %s", entity, entity.getLocation(), store_type.toString()));
config.saveData();
data.saveData();
}
public static void setEggInv(Entity egg_stack) {
if (egg_inv) {
private void setEggInv(Entity egg_stack) {
if (config.getEggInvincible()) {
egg_stack.setInvulnerable(true);
console_log("made drop invulnerable");
}
}
public static void eggDestroyed() {
private void eggDestroyed() {
announce("The dragon egg has been destroyed!");
resetEggOwner(false);
owner=null;
stored_as=Egg_Storage_Type.DNE;
loc=null;
stored_entity=null;
config.saveData();
if (resp_egg) {
if (resp_imm) {
data.owner=null;
data.stored_as=Egg_Storage_Type.DNE;
data.loc=null;
data.stored_entity=null;
data.saveData();
if (config.getRespawnEgg()) {
if (config.getRespawnImmediately()) {
spawnEggBlock();
} else {
announce("It will respawn the next time the dragon is defeated");
@ -602,41 +604,35 @@ public class EggHuntListener implements Listener {
}
}
public static void spawnEggBlock() {
Location new_egg_loc=end.getEnderDragonBattle().getEndPortalLocation().add(0, 4, 0);
private void spawnEggBlock() {
Location new_egg_loc=config.getEndWorld().getEnderDragonBattle().getEndPortalLocation().add(0, 4, 0);
new_egg_loc.getBlock().setType(Material.DRAGON_EGG);
setEggLocation(new_egg_loc,Egg_Storage_Type.BLOCK);
announce("The dragon egg has spawned in the end!");
}
public static void spawnEggItem(Location loc){
public void spawnEggItem(Location loc){
ItemStack egg=new ItemStack(Material.DRAGON_EGG);
egg.setAmount(1);
Item drop=loc.getWorld().dropItem(loc, egg);
drop.setGravity(false);
drop.setGlowing(true);
drop.setVelocity(new Vector().setX(0).setY(0).setZ(0));
if (egg_inv) {
if (config.getEggInvincible()) {
drop.setInvulnerable(true);
}
setEggLocation(drop, Egg_Storage_Type.ITEM);
}
public static void announce(String message) {
List<Player> players = new ArrayList<>(Bukkit.getOnlinePlayers());
for (Player player: players)
if (player.hasPermission("egghunt.notify")) {
((CommandSender) player).sendMessage(message);
}
console_log(String.format("Told %d players %s", players.size(), message));
private void announce(String msg) {
Announcement.announce(msg, logger);
}
public static void console_log(String message) {
private void console_log(String message) {
logger.info(message);
}
}

View file

@ -0,0 +1,122 @@
package io.github.J0hnL0cke.egghunt.Controller;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import io.github.J0hnL0cke.egghunt.Model.Configuration;
import io.github.J0hnL0cke.egghunt.Model.Data;
public class EventScheduler extends BukkitRunnable {
public final int UNDER_WORLD_HEIGHT = -40; // TODO this is wrong as of caves and cliffs
public final int VOID_RESPAWN_OFFSET = 2; // how much higher than the highest block to respawn the egg when it falls into the void
private Data data;
private Configuration config;
public EventScheduler(Configuration config, Data data) {
this.data = data;
this.config = config;
}
@Override
public void run() {
// check if the entity storing the egg has fallen out of the world
if (data.stored_as.equals(Data.Egg_Storage_Type.ENTITY_INV)) {
Entity entity = data.stored_entity;
if (entity != null) {
// TODO: check if this check is needed
if (hasEgg(entity)) {
if (isUnderWorld(entity)) {
removeEgg(entity);
}
}
}
} else if (data.stored_as.equals(Data.Egg_Storage_Type.ITEM)) {
Entity item = data.stored_entity;
if (item != null) {
if (isUnderWorld(item)) {
removeEgg(item);
}
}
}
}
public boolean hasEgg(Entity entity) {
if (entity instanceof Player) {
return ((Player) entity).getInventory().contains(Material.DRAGON_EGG);
} else if (entity instanceof LivingEntity) {
LivingEntity mob = (((LivingEntity) entity));
EntityEquipment inv = mob.getEquipment();
if (inv.getItemInMainHand().getType().equals(Material.DRAGON_EGG)) {
return true;
}
if (inv.getItemInOffHand().getType().equals(Material.DRAGON_EGG)) {
return true;
}
} else if (entity instanceof FallingBlock) {
return ((FallingBlock) entity).getBlockData().getMaterial().equals(Material.DRAGON_EGG);
} else if (entity instanceof Item) {
return ((Item) entity).getItemStack().getType().equals(Material.DRAGON_EGG);
}
return false;
}
public boolean isUnderWorld(Entity entity) {
return entity.getLocation().getY() < UNDER_WORLD_HEIGHT;
}
public void removeEgg(Entity container) {
Location l = container.getLocation();
removeMaterialFromEntity(Material.DRAGON_EGG, container);
if (config.getEggInvincible()) {
// get coords for egg to spawn at
// TODO: handle negative y coords in 1.17
Block block_pos = l.getWorld().getHighestBlockAt(l);
int y_pos = block_pos.getY();
if (block_pos.isEmpty()) {
y_pos = l.getWorld().getMaxHeight()/2; //respawn around sea level (world height / 2) if no blocks underneath
}
l.setY(y_pos);
EggHuntListener.spawnEggItem(l);
} else {
EggHuntListener.eggDestroyed();
}
EggHuntListener.resetEggOwner(true);
}
public void removeMaterialFromEntity(Material m, Entity entity) {
data.stored_as = Data.Egg_Storage_Type.DNE;
if (entity instanceof Player) {
Player player = (Player) entity;
player.getInventory().remove(m);
} else if (entity instanceof LivingEntity) {
EntityEquipment equipment = ((LivingEntity) entity).getEquipment();
if (equipment != null) {
// TODO: consider all armor slots, not just hands
if (equipment.getItemInMainHand().getType().equals(m)) {
equipment.setItemInMainHand(null);
}
if (equipment.getItemInOffHand().getType().equals(m)) {
equipment.setItemInOffHand(null);
}
}
} else if (entity instanceof Item) {
((Item) entity).remove();
} else if (entity instanceof FallingBlock) {
((FallingBlock) entity).remove();
}
}
}

View file

@ -1,114 +0,0 @@
package io.github.J0hnL0cke.egghunt;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import io.github.J0hnL0cke.egghunt.EggHuntListener.Egg_Storage_Type;;
public class EventScheduler extends BukkitRunnable {
private final JavaPlugin plugin;
public final int underWorld=-40;
public EventScheduler(JavaPlugin plugin) {
this.plugin = plugin;
}
@Override
public void run() {
//check if the entity storing the egg has fallen out of the world
if (EggHuntListener.stored_as.equals(Egg_Storage_Type.ENTITY_INV)) {
Entity entity=EggHuntListener.stored_entity;
if (entity!=null) {
//TODO: check if this check is needed
if (hasEgg(entity)) {
if (isUnderWorld(entity)) {
removeEgg(entity);
}
}
}
} else if (EggHuntListener.stored_as.equals(Egg_Storage_Type.ITEM)) {
Entity item=EggHuntListener.stored_entity;
if (item!=null) {
if (isUnderWorld(item)) {
removeEgg(item);
}
}
}
}
public boolean hasEgg(Entity entity) {
if (entity instanceof Player) {
return ((Player)entity).getInventory().contains(Material.DRAGON_EGG);
} else if (entity instanceof LivingEntity) {
LivingEntity mob=(((LivingEntity)entity));
EntityEquipment inv= mob.getEquipment();
if (inv.getItemInMainHand().getType().equals(Material.DRAGON_EGG)) {
return true;
}
if (inv.getItemInOffHand().getType().equals(Material.DRAGON_EGG)) {
return true;
}
} else if (entity instanceof FallingBlock) {
return ((FallingBlock)entity).getBlockData().getMaterial().equals(Material.DRAGON_EGG);
} else if (entity instanceof Item) {
return ((Item)entity).getItemStack().getType().equals(Material.DRAGON_EGG);
}
return false;
}
public boolean isUnderWorld(Entity entity) {
return entity.getLocation().getY()<underWorld;
}
public void removeEgg(Entity container) {
Location l=container.getLocation();
removeFromInventory(Material.DRAGON_EGG,container);
if (EggHuntListener.egg_inv) {
//get coords for egg to spawn at
//TODO: handle negative y coords in 1.17
int y_pos=Math.max(0, l.getWorld().getHighestBlockAt(l).getY()+2);
if (y_pos<2) {
y_pos=60;
}
l.setY(y_pos);
EggHuntListener.spawnEggItem(l);
} else {
EggHuntListener.eggDestroyed();
}
EggHuntListener.resetEggOwner(true);
}
public void removeFromInventory(Material m, Entity entity) {
EggHuntListener.stored_as=Egg_Storage_Type.DNE;
if (entity instanceof Player) {
Player player= (Player)entity;
player.getInventory().remove(m);
} else if (entity instanceof LivingEntity){
EntityEquipment equipment=((LivingEntity)entity).getEquipment();
if (equipment!=null) {
//TODO: consider all armor slots, not just hands
if(equipment.getItemInMainHand().getType().equals(m)) {
equipment.setItemInMainHand(null);
}
if(equipment.getItemInOffHand().getType().equals(m)) {
equipment.setItemInOffHand(null);
}
}
} else if (entity instanceof Item) {
((Item)entity).remove();
} else if (entity instanceof FallingBlock) {
((FallingBlock)entity).remove();
}
}
}

View file

@ -1,167 +0,0 @@
package io.github.J0hnL0cke.egghunt;
import java.time.LocalDateTime;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import io.github.J0hnL0cke.egghunt.EggHuntListener.Egg_Storage_Type;
public class FileSave {
JavaPlugin plugin;
public FileSave(JavaPlugin plugin) {
this.plugin = plugin;
}
//Saves data in key-value pairs
public void writeAll(String key, String value) {
writeKey(key,value);
}
public void writeKey(String key, String value) {
plugin.getConfig().set(key,value);
plugin.saveConfig();
}
public String getKey(String key, String not_found) {
return plugin.getConfig().getString(key,not_found);
}
public boolean keyExists(String key) {
return plugin.getConfig().contains(key);
}
public void loadData() {
//load config settings
EggHuntListener.egg_inv=getBoolFromConfig("egg_inv");
EggHuntListener.resp_egg=getBoolFromConfig("resp_egg");
EggHuntListener.resp_imm=getBoolFromConfig("resp_imm");
EggHuntListener.reset_owner_after_tp=getBoolFromConfig("reset_owner");
EggHuntListener.accurate_loc=getBoolFromConfig("accurate_loc");
EggHuntListener.drop_enderchested_egg=getBoolFromConfig("drop_enderchested_egg");
EggHuntListener.end=Bukkit.getServer().getWorld(plugin.getConfig().getString("end","world_end"));
//load egg location
//load stored_as
EggHuntListener.stored_as=Egg_Storage_Type.valueOf(this.getKey("stored_as", Egg_Storage_Type.DNE.name()));
//load owner
String owner=this.getKey("owner", null);
if (owner!=null) {
EggHuntListener.owner=UUID.fromString(owner);
} else {
EggHuntListener.owner=null;
}
//load loc
String loc_str=this.getKey("loc", null);
boolean needs_loc_str=EggHuntListener.stored_as==Egg_Storage_Type.BLOCK || EggHuntListener.stored_as==Egg_Storage_Type.CONTAINER_INV;
if (loc_str!=null) {
String[] loc=loc_str.split(":");
if (loc.length==4) {
World w = Bukkit.getServer().getWorld(loc[0]);
double x = Double.parseDouble(loc[1]);
double y = Double.parseDouble(loc[2]);
double z = Double.parseDouble(loc[3]);
EggHuntListener.loc=new Location(w,x,y,z);
} else {
plugin.getLogger().warning("Invalid block location string");
}
} else {
if (needs_loc_str) {
plugin.getLogger().warning("Location string was null when it should have a value");
}
EggHuntListener.loc=null;
}
//load stored_entity
String stored_entity=this.getKey("stored_entity", null);
boolean needs_stored_entity=EggHuntListener.stored_as==Egg_Storage_Type.ENTITY_INV || EggHuntListener.stored_as==Egg_Storage_Type.ITEM;
if (stored_entity!=null) {
UUID id=UUID.fromString(stored_entity);
EggHuntListener.stored_entity=Bukkit.getEntity(id);
//if the entity is not found
if (EggHuntListener.stored_entity==null && needs_stored_entity) {
plugin.getLogger().warning("Could not locate entity from saved UUID");
}
} else {
EggHuntListener.stored_entity=null;
if (needs_stored_entity) {
plugin.getLogger().warning("Stored entity was null when it should have a value");
}
}
}
public void saveData() {
//save loc
if (EggHuntListener.loc!=null) {
Location loc=EggHuntListener.loc;
writeKey("loc", serializeLocation(loc));
} else {
writeKey("loc", null);
}
//save stored_entity
if (EggHuntListener.stored_entity!=null) {
writeKey("stored_entity", EggHuntListener.stored_entity.getUniqueId().toString());
} else {
writeKey("stored_entity", null);
}
//save block/entity name to DB
String name;
switch (EggHuntListener.stored_as) {
case BLOCK: name="block";
break;
case CONTAINER_INV: name=egghunt.getEggLocation().getBlock().getType().toString();
break;
case DNE: name=null;
break;
case ENTITY_INV:
String entityName=EggHuntListener.stored_entity.getName();
String entityType=EggHuntListener.stored_entity.getType().toString();
name=String.format("%s:%s",entityType,entityName);
break;
case ITEM: name="item";
break;
default: throw new java.lang.Error("Unknown egg storage type");
}
//save stored_as
if (EggHuntListener.stored_as!=null) {
writeAll("stored_as", EggHuntListener.stored_as.name());
} else {
writeAll("stored_as",Egg_Storage_Type.DNE.name());
}
//save owner
if (EggHuntListener.owner!=null) {
writeAll("owner", EggHuntListener.owner.toString());
} else {
writeAll("owner", null);
}
//save timestamp
writeAll("timestamp", LocalDateTime.now().toString());
}
public String serializeLocation(Location loc) {
return loc.getWorld().getName() + ":" + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ();
}
public boolean getBoolFromConfig(String key) {
return Boolean.parseBoolean(plugin.getConfig().getString(key,"false"));
}
}

View file

@ -0,0 +1,71 @@
package io.github.J0hnL0cke.egghunt.Model;
import org.bukkit.Bukkit;
import org.bukkit.World;
import io.github.J0hnL0cke.egghunt.Persistence.ConfigDAO;
/**
* Retrieve settings for this plugin
*/
public class Configuration {
boolean eggInvincible; /** whether to make the egg immune to damage */
boolean respawnEgg; /** whether the egg should respawn when destroyed */
boolean respawnImmediately; /** if respawning the egg, whether it should immediately respawn in-place or whether it should generate after next dragon fight */
boolean resetOwnerOnTeleport; /** whether the egg should become "lost" when it is teleported */
boolean accurateLocation;
boolean dropEnderchestedEgg; /** whether an existing egg already in an ender chest should be forced out or stuck there */
World endWorld; /** the name of the world that counts as the end on this server */
public static String defaultEnd = "world_end"; /** default end world name for most spigot servers */
ConfigDAO fileDao;
public Configuration(ConfigDAO fileDao) {
this.fileDao = fileDao;
loadData();
}
private void loadData() {
//load config settings
eggInvincible = fileDao.readBool("egg_inv");
respawnEgg = fileDao.readBool("resp_egg");
respawnImmediately = fileDao.readBool("resp_imm");
resetOwnerOnTeleport = fileDao.readBool("reset_owner");
accurateLocation = fileDao.readBool("accurate_loc");
dropEnderchestedEgg = fileDao.readBool("drop_enderchested_egg");
endWorld = Bukkit.getServer().getWorld(fileDao.read("end", defaultEnd));
}
public boolean getEggInvincible() {
return eggInvincible;
}
public boolean getRespawnEgg() {
return respawnEgg;
}
public boolean getRespawnImmediately() {
return respawnImmediately;
}
public boolean resetOwnerOnTeleport() {
return resetOwnerOnTeleport;
}
public boolean getAccurateLocation() {
return accurateLocation;
}
public boolean getDropEnderchestedEgg() {
return dropEnderchestedEgg;
}
public World getEndWorld() {
return endWorld;
}
}

View file

@ -0,0 +1,159 @@
package io.github.J0hnL0cke.egghunt.Model;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import io.github.J0hnL0cke.egghunt.Persistence.DataDAO;
/**
* Retrieve and store this plugin's data
*/
public class Data {
private DataDAO dataDao;
private Logger logger;
public enum Egg_Storage_Type {
ITEM,
BLOCK,
ENTITY_INV,
CONTAINER_INV,
DNE, //egg does not exist
}
public Location loc;
public Entity stored_entity;
public UUID owner;
public Egg_Storage_Type stored_as;
public Data(DataDAO dataDAO, Logger logger) {
dataDAO = this.dataDao;
loadData();
//TODO figure out a better schema for getting/setting egg data than making everything public
}
public Location getEggLocation() {
if (stored_as != Egg_Storage_Type.DNE) {
boolean is_entity;
switch (stored_as) {
case BLOCK:
case CONTAINER_INV:
is_entity=false;
break;
case ENTITY_INV:
case ITEM:
is_entity=true;
break;
default:
throw new java.lang.Error("Unknown egg storage type when calling getEggLocation()"); //fail loudly instead of silently, you're welcome
}
return is_entity ? stored_entity.getLocation() : loc;
}
return null;
}
public void loadData() {
//load egg location
//load stored_as
stored_as=dataDao.read("stored_as", Egg_Storage_Type.class, Egg_Storage_Type.DNE);
//load owner
owner=dataDao.read("owner", UUID.class, null);
//load loc
//TODO major refactor to this
String loc_str=dataDao.read("loc", String.class, null);
boolean needs_loc_str = stored_as == Egg_Storage_Type.BLOCK
|| stored_as == Egg_Storage_Type.CONTAINER_INV;
if (loc_str!=null) {
String[] loc_arr=loc_str.split(":");
if (loc_arr.length==4) {
World w = Bukkit.getServer().getWorld(loc_arr[0]);
double x = Double.parseDouble(loc_arr[1]);
double y = Double.parseDouble(loc_arr[2]);
double z = Double.parseDouble(loc_arr[3]);
loc=new Location(w,x,y,z);
} else {
logger.warning("Invalid block location string");
}
} else {
if (needs_loc_str) {
logger.warning("Location string was null when it should have a value");
}
loc=null;
}
//load stored_entity
String stored_entity=dataDao.read("stored_entity", String.class, null);
boolean needs_stored_entity=stored_as==Egg_Storage_Type.ENTITY_INV || stored_as==Egg_Storage_Type.ITEM;
if (stored_entity!=null) {
UUID id=UUID.fromString(stored_entity);
this.stored_entity=Bukkit.getEntity(id);
//if the entity is not found
if (this.stored_entity==null && needs_stored_entity) {
logger.warning("Could not locate entity from saved UUID");
}
} else {
stored_entity=null;
if (needs_stored_entity) {
logger.warning("Stored entity was null when it should have a value");
}
}
}
public void saveData() {
//save loc
dataDao.write("loc", loc);
//save stored_entity
dataDao.write("stored_entity", stored_entity);
//save block/entity name to DB
String name;
switch (stored_as) {
case BLOCK: name="block";
break;
case CONTAINER_INV: name=loc.getBlock().getType().toString();
break;
case DNE: name=null;
break;
case ENTITY_INV:
String entityName=stored_entity.getName();
String entityType=stored_entity.getType().toString();
name=String.format("%s:%s",entityType,entityName);
break;
case ITEM: name="item";
break;
default: throw new java.lang.Error("Unknown egg storage type");
}
//save stored_as
if (stored_as!=null) {
dataDao.write("stored_as", stored_as.name());
} else {
dataDao.write("stored_as", Egg_Storage_Type.DNE.name());
}
//save owner
dataDao.write("owner", owner);
//save timestamp
dataDao.write("timestamp", LocalDateTime.now().toString());
//write to file
dataDao.save();
}
public String serializeLocation(Location loc) {
return loc.getWorld().getName() + ":" + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ();
}
}

View file

@ -0,0 +1,39 @@
package io.github.J0hnL0cke.egghunt.Persistence;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Reads and writes key/value pairs to/from the plugin's config.yml file
*/
public class ConfigDAO {
JavaPlugin plugin;
public ConfigDAO(JavaPlugin plugin) {
this.plugin = plugin;
}
public void write(String key, String value) {
plugin.getConfig().set(key,value);
plugin.saveConfig();
}
public String read(String key, String not_found) {
return plugin.getConfig().getString(key,not_found);
}
public boolean keyExists(String key) {
return plugin.getConfig().contains(key);
}
/**
* Read the given key as a boolean, defaulting to false if not found or if the value is not a boolean
* @param key the key to read from
* @return the boolean value at that key, or false if the key is not found or the value is invalid
*/
public boolean readBool(String key) {
return Boolean.parseBoolean(read(key, "false"));
}
}

View file

@ -0,0 +1,66 @@
package io.github.J0hnL0cke.egghunt.Persistence;
import java.io.IOException;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class DataDAO {
public static final String DATA_FILE = "data.yml";
private static DataDAO thisDao;
private FileConfiguration fileConfig;
private File file;
JavaPlugin plugin;
private DataDAO(JavaPlugin plugin){
this.plugin = plugin;
loadData(plugin, DATA_FILE);
}
public static DataDAO getDataDAO(JavaPlugin plugin){
if(thisDao == null){
thisDao = new DataDAO(plugin);
}
return thisDao;
}
/**
* Create the save file if necessary. Also load the save data
*/
private void loadData(JavaPlugin plugin, String ymlName) {
File file = new File(plugin.getDataFolder(), ymlName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
//TODO warn user
}
}
fileConfig = YamlConfiguration.loadConfiguration(file);
}
public void save() {
try {
fileConfig.save(file);
} catch (IOException e) {
Bukkit.getServer().getLogger().severe(String.format("Could not save data file!"));
}
}
public void write(String key, Object value) {
fileConfig.set(key, value);
}
public <V> V read(String key, Class<V> clazz, V notFound) {
return fileConfig.getObject(key, clazz, notFound);
}
}

View file

@ -1,35 +1,41 @@
package io.github.J0hnL0cke.egghunt;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.CompassMeta;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import io.github.J0hnL0cke.egghunt.Controller.CommandHandler;
import io.github.J0hnL0cke.egghunt.Controller.EggHuntListener;
import io.github.J0hnL0cke.egghunt.Controller.EventScheduler;
import io.github.J0hnL0cke.egghunt.Model.Configuration;
import io.github.J0hnL0cke.egghunt.Model.Data;
import io.github.J0hnL0cke.egghunt.Persistence.ConfigDAO;
import io.github.J0hnL0cke.egghunt.Persistence.DataDAO;
public final class egghunt extends JavaPlugin {
Configuration config;
Data data;
CommandHandler commandHandler;
FileSave config = new FileSave(this);
EventScheduler schedule=new EventScheduler(this);
EggHuntListener listener=new EggHuntListener(getLogger(),config);
EventScheduler schedule;
EggHuntListener listener;
BukkitTask belowWorldTask;
private static final String notPermitted="Insufficient permission";
@Override
public void onEnable() {
public void onEnable() {
//load saved data
getLogger().info("onEnable has been invoked, loading save data.");
saveDefaultConfig();
config.loadData();
getLogger().info("onEnable has been invoked, starting EggHunt.");
saveDefaultConfig();
//create model instances using dependency injection
config = new Configuration(new ConfigDAO(this));
data = new Data(DataDAO.getDataDAO(this), getLogger());
//create controller instances
listener = new EggHuntListener(getLogger(), config, data);
schedule = new EventScheduler(config, data);
//register event handlers
getLogger().info("registering event listeners.");
@ -50,172 +56,10 @@ public final class egghunt extends JavaPlugin {
}
getLogger().info("Done!");
}
public static Location getEggLocation() {
if (EggHuntListener.stored_as!= EggHuntListener.Egg_Storage_Type.DNE) {
boolean is_entity;
switch (EggHuntListener.stored_as) {
case BLOCK:
case CONTAINER_INV:
is_entity=false;
break;
case ENTITY_INV:
case ITEM:
is_entity=true;
break;
default:
throw new java.lang.Error("Unknown egg storage type when calling getEggLocation()"); //fail loudly instead of silently, you're welcome
}
return is_entity ? EggHuntListener.stored_entity.getLocation() : EggHuntListener.loc;
}
return null;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("locateegg")) {
if (sender.hasPermission("egghunt.locateegg")) {
String eggContainer="";
switch (EggHuntListener.stored_as) {
case BLOCK: eggContainer="has been placed";
break;
case CONTAINER_INV: eggContainer="is in a ".concat(EggHuntListener.loc.getBlock().getType().toString().toLowerCase());
break;
case ENTITY_INV: eggContainer="is in the inventory of ".concat(EggHuntListener.stored_entity.getName());
break;
case ITEM:eggContainer="is an item";
break;
default:eggContainer="does not exist";
break;
}
String egg_loc_str=""; //make this empty so if egg does not exist, it remains blank
if (EggHuntListener.stored_as!= EggHuntListener.Egg_Storage_Type.DNE){
Location egg_loc=getEggLocation();
// May occasionally produce a NullPointerException, assert that it wont
assert egg_loc != null;
int egg_x=egg_loc.getBlockX();
int egg_y=egg_loc.getBlockY();
int egg_z=egg_loc.getBlockZ();
String egg_world=egg_loc.getWorld().getName();
egg_loc_str=String.format(" at %d, %d, %d in %s",egg_x,egg_y,egg_z,egg_world);
}
sender.sendMessage("The dragon egg ".concat(eggContainer).concat(egg_loc_str).concat("."));
} else {
sender.sendMessage(notPermitted);
}
return true;
} else if (cmd.getName().equalsIgnoreCase("trackegg")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player, use /locateegg instead.");
} else {
if (sender.hasPermission("egghunt.trackegg")) {
Player player = (Player) sender;
//roundabout way of getting the item the player is holding in their hotbar
ItemStack held_item=player.getInventory().getItemInMainHand();
if (held_item.getType().equals(Material.COMPASS)) {
if (EggHuntListener.stored_as!= EggHuntListener.Egg_Storage_Type.DNE) {
Location egg_loc=getEggLocation();
if (player.getWorld().equals(egg_loc.getWorld())) {
CompassMeta meta = (CompassMeta) held_item.getItemMeta();
meta.setLodestoneTracked(false);
meta.setLodestone(egg_loc);
held_item.setItemMeta(meta);
sender.sendMessage("Compass set to track last known dragon egg position.");
} else {
sender.sendMessage("Not in the same dimension as the egg.");
sender.sendMessage(String.format("The egg is in %s.",egg_loc.getWorld().getName()));
}
}
else {
sender.sendMessage("The dragon egg does not exist.");
}
}
else {
sender.sendMessage("You must be holding a compass to use this command, use /locateegg instead.");
}
} else {
sender.sendMessage(notPermitted);
}
}
return true;
} else if (cmd.getName().equalsIgnoreCase("eggowner")) {
if (sender.hasPermission("egghunt.eggowner")) {
if (EggHuntListener.owner==null) {
sender.sendMessage("The dragon egg is currently unclaimed");
} else {
sender.sendMessage(String.format("The dragon egg belongs to %s.", get_username_from_uuid(EggHuntListener.owner)));
sender.sendMessage("Don't steal it!");
}
} else {
sender.sendMessage(notPermitted);
}
return true;
//TODO: add notification toggle
//requires a permission plugin api or some code run at onEnable, onJoin, and onDisconnect to implement
/*} else if (cmd.getName().equalsIgnoreCase("eggnotify")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
} else {
if (args.length==0) {
String isNotifying="OFF";
if (sender.hasPermission("egghunt.notify")) {
isNotifying="ON";
}
sender.sendMessage(String.format("Dragon egg notifications for %s are set to %s", sender.getName(), isNotifying));
} else if (sender.hasPermission("egghunt.togglenotify")) {
boolean currentPerm=sender.hasPermission("egghunt.notify");
boolean newPerm=true;//only need to initialize to prevent warning
boolean isValid=true;
String name="";
String state=args[0].toLowerCase();
if (state.equals("on")) {
newPerm=true;
name="ON";
} else if (state.equals("off")) {
newPerm=false;
name="OFF";
} else {
sender.sendMessage(String.format("Unknown argument %s", state));
isValid=false;
}
if (isValid) {
if (currentPerm==newPerm) {
sender.sendMessage(String.format("Dragon egg notifications are already set to %s", name));
} else {
PermissionAttachment attachment = sender.addAttachment(this);
attachment.setPermission("egghunt.notify", newPerm);
attachment.remove();
sender.sendMessage(String.format("Dragon egg notifications have been set to %s", name));
}
}
} else {
sender.sendMessage(notPermitted);
}
}
return true;*/
}
//if no command is found
return false;
}
public static String get_username_from_uuid(UUID id) {
return Bukkit.getOfflinePlayer(id).getName();
return commandHandler.onCommand(sender, cmd, label, args);
}
}

View file

@ -15,11 +15,6 @@ resp_imm: false
#whether to drop any eggs that players have in their ender chest onto the ground. Setting this to false will ignore that egg entirely.
drop_enderchested_egg: false
#whether to use mongoDB
use_db: false
db_name: null
db_password: null
#egg location information
######## Do not edit unless you know what you're doing ########
stored_entity: null