Get closer to finishing the better saving and loading system

This commit is contained in:
SeanOMik 2020-01-21 10:42:42 -06:00
parent 7db8c8b47a
commit 4fa1bef8fb
13 changed files with 862 additions and 2390 deletions

View File

@ -1,242 +1,248 @@
package net.seanomilk.tamablefoxes; package net.seanomik.tamablefoxes;
import net.minecraft.server.v1_15_R1.*; import net.minecraft.server.v1_15_R1.*;
import net.seanomilk.tamablefoxes.pathfinding.*; import net.seanomik.tamablefoxes.pathfinding.*;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld; import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.event.CraftEventFactory; import org.bukkit.craftbukkit.v1_15_R1.event.CraftEventFactory;
import org.bukkit.entity.Fox; import org.bukkit.entity.Fox;
import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
public class EntityTamableFox extends EntityFox { public class EntityTamableFox extends EntityFox {
private static Fox thisFox; private static Fox thisFox;
private final TamableFoxes plugin; private final TamableFoxes plugin;
private boolean isTamed; private boolean isTamed;
private EntityLiving owner; private EntityLiving owner;
private String chosenName; private String chosenName;
private boolean sit = false; private boolean sit = false;
private BukkitTask sittingRunnable; private BukkitTask sittingRunnable;
private FoxPathfindGoalSit goalSit; private FoxPathfindGoalSit goalSit;
private PathfinderGoalNearestAttackableTarget goalAttack; private PathfinderGoalNearestAttackableTarget goalAttack;
public EntityTamableFox(TamableFoxes plugin, EntityTypes entitytypes, World world) { public int databaseID = -1;
super(EntityTypes.FOX, world);
this.plugin = plugin; public EntityTamableFox(TamableFoxes plugin, EntityTypes entitytypes, World world) {
thisFox = (Fox) this.getBukkitEntity(); super(EntityTypes.FOX, world);
plugin.getFoxUUIDs().put(this.getBukkitEntity().getUniqueId(), null); this.plugin = plugin;
this.setPersistent(); thisFox = (Fox) this.getBukkitEntity();
}
if (!plugin.getFoxUUIDs().containsKey(thisFox.getUniqueId())) {
@Override plugin.getFoxUUIDs().put(this.getBukkitEntity().getUniqueId(), null);
protected void initPathfinder() { }
this.goalSit = new FoxPathfindGoalSit(this);
this.goalSelector.a(1, new FoxPathfindGoalFloat(this)); this.setPersistent();
this.goalSelector.a(2, this.goalSit); }
this.goalSelector.a(3, new FoxPathfindGoalMeleeAttack(this, 1.2000000476837158D, true));
this.goalSelector.a(3, new PathfinderGoalAvoidTarget(this, EntityWolf.class, 8.0F, 1.6D, 1.4D, @Override
entityliving -> !((EntityWolf) entityliving).isTamed())); protected void initPathfinder() {
this.goalSelector.a(4, new FoxPathfindGoalFollowOwner(this, 1.35D, 10.0F, 2.0F)); this.goalSit = new FoxPathfindGoalSit(this);
this.goalSelector.a(4, new FoxPathfindGoalLungeUNKNOWN_USE(this)); this.goalSelector.a(1, new FoxPathfindGoalFloat(this));
this.goalSelector.a(5, new FoxPathfindGoalLunge(this)); this.goalSelector.a(2, this.goalSit);
this.goalSelector.a(5, new FoxPathfindGoalFleeSun(this, 1.25D)); this.goalSelector.a(3, new FoxPathfindGoalMeleeAttack(this, 1.2000000476837158D, true));
this.goalSelector.a(5, new FoxPathfindGoalBreed(this, 1.0D)); this.goalSelector.a(3, new PathfinderGoalAvoidTarget(this, EntityWolf.class, 8.0F, 1.6D, 1.4D,
this.goalSelector.a(7, new PathfinderGoalFollowParent(this, 1.1D)); entityliving -> !((EntityWolf) entityliving).isTamed()));
this.goalSelector.a(7, new FoxPathfindGoalBeg(this, 8.0F)); this.goalSelector.a(4, new FoxPathfindGoalFollowOwner(this, 1.35D, 10.0F, 2.0F));
this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); this.goalSelector.a(4, new FoxPathfindGoalLungeUNKNOWN_USE(this));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); this.goalSelector.a(5, new FoxPathfindGoalLunge(this));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2)); this.goalSelector.a(5, new FoxPathfindGoalFleeSun(this, 1.25D));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2)); this.goalSelector.a(5, new FoxPathfindGoalBreed(this, 1.0D));
this.goalSelector.a(10, new FoxPathfindGoalRandomStrollLand(this, 1.0D)); this.goalSelector.a(7, new PathfinderGoalFollowParent(this, 1.1D));
this.targetSelector.a(1, new FoxPathfindGoalHurtByTarget(this)); this.goalSelector.a(7, new FoxPathfindGoalBeg(this, 8.0F));
this.targetSelector.a(2, new FoxPathfindGoalOwnerHurtByTarget(this)); this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this));
this.goalAttack = new PathfinderGoalNearestAttackableTarget(this, EntityLiving.class, 10, false, false, this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
entityLiving -> !isTamed && (entityLiving instanceof EntityChicken || entityLiving instanceof EntityRabbit)); this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
this.goalSelector.a(10, new FoxPathfindGoalRandomStrollLand(this, 1.0D));
if (!isTamed || (plugin.isTamedAttackRabbitChicken() && isTamed)) { this.targetSelector.a(1, new FoxPathfindGoalHurtByTarget(this));
this.targetSelector.a(4, goalAttack); this.targetSelector.a(2, new FoxPathfindGoalOwnerHurtByTarget(this));
}
this.goalAttack = new PathfinderGoalNearestAttackableTarget(this, EntityLiving.class, 10, false, false,
this.targetSelector.a(5, new FoxPathfindGoalHurtByTarget(this).a(new Class[0])); entityLiving -> !isTamed && (entityLiving instanceof EntityChicken || entityLiving instanceof EntityRabbit));
}
if (!isTamed || (plugin.isTamedAttackRabbitChicken() && isTamed)) {
@Override this.targetSelector.a(4, goalAttack);
protected void initAttributes() { }
this.getAttributeMap().b(GenericAttributes.MAX_HEALTH);
this.getAttributeMap().b(GenericAttributes.KNOCKBACK_RESISTANCE); this.targetSelector.a(5, new FoxPathfindGoalHurtByTarget(this).a(new Class[0]));
this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED); }
this.getAttributeMap().b(GenericAttributes.ARMOR);
this.getAttributeMap().b(GenericAttributes.ARMOR_TOUGHNESS); @Override
this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(2.0D); protected void initAttributes() {
this.getAttributeMap().b(GenericAttributes.ATTACK_KNOCKBACK); this.getAttributeMap().b(GenericAttributes.MAX_HEALTH);
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); this.getAttributeMap().b(GenericAttributes.KNOCKBACK_RESISTANCE);
this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D); this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D); this.getAttributeMap().b(GenericAttributes.ARMOR);
this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D); this.getAttributeMap().b(GenericAttributes.ARMOR_TOUGHNESS);
} this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(2.0D);
this.getAttributeMap().b(GenericAttributes.ATTACK_KNOCKBACK);
public EntityFox createChild(EntityAgeable entityageable) { this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D);
WorldServer world = ((CraftWorld) entityageable.getBukkitEntity().getWorld()).getHandle(); this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D);
Location location = entityageable.getBukkitEntity().getLocation(); this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D);
Entity b = plugin.getCustomType().b(world, null, null, null, this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D);
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false); }
EntityFox entityfox = (EntityFox) b;
entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType()); public EntityFox createChild(EntityAgeable entityageable) {
return entityfox; WorldServer world = ((CraftWorld) entityageable.getBukkitEntity().getWorld()).getHandle();
} Location location = entityageable.getBukkitEntity().getLocation();
Entity b = plugin.getCustomType().b(world, null, null, null,
protected void a(EntityItem entityitem) { new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
ItemStack itemstack = entityitem.getItemStack(); EntityFox entityfox = (EntityFox) b;
if (!this.isTamed() && !CraftEventFactory.callEntityPickupItemEvent(this, entityitem, entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType());
itemstack.getCount() - 1, !this.g(itemstack)).isCancelled()) { return entityfox;
try { }
int i = itemstack.getCount();
Method method; protected void a(EntityItem entityitem) {
if (i > 1) { ItemStack itemstack = entityitem.getItemStack();
method = this.getClass().getSuperclass().getDeclaredMethod("l", ItemStack.class); if (!this.isTamed() && !CraftEventFactory.callEntityPickupItemEvent(this, entityitem,
method.setAccessible(true); itemstack.getCount() - 1, !this.g(itemstack)).isCancelled()) {
method.invoke(this, itemstack.cloneAndSubtract(i - 1)); try {
method.setAccessible(false); int i = itemstack.getCount();
} Method method;
if (i > 1) {
method = this.getClass().getSuperclass().getDeclaredMethod("k", ItemStack.class); method = this.getClass().getSuperclass().getDeclaredMethod("l", ItemStack.class);
method.setAccessible(true); method.setAccessible(true);
method.invoke(this, this.getEquipment(EnumItemSlot.MAINHAND)); method.invoke(this, itemstack.cloneAndSubtract(i - 1));
method.setAccessible(false); method.setAccessible(false);
this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1)); }
this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F;
this.receive(entityitem, itemstack.getCount()); method = this.getClass().getSuperclass().getDeclaredMethod("k", ItemStack.class);
entityitem.die(); method.setAccessible(true);
Field field = this.getClass().getSuperclass().getDeclaredField("bL"); method.invoke(this, this.getEquipment(EnumItemSlot.MAINHAND));
field.setAccessible(true); method.setAccessible(false);
field.set(this, 0); this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1));
field.setAccessible(false); this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F;
} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { this.receive(entityitem, itemstack.getCount());
e.printStackTrace(); entityitem.die();
} Field field = this.getClass().getSuperclass().getDeclaredField("bL");
} field.setAccessible(true);
field.set(this, 0);
} field.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
public TamableFoxes getPlugin() { e.printStackTrace();
return plugin; }
} }
public boolean isTamed() { }
return this.isTamed;
} public TamableFoxes getPlugin() {
return plugin;
public void setTamed(boolean tamed) { }
this.isTamed = tamed;
// Remove attack goal if tamed public boolean isTamed() {
if (isTamed && plugin.isTamedAttackRabbitChicken()) { return this.isTamed;
this.targetSelector.a(goalAttack); }
} else {
this.targetSelector.a(4, goalAttack); public void setTamed(boolean tamed) {
} this.isTamed = tamed;
}
// Remove attack goal if tamed
public String getChosenName() { if (isTamed && plugin.isTamedAttackRabbitChicken()) {
return chosenName; this.targetSelector.a(goalAttack);
} } else { // Adds it
this.targetSelector.a(4, goalAttack);
public void setChosenName(String chosenName) { }
this.chosenName = chosenName; }
plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".name", chosenName).save();
updateFoxVisual(); public String getChosenName() {
} return chosenName;
}
public EntityLiving getOwner() {
return this.owner; public void setChosenName(String chosenName) {
} this.chosenName = chosenName;
updateFoxVisual();
public void setOwner(EntityLiving owner) { }
this.owner = owner;
plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".owner", owner.getUniqueIDString()).save(); public EntityLiving getOwner() {
updateFoxVisual(); return this.owner;
} }
public boolean toggleSitting() { public void setOwner(EntityLiving owner) {
this.sit = !this.sit; this.owner = owner;
updateFoxVisual(); updateFoxVisual();
return this.sit; }
}
public boolean toggleSitting() {
public void updateFox() { this.sit = !this.sit;
updateFoxVisual(); updateFoxVisual();
}
plugin.sqLiteSetterGetter.saveFox(this);
public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, return this.sit;
EnumMobSpawn enummobspawn, GroupDataEntity groupdataentity, NBTTagCompound nbttagcompound) { }
BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this));
Type entityfox_type = Type.a(biomebase); public void updateFox() {
boolean flag = false; updateFoxVisual();
if (groupdataentity instanceof i) { }
entityfox_type = ((i) groupdataentity).a;
if (((i) groupdataentity).a() >= 2) { public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler,
flag = true; EnumMobSpawn enummobspawn, GroupDataEntity groupdataentity, NBTTagCompound nbttagcompound) {
} else { BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this));
((i) groupdataentity).b(); Type entityfox_type = Type.a(biomebase);
} boolean flag = false;
} else { if (groupdataentity instanceof i) {
groupdataentity = new i(entityfox_type); entityfox_type = ((i) groupdataentity).a;
((i) groupdataentity).b(); if (((i) groupdataentity).a() >= 2) {
} flag = true;
} else {
this.setFoxType(entityfox_type); ((i) groupdataentity).b();
if (flag) { }
this.setAgeRaw(-24000); } else {
} groupdataentity = new i(entityfox_type);
((i) groupdataentity).b();
this.initPathfinder(); }
this.a(difficultydamagescaler);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random spawn bonus", this.setFoxType(entityfox_type);
this.random.nextGaussian() * 0.05D, AttributeModifier.Operation.MULTIPLY_BASE)); if (flag) {
if (this.random.nextFloat() < 0.05F) { this.setAgeRaw(-24000);
this.p(true); }
} else {
this.p(false); this.initPathfinder();
} this.a(difficultydamagescaler);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random spawn bonus",
return groupdataentity; this.random.nextGaussian() * 0.05D, AttributeModifier.Operation.MULTIPLY_BASE));
} if (this.random.nextFloat() < 0.05F) {
this.p(true);
public boolean isJumping() { } else {
return this.jumping; this.p(false);
} }
private void updateFoxVisual() { return groupdataentity;
this.sittingRunnable = new UpdateFoxRunnable(plugin).runTask(plugin); }
}
public boolean isJumping() {
private class UpdateFoxRunnable extends BukkitRunnable { return this.jumping;
}
private final TamableFoxes plugin;
private void updateFoxVisual() {
UpdateFoxRunnable(TamableFoxes plugin) { this.sittingRunnable = new UpdateFoxRunnable(plugin).runTask(plugin);
this.plugin = plugin; }
}
private class UpdateFoxRunnable extends BukkitRunnable {
public void run() {
goalSit.setSitting(sit); private final TamableFoxes plugin;
thisFox.setVelocity(new Vector(0, 0, 0));
setGoalTarget(null, EntityTargetEvent.TargetReason.CUSTOM, true); UpdateFoxRunnable(TamableFoxes plugin) {
this.plugin = plugin;
getBukkitEntity().setCustomName((chosenName != null ? chosenName : "") }
+ (owner != null && plugin.isShowOwnerFoxName() ? ChatColor.RESET + " (" + owner.getName() + ")" : ""));
getBukkitEntity().setCustomNameVisible(plugin.isShowNameTags()); public void run() {
} goalSit.setSitting(sit);
} thisFox.setVelocity(new Vector(0, 0, 0));
setGoalTarget(null, EntityTargetEvent.TargetReason.CUSTOM, true);
}
getBukkitEntity().setCustomName((chosenName != null ? chosenName : "")
+ (owner != null && plugin.isShowOwnerFoxName() ? ChatColor.RESET + " (" + owner.getName() + ")" : ""));
getBukkitEntity().setCustomNameVisible(plugin.isShowNameTags());
}
}
}

View File

@ -1,248 +0,0 @@
package net.seanomik.tamablefoxes;
import net.minecraft.server.v1_15_R1.*;
import net.seanomik.tamablefoxes.pathfinding.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.event.CraftEventFactory;
import org.bukkit.entity.Fox;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EntityTamableFox extends EntityFox {
private static Fox thisFox;
private final TamableFoxes plugin;
private boolean isTamed;
private EntityLiving owner;
private String chosenName;
private boolean sit = false;
private BukkitTask sittingRunnable;
private FoxPathfindGoalSit goalSit;
private PathfinderGoalNearestAttackableTarget goalAttack;
public int databaseIndex = -1;
public EntityTamableFox(TamableFoxes plugin, EntityTypes entitytypes, World world) {
super(EntityTypes.FOX, world);
this.plugin = plugin;
thisFox = (Fox) this.getBukkitEntity();
if (!plugin.getFoxUUIDs().containsKey(thisFox.getUniqueId())) {
plugin.getFoxUUIDs().put(this.getBukkitEntity().getUniqueId(), null);
}
this.setPersistent();
}
@Override
protected void initPathfinder() {
this.goalSit = new FoxPathfindGoalSit(this);
this.goalSelector.a(1, new FoxPathfindGoalFloat(this));
this.goalSelector.a(2, this.goalSit);
this.goalSelector.a(3, new FoxPathfindGoalMeleeAttack(this, 1.2000000476837158D, true));
this.goalSelector.a(3, new PathfinderGoalAvoidTarget(this, EntityWolf.class, 8.0F, 1.6D, 1.4D,
entityliving -> !((EntityWolf) entityliving).isTamed()));
this.goalSelector.a(4, new FoxPathfindGoalFollowOwner(this, 1.35D, 10.0F, 2.0F));
this.goalSelector.a(4, new FoxPathfindGoalLungeUNKNOWN_USE(this));
this.goalSelector.a(5, new FoxPathfindGoalLunge(this));
this.goalSelector.a(5, new FoxPathfindGoalFleeSun(this, 1.25D));
this.goalSelector.a(5, new FoxPathfindGoalBreed(this, 1.0D));
this.goalSelector.a(7, new PathfinderGoalFollowParent(this, 1.1D));
this.goalSelector.a(7, new FoxPathfindGoalBeg(this, 8.0F));
this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
this.goalSelector.a(10, new FoxPathfindGoalRandomStrollLand(this, 1.0D));
this.targetSelector.a(1, new FoxPathfindGoalHurtByTarget(this));
this.targetSelector.a(2, new FoxPathfindGoalOwnerHurtByTarget(this));
this.goalAttack = new PathfinderGoalNearestAttackableTarget(this, EntityLiving.class, 10, false, false,
entityLiving -> !isTamed && (entityLiving instanceof EntityChicken || entityLiving instanceof EntityRabbit));
if (!isTamed || (plugin.isTamedAttackRabbitChicken() && isTamed)) {
this.targetSelector.a(4, goalAttack);
}
this.targetSelector.a(5, new FoxPathfindGoalHurtByTarget(this).a(new Class[0]));
}
@Override
protected void initAttributes() {
this.getAttributeMap().b(GenericAttributes.MAX_HEALTH);
this.getAttributeMap().b(GenericAttributes.KNOCKBACK_RESISTANCE);
this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED);
this.getAttributeMap().b(GenericAttributes.ARMOR);
this.getAttributeMap().b(GenericAttributes.ARMOR_TOUGHNESS);
this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(2.0D);
this.getAttributeMap().b(GenericAttributes.ATTACK_KNOCKBACK);
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D);
this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D);
this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D);
}
public EntityFox createChild(EntityAgeable entityageable) {
WorldServer world = ((CraftWorld) entityageable.getBukkitEntity().getWorld()).getHandle();
Location location = entityageable.getBukkitEntity().getLocation();
Entity b = plugin.getCustomType().b(world, null, null, null,
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
EntityFox entityfox = (EntityFox) b;
entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType());
return entityfox;
}
protected void a(EntityItem entityitem) {
ItemStack itemstack = entityitem.getItemStack();
if (!this.isTamed() && !CraftEventFactory.callEntityPickupItemEvent(this, entityitem,
itemstack.getCount() - 1, !this.g(itemstack)).isCancelled()) {
try {
int i = itemstack.getCount();
Method method;
if (i > 1) {
method = this.getClass().getSuperclass().getDeclaredMethod("l", ItemStack.class);
method.setAccessible(true);
method.invoke(this, itemstack.cloneAndSubtract(i - 1));
method.setAccessible(false);
}
method = this.getClass().getSuperclass().getDeclaredMethod("k", ItemStack.class);
method.setAccessible(true);
method.invoke(this, this.getEquipment(EnumItemSlot.MAINHAND));
method.setAccessible(false);
this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1));
this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F;
this.receive(entityitem, itemstack.getCount());
entityitem.die();
Field field = this.getClass().getSuperclass().getDeclaredField("bL");
field.setAccessible(true);
field.set(this, 0);
field.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public TamableFoxes getPlugin() {
return plugin;
}
public boolean isTamed() {
return this.isTamed;
}
public void setTamed(boolean tamed) {
this.isTamed = tamed;
// Remove attack goal if tamed
if (isTamed && plugin.isTamedAttackRabbitChicken()) {
this.targetSelector.a(goalAttack);
} else {
this.targetSelector.a(4, goalAttack);
}
}
public String getChosenName() {
return chosenName;
}
public void setChosenName(String chosenName) {
this.chosenName = chosenName;
//plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".name", chosenName).save();
updateFoxVisual();
}
public EntityLiving getOwner() {
return this.owner;
}
public void setOwner(EntityLiving owner) {
this.owner = owner;
//plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".owner", owner.getUniqueIDString()).save();
updateFoxVisual();
}
public boolean toggleSitting() {
this.sit = !this.sit;
updateFoxVisual();
return this.sit;
}
public void updateFox() {
updateFoxVisual();
}
public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler,
EnumMobSpawn enummobspawn, GroupDataEntity groupdataentity, NBTTagCompound nbttagcompound) {
BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this));
Type entityfox_type = Type.a(biomebase);
boolean flag = false;
if (groupdataentity instanceof i) {
entityfox_type = ((i) groupdataentity).a;
if (((i) groupdataentity).a() >= 2) {
flag = true;
} else {
((i) groupdataentity).b();
}
} else {
groupdataentity = new i(entityfox_type);
((i) groupdataentity).b();
}
this.setFoxType(entityfox_type);
if (flag) {
this.setAgeRaw(-24000);
}
this.initPathfinder();
this.a(difficultydamagescaler);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random spawn bonus",
this.random.nextGaussian() * 0.05D, AttributeModifier.Operation.MULTIPLY_BASE));
if (this.random.nextFloat() < 0.05F) {
this.p(true);
} else {
this.p(false);
}
return groupdataentity;
}
public boolean isJumping() {
return this.jumping;
}
private void updateFoxVisual() {
this.sittingRunnable = new UpdateFoxRunnable(plugin).runTask(plugin);
}
private class UpdateFoxRunnable extends BukkitRunnable {
private final TamableFoxes plugin;
UpdateFoxRunnable(TamableFoxes plugin) {
this.plugin = plugin;
}
public void run() {
goalSit.setSitting(sit);
thisFox.setVelocity(new Vector(0, 0, 0));
setGoalTarget(null, EntityTargetEvent.TargetReason.CUSTOM, true);
getBukkitEntity().setCustomName((chosenName != null ? chosenName : "")
+ (owner != null && plugin.isShowOwnerFoxName() ? ChatColor.RESET + " (" + owner.getName() + ")" : ""));
getBukkitEntity().setCustomNameVisible(plugin.isShowNameTags());
}
}
}

View File

@ -1,242 +0,0 @@
package net.seanomilk.tamablefoxes;
import net.minecraft.server.v1_15_R1.*;
import net.seanomilk.tamablefoxes.pathfinding.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.event.CraftEventFactory;
import org.bukkit.entity.Fox;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EntityTamableFox extends EntityFox {
private static Fox thisFox;
private final TamableFoxes plugin;
private boolean isTamed;
private EntityLiving owner;
private String chosenName;
private boolean sit = false;
private BukkitTask sittingRunnable;
private FoxPathfindGoalSit goalSit;
private PathfinderGoalNearestAttackableTarget goalAttack;
public EntityTamableFox(TamableFoxes plugin, EntityTypes entitytypes, World world) {
super(EntityTypes.FOX, world);
this.plugin = plugin;
thisFox = (Fox) this.getBukkitEntity();
plugin.getFoxUUIDs().put(this.getBukkitEntity().getUniqueId(), null);
this.setPersistent();
}
@Override
protected void initPathfinder() {
this.goalSit = new FoxPathfindGoalSit(this);
this.goalSelector.a(1, new FoxPathfindGoalFloat(this));
this.goalSelector.a(2, this.goalSit);
this.goalSelector.a(3, new FoxPathfindGoalMeleeAttack(this, 1.2000000476837158D, true));
this.goalSelector.a(3, new PathfinderGoalAvoidTarget(this, EntityWolf.class, 8.0F, 1.6D, 1.4D,
entityliving -> !((EntityWolf) entityliving).isTamed()));
this.goalSelector.a(4, new FoxPathfindGoalFollowOwner(this, 1.35D, 10.0F, 2.0F));
this.goalSelector.a(4, new FoxPathfindGoalLungeUNKNOWN_USE(this));
this.goalSelector.a(5, new FoxPathfindGoalLunge(this));
this.goalSelector.a(5, new FoxPathfindGoalFleeSun(this, 1.25D));
this.goalSelector.a(5, new FoxPathfindGoalBreed(this, 1.0D));
this.goalSelector.a(7, new PathfinderGoalFollowParent(this, 1.1D));
this.goalSelector.a(7, new FoxPathfindGoalBeg(this, 8.0F));
this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
this.goalSelector.a(9, new FoxPathfindGoalPickBushes(this, 1.2000000476837158D, 12, 2));
this.goalSelector.a(10, new FoxPathfindGoalRandomStrollLand(this, 1.0D));
this.targetSelector.a(1, new FoxPathfindGoalHurtByTarget(this));
this.targetSelector.a(2, new FoxPathfindGoalOwnerHurtByTarget(this));
this.goalAttack = new PathfinderGoalNearestAttackableTarget(this, EntityLiving.class, 10, false, false,
entityLiving -> !isTamed && (entityLiving instanceof EntityChicken || entityLiving instanceof EntityRabbit));
if (!isTamed || (plugin.isTamedAttackRabbitChicken() && isTamed)) {
this.targetSelector.a(4, goalAttack);
}
this.targetSelector.a(5, new FoxPathfindGoalHurtByTarget(this).a(new Class[0]));
}
@Override
protected void initAttributes() {
this.getAttributeMap().b(GenericAttributes.MAX_HEALTH);
this.getAttributeMap().b(GenericAttributes.KNOCKBACK_RESISTANCE);
this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED);
this.getAttributeMap().b(GenericAttributes.ARMOR);
this.getAttributeMap().b(GenericAttributes.ARMOR_TOUGHNESS);
this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(2.0D);
this.getAttributeMap().b(GenericAttributes.ATTACK_KNOCKBACK);
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D);
this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D);
this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D);
}
public EntityFox createChild(EntityAgeable entityageable) {
WorldServer world = ((CraftWorld) entityageable.getBukkitEntity().getWorld()).getHandle();
Location location = entityageable.getBukkitEntity().getLocation();
Entity b = plugin.getCustomType().b(world, null, null, null,
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
EntityFox entityfox = (EntityFox) b;
entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType());
return entityfox;
}
protected void a(EntityItem entityitem) {
ItemStack itemstack = entityitem.getItemStack();
if (!this.isTamed() && !CraftEventFactory.callEntityPickupItemEvent(this, entityitem,
itemstack.getCount() - 1, !this.g(itemstack)).isCancelled()) {
try {
int i = itemstack.getCount();
Method method;
if (i > 1) {
method = this.getClass().getSuperclass().getDeclaredMethod("l", ItemStack.class);
method.setAccessible(true);
method.invoke(this, itemstack.cloneAndSubtract(i - 1));
method.setAccessible(false);
}
method = this.getClass().getSuperclass().getDeclaredMethod("k", ItemStack.class);
method.setAccessible(true);
method.invoke(this, this.getEquipment(EnumItemSlot.MAINHAND));
method.setAccessible(false);
this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1));
this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F;
this.receive(entityitem, itemstack.getCount());
entityitem.die();
Field field = this.getClass().getSuperclass().getDeclaredField("bL");
field.setAccessible(true);
field.set(this, 0);
field.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public TamableFoxes getPlugin() {
return plugin;
}
public boolean isTamed() {
return this.isTamed;
}
public void setTamed(boolean tamed) {
this.isTamed = tamed;
// Remove attack goal if tamed
if (isTamed && plugin.isTamedAttackRabbitChicken()) {
this.targetSelector.a(goalAttack);
} else {
this.targetSelector.a(4, goalAttack);
}
}
public String getChosenName() {
return chosenName;
}
public void setChosenName(String chosenName) {
this.chosenName = chosenName;
plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".name", chosenName).save();
updateFoxVisual();
}
public EntityLiving getOwner() {
return this.owner;
}
public void setOwner(EntityLiving owner) {
this.owner = owner;
plugin.getConfigFoxes().set("Foxes." + getUniqueID() + ".owner", owner.getUniqueIDString()).save();
updateFoxVisual();
}
public boolean toggleSitting() {
this.sit = !this.sit;
updateFoxVisual();
return this.sit;
}
public void updateFox() {
updateFoxVisual();
}
public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler,
EnumMobSpawn enummobspawn, GroupDataEntity groupdataentity, NBTTagCompound nbttagcompound) {
BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this));
Type entityfox_type = Type.a(biomebase);
boolean flag = false;
if (groupdataentity instanceof i) {
entityfox_type = ((i) groupdataentity).a;
if (((i) groupdataentity).a() >= 2) {
flag = true;
} else {
((i) groupdataentity).b();
}
} else {
groupdataentity = new i(entityfox_type);
((i) groupdataentity).b();
}
this.setFoxType(entityfox_type);
if (flag) {
this.setAgeRaw(-24000);
}
this.initPathfinder();
this.a(difficultydamagescaler);
this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random spawn bonus",
this.random.nextGaussian() * 0.05D, AttributeModifier.Operation.MULTIPLY_BASE));
if (this.random.nextFloat() < 0.05F) {
this.p(true);
} else {
this.p(false);
}
return groupdataentity;
}
public boolean isJumping() {
return this.jumping;
}
private void updateFoxVisual() {
this.sittingRunnable = new UpdateFoxRunnable(plugin).runTask(plugin);
}
private class UpdateFoxRunnable extends BukkitRunnable {
private final TamableFoxes plugin;
UpdateFoxRunnable(TamableFoxes plugin) {
this.plugin = plugin;
}
public void run() {
goalSit.setSitting(sit);
thisFox.setVelocity(new Vector(0, 0, 0));
setGoalTarget(null, EntityTargetEvent.TargetReason.CUSTOM, true);
getBukkitEntity().setCustomName((chosenName != null ? chosenName : "")
+ (owner != null && plugin.isShowOwnerFoxName() ? ChatColor.RESET + " (" + owner.getName() + ")" : ""));
getBukkitEntity().setCustomNameVisible(plugin.isShowNameTags());
}
}
}

View File

@ -1,515 +1,462 @@
package net.seanomilk.tamablefoxes; package net.seanomik.tamablefoxes;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.mojang.datafixers.DataFixUtils; import com.mojang.datafixers.DataFixUtils;
import com.mojang.datafixers.types.Type; import com.mojang.datafixers.types.Type;
import net.seanomilk.tamablefoxes.command.CommandSpawnTamableFox; import net.seanomik.tamablefoxes.command.CommandSpawnTamableFox;
import net.seanomilk.tamablefoxes.io.FileManager; import net.seanomik.tamablefoxes.io.FileManager;
import net.minecraft.server.v1_15_R1.*; import net.minecraft.server.v1_15_R1.*;
import net.wesjd.anvilgui.AnvilGUI; import net.seanomik.tamablefoxes.sqlite.SQLiteHandler;
import org.bukkit.Chunk; import net.seanomik.tamablefoxes.sqlite.SQLiteSetterGetter;
import org.bukkit.Material; import net.wesjd.anvilgui.AnvilGUI;
import org.bukkit.Particle; import org.bukkit.Chunk;
import org.bukkit.World; import org.bukkit.Material;
import org.bukkit.*; import org.bukkit.Particle;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.World;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld; import org.bukkit.*;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftEntity; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftFox; import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftItem; import org.bukkit.craftbukkit.v1_15_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_15_R1.entity.CraftFox;
import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer;
import org.bukkit.entity.Entity; import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack;
import org.bukkit.entity.EntityType; import org.bukkit.entity.Entity;
import org.bukkit.entity.Fox; import org.bukkit.entity.Fox;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.*; import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.player.*;
import org.bukkit.inventory.EquipmentSlot; import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.InvocationTargetException; import org.bukkit.scheduler.BukkitRunnable;
import java.lang.reflect.Method; import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.List; import java.util.Arrays;
import java.util.Map; import java.util.List;
import java.util.UUID; import java.util.Map;
import java.util.stream.Collectors; import java.util.UUID;
import java.util.stream.Collectors;
public class TamableFoxes extends JavaPlugin implements Listener {
// @TODO: Add language.yml
public static final String ITEM_INSPECTOR_LORE = ChatColor.BLUE + "Tamable Fox Inspector";
public static final String TAG_TAME_FOX = "tameablefox"; public class TamableFoxes extends JavaPlugin implements Listener {
private FileManager fileManager; public static final String ITEM_INSPECTOR_LORE = ChatColor.BLUE + "Tamable Fox Inspector";
public static final String TAG_TAME_FOX = "tameablefox";
private Map<UUID, UUID> foxUUIDs;
private EntityTypes customType; private FileManager fileManager = new FileManager(this);
private boolean isOnLoad = true; private Map<UUID, UUID> foxUUIDs = Maps.newHashMap(); // FoxUUID, OwnerUUID
private EntityTypes customType;
private Map<UUID, Entity> lookupCache; private boolean isOnLoad = true;
private Map<UUID, Entity> lookupCache = Maps.newHashMap();
private FileManager.Config config, configFoxes; private List<EntityTamableFox> spawnedFoxes;
private FileManager.Config config;//, configFoxes;
private Map<Player, UUID> waitingName; public static SQLiteHandler sqLiteHandler = new SQLiteHandler();
public static SQLiteSetterGetter sqLiteSetterGetter = new SQLiteSetterGetter();
@Override
public void onEnable() { @Override
String version = Bukkit.getServer().getClass().getPackage().getName(); public void onEnable() {
if (!version.equals("org.bukkit.craftbukkit.v1_15_R1")) { String version = Bukkit.getServer().getClass().getPackage().getName();
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "This plugin version only supports 1.15.1!"); if (!version.equals("org.bukkit.craftbukkit.v1_15_R1")) {
getServer().getPluginManager().disablePlugin(this); Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "This plugin version only supports 1.15.1!");
return; getServer().getPluginManager().disablePlugin(this);
} return;
}
fileManager = new FileManager(this);
this.config = fileManager.getConfig("config.yml"); this.config = fileManager.getConfig("config.yml");
this.config.copyDefaults(true).save(); this.config.copyDefaults(true).save();
this.configFoxes = fileManager.getConfig("foxes.yml");
this.configFoxes.copyDefaults(true).save(); sqLiteHandler.connect();
sqLiteSetterGetter.createTablesIfNotExist();
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("spawntamablefox").setExecutor(new CommandSpawnTamableFox(this)); this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("spawntamablefox").setExecutor(new CommandSpawnTamableFox(this));
this.foxUUIDs = Maps.newHashMap();
this.lookupCache = Maps.newHashMap(); final Map<String, Type<?>> types = (Map<String, Type<?>>) DataConverterRegistry.a()
this.waitingName = Maps.newHashMap(); .getSchema(DataFixUtils.makeKey(SharedConstants.getGameVersion().getWorldVersion()))
.findChoiceType(DataConverterTypes.ENTITY).types();
final Map<String, Type<?>> types = (Map<String, Type<?>>) DataConverterRegistry.a() types.put("minecraft:" + TAG_TAME_FOX, types.get("minecraft:fox"));
.getSchema(DataFixUtils.makeKey(SharedConstants.getGameVersion().getWorldVersion()))
.findChoiceType(DataConverterTypes.ENTITY).types(); EntityTypes.a<net.minecraft.server.v1_15_R1.Entity> a = EntityTypes.a.a((entityTypes, world) ->
types.put("minecraft:" + TAG_TAME_FOX, types.get("minecraft:fox")); new EntityTamableFox(this, entityTypes, world), EnumCreatureType.AMBIENT);
customType = IRegistry.a(IRegistry.ENTITY_TYPE, "tameablefox", a.a("tameablefox"));
EntityTypes.a<net.minecraft.server.v1_15_R1.Entity> a = EntityTypes.a.a((entityTypes, world) ->
new EntityTamableFox(this, entityTypes, world), EnumCreatureType.AMBIENT); this.replaceFoxesOnLoad();
customType = IRegistry.a(IRegistry.ENTITY_TYPE, "tameablefox", a.a("tameablefox")); }
this.replaceFoxesOnLoad(); @Override
} public void onDisable() {
try {
@Override for (EntityTamableFox fox : spawnedFoxes) {
public void onDisable() { sqLiteSetterGetter.saveFox(fox);
} fox.getBukkitEntity().remove();
}
private void replaceFoxesOnLoad() {
int amountReplaced = 0; getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.GREEN + "Saved all foxes successfully!");
} catch (Exception e) {
for (World world : Bukkit.getWorlds()) { getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.RED + "Failed to save foxes!");
Chunk[] loadedChunks = world.getLoadedChunks(); }
for (Chunk chunk : loadedChunks) { }
Entity[] entities = chunk.getEntities();
for (Entity entity : entities) { private void replaceFoxesOnLoad() {
if (!(entity instanceof Fox)) /*int amountReplaced = 0;
continue;
if (this.isTamableFox(entity)) for (World world : Bukkit.getWorlds()) {
continue; Chunk[] loadedChunks = world.getLoadedChunks();
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType()); for (Chunk chunk : loadedChunks) {
Entity[] entities = chunk.getEntities();
final YamlConfiguration configuration = configFoxes.get(); for (Entity entity : entities) {
// get living entity data if (!(entity instanceof Fox))
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) { continue;
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner"); if (this.isTamableFox(entity))
continue;
// make new data EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType());
if (owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), null); //final YamlConfiguration configuration = configFoxes.get();
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none"); // get living entity data
} else { if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner)); String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner");
tamableFox.setTamed(true);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner); // make new data
} if (owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), null);
// set name configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) { } else {
final String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name"); foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner));
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name); tamableFox.setTamed(true);
tamableFox.setChosenName(name); configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner);
} }
// delete old data // set name
configuration.set("Foxes." + entity.getUniqueId(), null); if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) {
final String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name");
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting()); configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.updateFox(); tamableFox.setChosenName(name);
tamableFox.setAge(((CraftFox) entity).getAge()); }
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) { // delete old data
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1))); configuration.set("Foxes." + entity.getUniqueId(), null);
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR)); tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting());
} tamableFox.updateFox();
tamableFox.setAge(((CraftFox) entity).getAge());
} else { ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none"); entityMouthItem.setAmount(1);
tamableFox.setAge(((CraftFox) entity).getAge()); if (entityMouthItem.getType() != Material.AIR) {
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand(); tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(entityMouthItem));
if (entityMouthItem.getType() != Material.AIR) { } else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1))); tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} else { }
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} } else {
} configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
entity.remove(); tamableFox.setAge(((CraftFox) entity).getAge());
++amountReplaced; ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
} entityMouthItem.setAmount(1);
}
} if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(entityMouthItem));
configFoxes.save(); } else {
this.isOnLoad = false; tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} }
}
public net.minecraft.server.v1_15_R1.Entity spawnTamableFox(Location location, net.minecraft.server.v1_15_R1.EntityFox.Type type) {
WorldServer world = ((CraftWorld) location.getWorld()).getHandle(); entity.remove();
net.minecraft.server.v1_15_R1.Entity spawnedEntity = customType.b(world, null, null, null, ++amountReplaced;
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false); }
}
world.addEntity(spawnedEntity); }
EntityFox fox = (EntityFox) spawnedEntity;
fox.setFoxType(type); configFoxes.save();*/
configFoxes.get().set("Foxes." + spawnedEntity.getUniqueID() + ".owner", "none"); spawnedFoxes = sqLiteSetterGetter.spawnFoxes();
fileManager.saveConfig("foxes.yml"); this.isOnLoad = false;
}
return fox;
} public net.minecraft.server.v1_15_R1.Entity spawnTamableFox(Location location, net.minecraft.server.v1_15_R1.EntityFox.Type type) {
WorldServer world = ((CraftWorld) location.getWorld()).getHandle();
@EventHandler EntityTamableFox spawnedFox = (EntityTamableFox) customType.b(world, null, null, null,
public void onChunkLoad(ChunkLoadEvent event) { new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
if (isOnLoad)
return; if (!world.addEntity(spawnedFox)) { // Throw a error if the fox failed to spawn
Chunk chunk = event.getChunk(); throw new RuntimeException("Failed to spawn fox!");
Entity[] entities = chunk.getEntities(); }
for (Entity entity : entities) { spawnedFox.setFoxType(type);
if (entity instanceof Fox && !this.isTamableFox(entity)) {
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType()); sqLiteSetterGetter.saveFox((EntityTamableFox) spawnedFox);
final YamlConfiguration configuration = configFoxes.get();
// if has data return spawnedFox;
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) { }
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner", "none");
private class SaveFoxRunnable extends BukkitRunnable {
// if has owner private final TamableFoxes plugin;
if (!owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner)); SaveFoxRunnable(TamableFoxes plugin) {
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner); this.plugin = plugin;
}
// set name
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) { public void run() {
String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name"); try {
sqLiteSetterGetter.saveFoxes(spawnedFoxes);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.setChosenName(name); getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.GREEN + "Saved all foxes successfully!");
} } catch (Exception e) {
getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.RED + "Failed to save foxes!");
// remove old data }
configuration.set("Foxes." + entity.getUniqueId(), null); }
}
tamableFox.setTamed(true);
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting()); @EventHandler
tamableFox.updateFox(); public void onPlayerJoin(PlayerJoinEvent event) {
tamableFox.setAge(((CraftFox) entity).getAge()); Player player = event.getPlayer();
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) { getFoxesOf(player).forEach(uuid -> {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1))); EntityTamableFox tamableFox = getSpawnedFox(uuid);
} else { tamableFox.setOwner(((CraftPlayer) player).getHandle());
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR)); tamableFox.setTamed(true);
} foxUUIDs.replace(tamableFox.getUniqueID(), player.getUniqueId());
} });
} else { }
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
@EventHandler
tamableFox.setAge(((CraftFox) entity).getAge()); public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand(); Entity entity = event.getRightClicked();
if (entityMouthItem.getType() != Material.AIR) { Player player = event.getPlayer();
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else { if (event.getHand() != EquipmentSlot.HAND)
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR)); return;
}
} final ItemStack playerHand = player.getInventory().getItemInMainHand();
ItemMeta itemMeta = playerHand.getItemMeta();
entity.remove();
} if (itemMeta != null && playerHand.getType() == Material.REDSTONE_TORCH
} && itemMeta.hasLore() && itemMeta.getLore().contains(ITEM_INSPECTOR_LORE)) {
List<String> lore;
}
if (!this.isTamableFox(entity)) {
@EventHandler lore = Arrays.asList(ITEM_INSPECTOR_LORE,
public void onPlayerJoin(PlayerJoinEvent event) { "UUID: " + entity.getUniqueId(),
Player player = event.getPlayer(); "Entity ID: " + entity.getEntityId(),
"Entity type: " + ((CraftEntity) entity).getHandle());
getFoxesOf(player).forEach(uuid -> { } else {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) this.getEntityByUniqueId(uuid)).getHandle(); EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
tamableFox.setOwner(((CraftPlayer) player).getHandle());
tamableFox.setTamed(true); lore = Arrays.asList(ITEM_INSPECTOR_LORE,
foxUUIDs.replace(tamableFox.getUniqueID(), player.getUniqueId()); "UUID: " + entity.getUniqueId(),
}); "Entity ID: " + entity.getEntityId(),
} "Tamable",
"Owner: " + ((tamableFox.getOwner() == null) ? "none" : tamableFox.getOwner().getName()));
@EventHandler }
public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
Entity entity = event.getRightClicked(); // Update item
Player player = event.getPlayer(); itemMeta.setLore(lore);
playerHand.setItemMeta(itemMeta);
if (event.getHand() != EquipmentSlot.HAND) player.getInventory().setItemInMainHand(playerHand);
return;
event.setCancelled(true);
final ItemStack playerHand = player.getInventory().getItemInMainHand(); player.sendMessage(getPrefix() + "Inspected Entity.");
ItemMeta itemMeta = playerHand.getItemMeta(); return;
}
if (itemMeta != null && playerHand.getType() == Material.REDSTONE_TORCH
&& itemMeta.hasLore() && itemMeta.getLore().contains(ITEM_INSPECTOR_LORE)) { if (this.isTamableFox(entity)) {
List<String> lore; EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (!this.isTamableFox(entity)) { if (tamableFox.isTamed() && tamableFox.getOwner() != null &&
lore = Arrays.asList(ITEM_INSPECTOR_LORE, playerHand.getType() != Material.SWEET_BERRIES) {
"UUID: " + entity.getUniqueId(), // if this fox is theirs
"Entity ID: " + entity.getEntityId()); if (foxUUIDs.get(entity.getUniqueId()).equals(player.getUniqueId())) {
} else { if (player.isSneaking()) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle(); net.minecraft.server.v1_15_R1.ItemStack wolfHolding = tamableFox.getEquipment(EnumItemSlot.MAINHAND);
net.minecraft.server.v1_15_R1.ItemStack playerItemInHandNMS;
if (tamableFox.getOwner() == null) { if (wolfHolding.isEmpty()) {
lore = Arrays.asList(ITEM_INSPECTOR_LORE, if (playerHand.getType() == Material.AIR) {
"UUID: " + entity.getUniqueId(), return;
"Entity ID: " + entity.getEntityId(), }
"Tamable",
"Owner: None"); playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
} else { playerItemInHandNMS.setCount(1);
lore = Arrays.asList(ITEM_INSPECTOR_LORE, tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
"UUID: " + entity.getUniqueId(), playerHand.setAmount(playerHand.getAmount() - 1);
"Entity ID: " + entity.getEntityId(), player.getInventory().setItemInMainHand(playerHand);
"Tamable", } else if (playerHand.getType() == Material.AIR) {
"Owner: " + tamableFox.getOwner().getName()); entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
} CraftItemStack.asBukkitCopy(wolfHolding));
} tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} else {
// update item playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
itemMeta.setLore(lore); entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
playerHand.setItemMeta(itemMeta); CraftItemStack.asBukkitCopy(wolfHolding));
player.getInventory().setItemInMainHand(playerHand); playerItemInHandNMS.setCount(1);
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
event.setCancelled(true); playerHand.setAmount(playerHand.getAmount() - 1);
player.sendMessage(getPrefix() + "Inspected Entity."); player.getInventory().setItemInMainHand(playerHand);
return; }
} } else if (playerHand.getType() == Material.NAME_TAG) {
ItemMeta handMeta = playerHand.getItemMeta();
if (this.isTamableFox(entity)) { tamableFox.setChosenName(handMeta.getDisplayName());
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle(); } else {
tamableFox.toggleSitting();
if (tamableFox.isTamed() && tamableFox.getOwner() != null && }
playerHand.getType() != Material.SWEET_BERRIES) {
// if this fox is theirs event.setCancelled(true);
if (foxUUIDs.get(entity.getUniqueId()).equals(player.getUniqueId())) { }
if (player.isSneaking()) { } else if (playerHand.getType() == Material.CHICKEN) {
net.minecraft.server.v1_15_R1.ItemStack wolfHolding = tamableFox.getEquipment(EnumItemSlot.MAINHAND); if (Math.random() < 0.33D) {
net.minecraft.server.v1_15_R1.ItemStack playerItemInHandNMS; tamableFox.setTamed(true);
if (wolfHolding.isEmpty()) { tamableFox.setOwner(((CraftPlayer) player).getHandle());
if (playerHand.getType() == Material.AIR) { foxUUIDs.replace(tamableFox.getUniqueID(), null, player.getUniqueId());
return; player.getWorld().spawnParticle(Particle.HEART, entity.getLocation(), 6, 0.5D, 0.5D, 0.5D);
}
// Name process
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand); player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "You just tamed a wild fox!");
playerItemInHandNMS.setCount(1); player.sendMessage(ChatColor.RED + "What do you want to call it?");
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS); tamableFox.setChosenName("???");
playerHand.setAmount(playerHand.getAmount() - 1);
player.getInventory().setItemInMainHand(playerHand); event.setCancelled(true);
} else if (playerHand.getType() == Material.AIR) { new AnvilGUI.Builder()
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D), .onComplete((plr, text) -> { // Called when the inventory output slot is clicked
CraftItemStack.asBukkitCopy(wolfHolding)); if(!text.equals("")) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR)); tamableFox.setChosenName(text);
} else { plr.sendMessage(getPrefix() + ChatColor.GREEN + text + " is perfect!");
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand); }
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
CraftItemStack.asBukkitCopy(wolfHolding)); return AnvilGUI.Response.close();
playerItemInHandNMS.setCount(1); })
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS); //.preventClose() // Prevents the inventory from being closed
playerHand.setAmount(playerHand.getAmount() - 1); .text("Fox name") // Sets the text the GUI should start with
player.getInventory().setItemInMainHand(playerHand); .plugin(this) // Set the plugin instance
} .open(player); // Opens the GUI for the player provided
} else if (playerHand.getType() == Material.NAME_TAG) {
ItemMeta handMeta = playerHand.getItemMeta(); } else { // Failed to tame
tamableFox.setChosenName(handMeta.getDisplayName()); player.getWorld().spawnParticle(Particle.SMOKE_NORMAL, entity.getLocation(), 10, 0.3D, 0.3D, 0.3D, 0.15D);
} else { }
tamableFox.toggleSitting();
} if (!player.getGameMode().equals(GameMode.CREATIVE)) {
playerHand.setAmount(playerHand.getAmount() - 1);
event.setCancelled(true); }
}
} else if (playerHand.getType() == Material.CHICKEN) { event.setCancelled(true);
if (Math.random() < 0.33D) { }
tamableFox.setTamed(true); }
tamableFox.setOwner(((CraftPlayer) player).getHandle()); }
foxUUIDs.replace(tamableFox.getUniqueID(), null, player.getUniqueId());
player.getWorld().spawnParticle(Particle.HEART, entity.getLocation(), 6, 0.5D, 0.5D, 0.5D); @EventHandler
public void onPlayerBedEnterEvent(PlayerBedEnterEvent event) {
// Name process Player player = event.getPlayer();
player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "You just tamed a wild fox!");
player.sendMessage(ChatColor.RED + "What do you want to call it?"); getFoxesOf(player).forEach(uuid -> {
tamableFox.setChosenName("???"); EntityTamableFox tamableFox = getSpawnedFox(uuid);
if (player.getWorld().getTime() > 12541L && player.getWorld().getTime() < 23460L) {
new AnvilGUI.Builder() tamableFox.setSleeping(true);
.onComplete((plr, text) -> { // Called when the inventory output slot is clicked } else return; // Stop the loop, no point of iterating through all the foxes if the condition will be the same.
if(!text.equals("")) { });
tamableFox.setChosenName(text); }
plr.sendMessage(getPrefix() + ChatColor.GREEN + text + " is perfect!");
return AnvilGUI.Response.close(); @EventHandler
} else { public void onPlayerBedLeaveEvent(PlayerBedLeaveEvent event) {
return AnvilGUI.Response.text("Insert a name for your fox!"); Player player = event.getPlayer();
}
}) getFoxesOf(player).forEach(uuid -> {
.preventClose() // Prevents the inventory from being closed EntityTamableFox tamableFox = getSpawnedFox(uuid);
.text("Fox name") // Sets the text the GUI should start with tamableFox.setSleeping(false);
.plugin(this) // Set the plugin instance });
.open(player); // Opens the GUI for the player provided }
} else { @EventHandler
player.getWorld().spawnParticle(Particle.SMOKE_NORMAL, entity.getLocation(), 10, 0.3D, 0.3D, 0.3D, 0.15D); public void onCreatureSpawnEvent(CreatureSpawnEvent event) {
} org.bukkit.entity.Entity entity = event.getEntity();
if (entity instanceof Fox && !this.isTamableFox(entity)) {
if (!player.getGameMode().equals(GameMode.CREATIVE)) { net.minecraft.server.v1_15_R1.EntityFox.Type foxType = ((EntityFox) ((CraftEntity) entity).getHandle()).getFoxType();
playerHand.setAmount(playerHand.getAmount() - 1); spawnTamableFox(entity.getLocation(), foxType);
} event.setCancelled(true);
}
event.setCancelled(true); }
}
} @EventHandler
} public void onEntityDeathEvent(EntityDeathEvent event) {
Entity entity = event.getEntity();
@EventHandler if (!this.isTamableFox(entity)) return; // Is the entity a tamable fox?
public void onPlayerBedEnterEvent(PlayerBedEnterEvent event) {
Player player = event.getPlayer(); // Remove the fox from storage
List<UUID> dogsToSleep = getFoxesOf(player); lookupCache.remove(entity.getUniqueId());
foxUUIDs.remove(entity.getUniqueId());
for (UUID uuid : dogsToSleep) { spawnedFoxes.remove(entity.getUniqueId());
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle();
if (player.getWorld().getTime() > 12541L && player.getWorld().getTime() < 23460L) { // Notify the owner
tamableFox.setSleeping(true); EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
} if (tamableFox.getOwner() != null) {
} Player owner = ((EntityPlayer)tamableFox.getOwner()).getBukkitEntity();
owner.sendMessage(getPrefix() + ChatColor.RED + tamableFox.getChosenName() + " was killed!");
} }
@EventHandler // Remove the fox from database
public void onPlayerBedLeaveEvent(PlayerBedLeaveEvent event) { sqLiteSetterGetter.removeFox(tamableFox);
Player player = event.getPlayer(); }
final List<UUID> foxesOf = getFoxesOf(player);
public EntityTamableFox getSpawnedFox(UUID uniqueId) {
for (UUID uuid : foxesOf) { for (EntityTamableFox fox : spawnedFoxes) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle(); if (fox.getUniqueID() == uniqueId) {
tamableFox.setSleeping(false); return fox;
} }
}
}
return null;
@EventHandler }
public void onCreatureSpawnEvent(CreatureSpawnEvent event) {
org.bukkit.entity.Entity entity = event.getEntity(); public boolean isTamableFox(org.bukkit.entity.Entity entity) {
if (entity instanceof Fox && !this.isTamableFox(entity)) { return ((CraftEntity) entity).getHandle().getClass().getName().contains("TamableFox") || ((CraftEntity) entity).getHandle() instanceof EntityTamableFox;
net.minecraft.server.v1_15_R1.EntityFox.Type foxType = ((EntityFox) ((CraftEntity) entity).getHandle()).getFoxType(); }
spawnTamableFox(entity.getLocation(), foxType);
event.setCancelled(true); public List<UUID> getFoxesOf(Player player) {
} return foxUUIDs.entrySet().stream().filter(foxPlayer -> foxPlayer.getValue() != null && foxPlayer.getValue().equals(player.getUniqueId())).map(Map.Entry::getKey).collect(Collectors.toList());
}
}
public FileManager getFileManager() {
public Entity getEntityByUniqueId(UUID uniqueId) { return fileManager;
final Entity cacheEntity = lookupCache.get(uniqueId); }
if (cacheEntity != null) {
if (cacheEntity.isDead()) public FileManager.Config getMainConfig() {
lookupCache.remove(uniqueId); return config;
else return cacheEntity; }
}
public EntityTypes getCustomType() {
for (World world : Bukkit.getWorlds()) { return customType;
for (Chunk loadedChunk : world.getLoadedChunks()) { }
for (Entity entity : loadedChunk.getEntities()) {
if (entity.getUniqueId().equals(uniqueId)) { public Map<UUID, UUID> getFoxUUIDs() {
this.lookupCache.put(uniqueId, entity); return foxUUIDs;
return entity; }
}
} public List<EntityTamableFox> getSpawnedFoxes() {
} return spawnedFoxes;
} }
return null; public static String getPrefix() {
} //return ChatColor.translateAlternateColorCodes('&', (String) config.get("prefix"));
return ChatColor.RED + "[Tamable Foxes] ";
@EventHandler }
public void onEntityDeathEvent(EntityDeathEvent event) {
Entity entity = event.getEntity(); public boolean isShowOwnerFoxName() {
if (!this.isTamableFox(entity)) return (boolean) config.get("show-owner-in-fox-name");
return; }
this.lookupCache.remove(entity.getUniqueId());
foxUUIDs.remove(entity.getUniqueId()); public boolean isShowNameTags() {
return (boolean) config.get("show-nametags");
if (configFoxes.get().getConfigurationSection("Foxes").contains(entity.getUniqueId().toString())) { }
/*EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() != null && tamableFox.getOwner() instanceof Player) { public boolean isTamedAttackRabbitChicken() {
Player owner = (Player) tamableFox.getOwner(); return (boolean) config.get("tamed-behavior.attack-chicken-rabbit");
owner.sendMessage(getPrefix() + ChatColor.RED + tamableFox.getChosenName() + " was killed!"); }
}*/
}
configFoxes.get().set("Foxes." + entity.getUniqueId(), null);
fileManager.saveConfig("foxes.yml");
}
}
public boolean isTamableFox(org.bukkit.entity.Entity entity) {
return ((CraftEntity) entity).getHandle().getClass().getName().contains("TamableFox")
|| ((CraftEntity) entity).getHandle() instanceof EntityTamableFox;
}
public List<UUID> getFoxesOf(Player player) {
return foxUUIDs.entrySet().stream().filter(foxPlayer -> foxPlayer.getValue() != null && foxPlayer.getValue().equals(player.getUniqueId()))
.map(Map.Entry::getKey).collect(Collectors.toList());
}
public FileManager getFileManager() {
return fileManager;
}
public FileManager.Config getMainConfig() {
return config;
}
public FileManager.Config getConfigFoxes() {
return configFoxes;
}
public EntityTypes getCustomType() {
return customType;
}
public Map<UUID, UUID> getFoxUUIDs() {
return foxUUIDs;
}
public static String getPrefix() {
//return ChatColor.translateAlternateColorCodes('&', (String) config.get("prefix"));
return ChatColor.RED + "[Tamable Foxes] ";
}
public boolean isShowOwnerFoxName() {
return (boolean) config.get("show-owner-in-fox-name");
}
public boolean isShowNameTags() {
return (boolean) config.get("show-nametags");
}
public boolean isTamedAttackRabbitChicken() {
return (boolean) config.get("tamed-behavior.no-attack-chicken-rabbit");
}
}

View File

@ -1,546 +0,0 @@
package net.seanomik.tamablefoxes;
import com.google.common.collect.Maps;
import com.mojang.datafixers.DataFixUtils;
import com.mojang.datafixers.types.Type;
import net.seanomik.tamablefoxes.command.CommandSpawnTamableFox;
import net.seanomik.tamablefoxes.io.FileManager;
import net.minecraft.server.v1_15_R1.*;
import net.seanomik.tamablefoxes.sqlite.SQLiteHandler;
import net.seanomik.tamablefoxes.sqlite.SQLiteSetterGetter;
import net.wesjd.anvilgui.AnvilGUI;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftFox;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fox;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
// @TODO: Add language.yml
public class TamableFoxes extends JavaPlugin implements Listener {
public static final String ITEM_INSPECTOR_LORE = ChatColor.BLUE + "Tamable Fox Inspector";
public static final String TAG_TAME_FOX = "tameablefox";
private FileManager fileManager = new FileManager(this);
private Map<UUID, UUID> foxUUIDs = Maps.newHashMap(); // FoxUUID, OwnerUUID
private EntityTypes customType;
private boolean isOnLoad = true;
private Map<UUID, Entity> lookupCache = Maps.newHashMap();
private List<EntityTamableFox> spawnedFoxes;
private FileManager.Config config;//, configFoxes;
public static SQLiteHandler sqLiteHandler = new SQLiteHandler();
public static SQLiteSetterGetter sqLiteSetterGetter = new SQLiteSetterGetter();
@Override
public void onEnable() {
String version = Bukkit.getServer().getClass().getPackage().getName();
if (!version.equals("org.bukkit.craftbukkit.v1_15_R1")) {
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "This plugin version only supports 1.15.1!");
getServer().getPluginManager().disablePlugin(this);
return;
}
sqLiteHandler.connect();
sqLiteSetterGetter.createTablesIfNotExist();
this.config = fileManager.getConfig("config.yml");
this.config.copyDefaults(true).save();
/*this.configFoxes = fileManager.getConfig("foxes.yml");
this.configFoxes.copyDefaults(true).save();*/
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("spawntamablefox").setExecutor(new CommandSpawnTamableFox(this));
final Map<String, Type<?>> types = (Map<String, Type<?>>) DataConverterRegistry.a()
.getSchema(DataFixUtils.makeKey(SharedConstants.getGameVersion().getWorldVersion()))
.findChoiceType(DataConverterTypes.ENTITY).types();
types.put("minecraft:" + TAG_TAME_FOX, types.get("minecraft:fox"));
EntityTypes.a<net.minecraft.server.v1_15_R1.Entity> a = EntityTypes.a.a((entityTypes, world) ->
new EntityTamableFox(this, entityTypes, world), EnumCreatureType.AMBIENT);
customType = IRegistry.a(IRegistry.ENTITY_TYPE, "tameablefox", a.a("tameablefox"));
this.replaceFoxesOnLoad();
}
@Override
public void onDisable() {
try {
for (EntityTamableFox fox : spawnedFoxes) {
sqLiteSetterGetter.saveFox(fox);
fox.getBukkitEntity().remove();
}
getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.GREEN + "Saved all foxes successfully!");
} catch (Exception e) {
getServer().getConsoleSender().sendMessage(getPrefix() + ChatColor.RED + "Failed to save foxes!");
}
}
private void replaceFoxesOnLoad() {
/*int amountReplaced = 0;
for (World world : Bukkit.getWorlds()) {
Chunk[] loadedChunks = world.getLoadedChunks();
for (Chunk chunk : loadedChunks) {
Entity[] entities = chunk.getEntities();
for (Entity entity : entities) {
if (!(entity instanceof Fox))
continue;
if (this.isTamableFox(entity))
continue;
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType());
//final YamlConfiguration configuration = configFoxes.get();
// get living entity data
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) {
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner");
// make new data
if (owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), null);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
} else {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner));
tamableFox.setTamed(true);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner);
}
// set name
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) {
final String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name");
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.setChosenName(name);
}
// delete old data
configuration.set("Foxes." + entity.getUniqueId(), null);
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting());
tamableFox.updateFox();
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
entityMouthItem.setAmount(1);
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(entityMouthItem));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
} else {
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
entityMouthItem.setAmount(1);
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(entityMouthItem));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
entity.remove();
++amountReplaced;
}
}
}
configFoxes.save();*/
spawnedFoxes = sqLiteSetterGetter.spawnFoxes();
this.isOnLoad = false;
}
public net.minecraft.server.v1_15_R1.Entity spawnTamableFox(Location location, net.minecraft.server.v1_15_R1.EntityFox.Type type) {
WorldServer world = ((CraftWorld) location.getWorld()).getHandle();
net.minecraft.server.v1_15_R1.Entity spawnedEntity = customType.b(world, null, null, null,
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
world.addEntity(spawnedEntity);
EntityFox fox = (EntityFox) spawnedEntity;
fox.setFoxType(type);
/*configFoxes.get().set("Foxes." + spawnedEntity.getUniqueID() + ".owner", "none");
fileManager.saveConfig("foxes.yml");*/
return fox;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
/*if (isOnLoad)
return;
Chunk chunk = event.getChunk();
Entity[] entities = chunk.getEntities();
for (Entity entity : entities) {
if (entity instanceof Fox && !this.isTamableFox(entity)) {
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType());
final YamlConfiguration configuration = configFoxes.get();
// if has data
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) {
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner", "none");
// if has owner
if (!owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner));
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner);
// set name
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) {
String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name");
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.setChosenName(name);
}
// remove old data
configuration.set("Foxes." + entity.getUniqueId(), null);
tamableFox.setTamed(true);
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting());
tamableFox.updateFox();
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
} else {
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
entity.remove();
}
}*/
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
getFoxesOf(player).forEach(uuid -> {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) this.getEntityByUniqueId(uuid)).getHandle();
tamableFox.setOwner(((CraftPlayer) player).getHandle());
tamableFox.setTamed(true);
foxUUIDs.replace(tamableFox.getUniqueID(), player.getUniqueId());
});
}
@EventHandler
public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
Entity entity = event.getRightClicked();
Player player = event.getPlayer();
if (event.getHand() != EquipmentSlot.HAND)
return;
final ItemStack playerHand = player.getInventory().getItemInMainHand();
ItemMeta itemMeta = playerHand.getItemMeta();
if (itemMeta != null && playerHand.getType() == Material.REDSTONE_TORCH
&& itemMeta.hasLore() && itemMeta.getLore().contains(ITEM_INSPECTOR_LORE)) {
List<String> lore;
if (!this.isTamableFox(entity)) {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId());
} else {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() == null) {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId(),
"Tamable",
"Owner: None");
} else {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId(),
"Tamable",
"Owner: " + tamableFox.getOwner().getName());
}
}
// update item
itemMeta.setLore(lore);
playerHand.setItemMeta(itemMeta);
player.getInventory().setItemInMainHand(playerHand);
event.setCancelled(true);
player.sendMessage(getPrefix() + "Inspected Entity.");
return;
}
if (this.isTamableFox(entity)) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.isTamed() && tamableFox.getOwner() != null &&
playerHand.getType() != Material.SWEET_BERRIES) {
// if this fox is theirs
if (foxUUIDs.get(entity.getUniqueId()).equals(player.getUniqueId())) {
if (player.isSneaking()) {
net.minecraft.server.v1_15_R1.ItemStack wolfHolding = tamableFox.getEquipment(EnumItemSlot.MAINHAND);
net.minecraft.server.v1_15_R1.ItemStack playerItemInHandNMS;
if (wolfHolding.isEmpty()) {
if (playerHand.getType() == Material.AIR) {
return;
}
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
playerItemInHandNMS.setCount(1);
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
playerHand.setAmount(playerHand.getAmount() - 1);
player.getInventory().setItemInMainHand(playerHand);
} else if (playerHand.getType() == Material.AIR) {
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
CraftItemStack.asBukkitCopy(wolfHolding));
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} else {
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
CraftItemStack.asBukkitCopy(wolfHolding));
playerItemInHandNMS.setCount(1);
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
playerHand.setAmount(playerHand.getAmount() - 1);
player.getInventory().setItemInMainHand(playerHand);
}
} else if (playerHand.getType() == Material.NAME_TAG) {
ItemMeta handMeta = playerHand.getItemMeta();
tamableFox.setChosenName(handMeta.getDisplayName());
} else {
tamableFox.toggleSitting();
}
event.setCancelled(true);
}
} else if (playerHand.getType() == Material.CHICKEN) {
if (Math.random() < 0.33D) {
tamableFox.setTamed(true);
tamableFox.setOwner(((CraftPlayer) player).getHandle());
foxUUIDs.replace(tamableFox.getUniqueID(), null, player.getUniqueId());
player.getWorld().spawnParticle(Particle.HEART, entity.getLocation(), 6, 0.5D, 0.5D, 0.5D);
// Name process
player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "You just tamed a wild fox!");
player.sendMessage(ChatColor.RED + "What do you want to call it?");
tamableFox.setChosenName("???");
new AnvilGUI.Builder()
.onComplete((plr, text) -> { // Called when the inventory output slot is clicked
if(!text.equals("")) {
tamableFox.setChosenName(text);
plr.sendMessage(getPrefix() + ChatColor.GREEN + text + " is perfect!");
}
return AnvilGUI.Response.close();
})
//.preventClose() // Prevents the inventory from being closed
.text("Fox name") // Sets the text the GUI should start with
.plugin(this) // Set the plugin instance
.open(player); // Opens the GUI for the player provided
} else {
player.getWorld().spawnParticle(Particle.SMOKE_NORMAL, entity.getLocation(), 10, 0.3D, 0.3D, 0.3D, 0.15D);
}
if (!player.getGameMode().equals(GameMode.CREATIVE)) {
playerHand.setAmount(playerHand.getAmount() - 1);
}
event.setCancelled(true);
}
}
}
@EventHandler
public void onPlayerBedEnterEvent(PlayerBedEnterEvent event) {
Player player = event.getPlayer();
List<UUID> dogsToSleep = getFoxesOf(player);
for (UUID uuid : dogsToSleep) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle();
if (player.getWorld().getTime() > 12541L && player.getWorld().getTime() < 23460L) {
tamableFox.setSleeping(true);
}
}
}
@EventHandler
public void onPlayerBedLeaveEvent(PlayerBedLeaveEvent event) {
Player player = event.getPlayer();
final List<UUID> foxesOf = getFoxesOf(player);
for (UUID uuid : foxesOf) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle();
tamableFox.setSleeping(false);
}
}
@EventHandler
public void onCreatureSpawnEvent(CreatureSpawnEvent event) {
org.bukkit.entity.Entity entity = event.getEntity();
if (entity instanceof Fox && !this.isTamableFox(entity)) {
net.minecraft.server.v1_15_R1.EntityFox.Type foxType = ((EntityFox) ((CraftEntity) entity).getHandle()).getFoxType();
spawnTamableFox(entity.getLocation(), foxType);
event.setCancelled(true);
}
}
@EventHandler
public void onEntityDeathEvent(EntityDeathEvent event) {
Entity entity = event.getEntity();
if (!this.isTamableFox(entity)) {
return;
}
// Remove the fox from storage
lookupCache.remove(entity.getUniqueId());
foxUUIDs.remove(entity.getUniqueId());
spawnedFoxes.remove(entity.getUniqueId());
//sqLiteSetterGetter.removeFox();
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() != null) {
Player owner = ((EntityPlayer)tamableFox.getOwner()).getBukkitEntity();
owner.sendMessage(getPrefix() + ChatColor.RED + tamableFox.getChosenName() + " was killed!");
}
sqLiteSetterGetter.removeFox(tamableFox);
/*if (configFoxes.get().getConfigurationSection("Foxes").contains(entity.getUniqueId().toString())) {
*//*EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() != null && tamableFox.getOwner() instanceof Player) {
Player owner = (Player) tamableFox.getOwner();
owner.sendMessage(getPrefix() + ChatColor.RED + tamableFox.getChosenName() + " was killed!");
}*//*
configFoxes.get().set("Foxes." + entity.getUniqueId(), null);
fileManager.saveConfig("foxes.yml");
}*/
}
public Entity getEntityByUniqueId(UUID uniqueId) {
final Entity cacheEntity = lookupCache.get(uniqueId);
if (cacheEntity != null) {
if (cacheEntity.isDead())
lookupCache.remove(uniqueId);
else return cacheEntity;
}
for (World world : Bukkit.getWorlds()) {
for (Chunk loadedChunk : world.getLoadedChunks()) {
for (Entity entity : loadedChunk.getEntities()) {
if (entity.getUniqueId().equals(uniqueId)) {
this.lookupCache.put(uniqueId, entity);
return entity;
}
}
}
}
return null;
}
public boolean isTamableFox(org.bukkit.entity.Entity entity) {
return ((CraftEntity) entity).getHandle().getClass().getName().contains("TamableFox")
|| ((CraftEntity) entity).getHandle() instanceof EntityTamableFox;
}
public List<UUID> getFoxesOf(Player player) {
return foxUUIDs.entrySet().stream().filter(foxPlayer -> foxPlayer.getValue() != null && foxPlayer.getValue().equals(player.getUniqueId()))
.map(Map.Entry::getKey).collect(Collectors.toList());
}
public FileManager getFileManager() {
return fileManager;
}
public FileManager.Config getMainConfig() {
return config;
}
/*public FileManager.Config getConfigFoxes() {
return configFoxes;
}*/
public EntityTypes getCustomType() {
return customType;
}
public Map<UUID, UUID> getFoxUUIDs() {
return foxUUIDs;
}
public List<EntityTamableFox> getSpawnedFoxes() {
return spawnedFoxes;
}
public static String getPrefix() {
//return ChatColor.translateAlternateColorCodes('&', (String) config.get("prefix"));
return ChatColor.RED + "[Tamable Foxes] ";
}
public boolean isShowOwnerFoxName() {
return (boolean) config.get("show-owner-in-fox-name");
}
public boolean isShowNameTags() {
return (boolean) config.get("show-nametags");
}
public boolean isTamedAttackRabbitChicken() {
return (boolean) config.get("tamed-behavior.no-attack-chicken-rabbit");
}
}

View File

@ -1,515 +0,0 @@
package net.seanomilk.tamablefoxes;
import com.google.common.collect.Maps;
import com.mojang.datafixers.DataFixUtils;
import com.mojang.datafixers.types.Type;
import net.seanomilk.tamablefoxes.command.CommandSpawnTamableFox;
import net.seanomilk.tamablefoxes.io.FileManager;
import net.minecraft.server.v1_15_R1.*;
import net.wesjd.anvilgui.AnvilGUI;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftFox;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftItem;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fox;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class TamableFoxes extends JavaPlugin implements Listener {
public static final String ITEM_INSPECTOR_LORE = ChatColor.BLUE + "Tamable Fox Inspector";
public static final String TAG_TAME_FOX = "tameablefox";
private FileManager fileManager;
private Map<UUID, UUID> foxUUIDs;
private EntityTypes customType;
private boolean isOnLoad = true;
private Map<UUID, Entity> lookupCache;
private FileManager.Config config, configFoxes;
private Map<Player, UUID> waitingName;
@Override
public void onEnable() {
String version = Bukkit.getServer().getClass().getPackage().getName();
if (!version.equals("org.bukkit.craftbukkit.v1_15_R1")) {
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "This plugin version only supports 1.15.1!");
getServer().getPluginManager().disablePlugin(this);
return;
}
fileManager = new FileManager(this);
this.config = fileManager.getConfig("config.yml");
this.config.copyDefaults(true).save();
this.configFoxes = fileManager.getConfig("foxes.yml");
this.configFoxes.copyDefaults(true).save();
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("spawntamablefox").setExecutor(new CommandSpawnTamableFox(this));
this.foxUUIDs = Maps.newHashMap();
this.lookupCache = Maps.newHashMap();
this.waitingName = Maps.newHashMap();
final Map<String, Type<?>> types = (Map<String, Type<?>>) DataConverterRegistry.a()
.getSchema(DataFixUtils.makeKey(SharedConstants.getGameVersion().getWorldVersion()))
.findChoiceType(DataConverterTypes.ENTITY).types();
types.put("minecraft:" + TAG_TAME_FOX, types.get("minecraft:fox"));
EntityTypes.a<net.minecraft.server.v1_15_R1.Entity> a = EntityTypes.a.a((entityTypes, world) ->
new EntityTamableFox(this, entityTypes, world), EnumCreatureType.AMBIENT);
customType = IRegistry.a(IRegistry.ENTITY_TYPE, "tameablefox", a.a("tameablefox"));
this.replaceFoxesOnLoad();
}
@Override
public void onDisable() {
}
private void replaceFoxesOnLoad() {
int amountReplaced = 0;
for (World world : Bukkit.getWorlds()) {
Chunk[] loadedChunks = world.getLoadedChunks();
for (Chunk chunk : loadedChunks) {
Entity[] entities = chunk.getEntities();
for (Entity entity : entities) {
if (!(entity instanceof Fox))
continue;
if (this.isTamableFox(entity))
continue;
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType());
final YamlConfiguration configuration = configFoxes.get();
// get living entity data
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) {
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner");
// make new data
if (owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), null);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
} else {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner));
tamableFox.setTamed(true);
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner);
}
// set name
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) {
final String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name");
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.setChosenName(name);
}
// delete old data
configuration.set("Foxes." + entity.getUniqueId(), null);
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting());
tamableFox.updateFox();
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
} else {
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
entity.remove();
++amountReplaced;
}
}
}
configFoxes.save();
this.isOnLoad = false;
}
public net.minecraft.server.v1_15_R1.Entity spawnTamableFox(Location location, net.minecraft.server.v1_15_R1.EntityFox.Type type) {
WorldServer world = ((CraftWorld) location.getWorld()).getHandle();
net.minecraft.server.v1_15_R1.Entity spawnedEntity = customType.b(world, null, null, null,
new BlockPosition(location.getX(), location.getY(), location.getZ()), null, false, false);
world.addEntity(spawnedEntity);
EntityFox fox = (EntityFox) spawnedEntity;
fox.setFoxType(type);
configFoxes.get().set("Foxes." + spawnedEntity.getUniqueID() + ".owner", "none");
fileManager.saveConfig("foxes.yml");
return fox;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
if (isOnLoad)
return;
Chunk chunk = event.getChunk();
Entity[] entities = chunk.getEntities();
for (Entity entity : entities) {
if (entity instanceof Fox && !this.isTamableFox(entity)) {
EntityTamableFox tamableFox = (EntityTamableFox) spawnTamableFox(entity.getLocation(), ((CraftFox) entity).getHandle().getFoxType());
final YamlConfiguration configuration = configFoxes.get();
// if has data
if (configuration.isConfigurationSection("Foxes." + entity.getUniqueId())) {
String owner = configuration.getString("Foxes." + entity.getUniqueId() + ".owner", "none");
// if has owner
if (!owner.equals("none")) {
foxUUIDs.replace(tamableFox.getUniqueID(), UUID.fromString(owner));
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", owner);
// set name
if (configuration.isSet("Foxes." + entity.getUniqueId() + ".name")) {
String name = configuration.getString("Foxes." + entity.getUniqueId() + ".name");
configuration.set("Foxes." + tamableFox.getUniqueID() + ".name", name);
tamableFox.setChosenName(name);
}
// remove old data
configuration.set("Foxes." + entity.getUniqueId(), null);
tamableFox.setTamed(true);
tamableFox.setSitting(((EntityFox) ((CraftEntity) entity).getHandle()).isSitting());
tamableFox.updateFox();
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
} else {
configuration.set("Foxes." + tamableFox.getUniqueID() + ".owner", "none");
tamableFox.setAge(((CraftFox) entity).getAge());
ItemStack entityMouthItem = ((CraftFox) entity).getEquipment().getItemInMainHand();
if (entityMouthItem.getType() != Material.AIR) {
tamableFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(entityMouthItem.getType(), 1)));
} else {
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
}
}
entity.remove();
}
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
getFoxesOf(player).forEach(uuid -> {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) this.getEntityByUniqueId(uuid)).getHandle();
tamableFox.setOwner(((CraftPlayer) player).getHandle());
tamableFox.setTamed(true);
foxUUIDs.replace(tamableFox.getUniqueID(), player.getUniqueId());
});
}
@EventHandler
public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
Entity entity = event.getRightClicked();
Player player = event.getPlayer();
if (event.getHand() != EquipmentSlot.HAND)
return;
final ItemStack playerHand = player.getInventory().getItemInMainHand();
ItemMeta itemMeta = playerHand.getItemMeta();
if (itemMeta != null && playerHand.getType() == Material.REDSTONE_TORCH
&& itemMeta.hasLore() && itemMeta.getLore().contains(ITEM_INSPECTOR_LORE)) {
List<String> lore;
if (!this.isTamableFox(entity)) {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId());
} else {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() == null) {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId(),
"Tamable",
"Owner: None");
} else {
lore = Arrays.asList(ITEM_INSPECTOR_LORE,
"UUID: " + entity.getUniqueId(),
"Entity ID: " + entity.getEntityId(),
"Tamable",
"Owner: " + tamableFox.getOwner().getName());
}
}
// update item
itemMeta.setLore(lore);
playerHand.setItemMeta(itemMeta);
player.getInventory().setItemInMainHand(playerHand);
event.setCancelled(true);
player.sendMessage(getPrefix() + "Inspected Entity.");
return;
}
if (this.isTamableFox(entity)) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.isTamed() && tamableFox.getOwner() != null &&
playerHand.getType() != Material.SWEET_BERRIES) {
// if this fox is theirs
if (foxUUIDs.get(entity.getUniqueId()).equals(player.getUniqueId())) {
if (player.isSneaking()) {
net.minecraft.server.v1_15_R1.ItemStack wolfHolding = tamableFox.getEquipment(EnumItemSlot.MAINHAND);
net.minecraft.server.v1_15_R1.ItemStack playerItemInHandNMS;
if (wolfHolding.isEmpty()) {
if (playerHand.getType() == Material.AIR) {
return;
}
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
playerItemInHandNMS.setCount(1);
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
playerHand.setAmount(playerHand.getAmount() - 1);
player.getInventory().setItemInMainHand(playerHand);
} else if (playerHand.getType() == Material.AIR) {
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
CraftItemStack.asBukkitCopy(wolfHolding));
tamableFox.setSlot(EnumItemSlot.MAINHAND, new net.minecraft.server.v1_15_R1.ItemStack(Items.AIR));
} else {
playerItemInHandNMS = CraftItemStack.asNMSCopy(playerHand);
entity.getWorld().dropItem(tamableFox.getBukkitEntity().getLocation().add(0.0D, 0.2D, 0.0D),
CraftItemStack.asBukkitCopy(wolfHolding));
playerItemInHandNMS.setCount(1);
tamableFox.setSlot(EnumItemSlot.MAINHAND, playerItemInHandNMS);
playerHand.setAmount(playerHand.getAmount() - 1);
player.getInventory().setItemInMainHand(playerHand);
}
} else if (playerHand.getType() == Material.NAME_TAG) {
ItemMeta handMeta = playerHand.getItemMeta();
tamableFox.setChosenName(handMeta.getDisplayName());
} else {
tamableFox.toggleSitting();
}
event.setCancelled(true);
}
} else if (playerHand.getType() == Material.CHICKEN) {
if (Math.random() < 0.33D) {
tamableFox.setTamed(true);
tamableFox.setOwner(((CraftPlayer) player).getHandle());
foxUUIDs.replace(tamableFox.getUniqueID(), null, player.getUniqueId());
player.getWorld().spawnParticle(Particle.HEART, entity.getLocation(), 6, 0.5D, 0.5D, 0.5D);
// Name process
player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "You just tamed a wild fox!");
player.sendMessage(ChatColor.RED + "What do you want to call it?");
tamableFox.setChosenName("???");
new AnvilGUI.Builder()
.onComplete((plr, text) -> { // Called when the inventory output slot is clicked
if(!text.equals("")) {
tamableFox.setChosenName(text);
plr.sendMessage(getPrefix() + ChatColor.GREEN + text + " is perfect!");
return AnvilGUI.Response.close();
} else {
return AnvilGUI.Response.text("Insert a name for your fox!");
}
})
.preventClose() // Prevents the inventory from being closed
.text("Fox name") // Sets the text the GUI should start with
.plugin(this) // Set the plugin instance
.open(player); // Opens the GUI for the player provided
} else {
player.getWorld().spawnParticle(Particle.SMOKE_NORMAL, entity.getLocation(), 10, 0.3D, 0.3D, 0.3D, 0.15D);
}
if (!player.getGameMode().equals(GameMode.CREATIVE)) {
playerHand.setAmount(playerHand.getAmount() - 1);
}
event.setCancelled(true);
}
}
}
@EventHandler
public void onPlayerBedEnterEvent(PlayerBedEnterEvent event) {
Player player = event.getPlayer();
List<UUID> dogsToSleep = getFoxesOf(player);
for (UUID uuid : dogsToSleep) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle();
if (player.getWorld().getTime() > 12541L && player.getWorld().getTime() < 23460L) {
tamableFox.setSleeping(true);
}
}
}
@EventHandler
public void onPlayerBedLeaveEvent(PlayerBedLeaveEvent event) {
Player player = event.getPlayer();
final List<UUID> foxesOf = getFoxesOf(player);
for (UUID uuid : foxesOf) {
EntityTamableFox tamableFox = (EntityTamableFox) ((CraftFox) this.getEntityByUniqueId(uuid)).getHandle();
tamableFox.setSleeping(false);
}
}
@EventHandler
public void onCreatureSpawnEvent(CreatureSpawnEvent event) {
org.bukkit.entity.Entity entity = event.getEntity();
if (entity instanceof Fox && !this.isTamableFox(entity)) {
net.minecraft.server.v1_15_R1.EntityFox.Type foxType = ((EntityFox) ((CraftEntity) entity).getHandle()).getFoxType();
spawnTamableFox(entity.getLocation(), foxType);
event.setCancelled(true);
}
}
public Entity getEntityByUniqueId(UUID uniqueId) {
final Entity cacheEntity = lookupCache.get(uniqueId);
if (cacheEntity != null) {
if (cacheEntity.isDead())
lookupCache.remove(uniqueId);
else return cacheEntity;
}
for (World world : Bukkit.getWorlds()) {
for (Chunk loadedChunk : world.getLoadedChunks()) {
for (Entity entity : loadedChunk.getEntities()) {
if (entity.getUniqueId().equals(uniqueId)) {
this.lookupCache.put(uniqueId, entity);
return entity;
}
}
}
}
return null;
}
@EventHandler
public void onEntityDeathEvent(EntityDeathEvent event) {
Entity entity = event.getEntity();
if (!this.isTamableFox(entity))
return;
this.lookupCache.remove(entity.getUniqueId());
foxUUIDs.remove(entity.getUniqueId());
if (configFoxes.get().getConfigurationSection("Foxes").contains(entity.getUniqueId().toString())) {
/*EntityTamableFox tamableFox = (EntityTamableFox) ((CraftEntity) entity).getHandle();
if (tamableFox.getOwner() != null && tamableFox.getOwner() instanceof Player) {
Player owner = (Player) tamableFox.getOwner();
owner.sendMessage(getPrefix() + ChatColor.RED + tamableFox.getChosenName() + " was killed!");
}*/
configFoxes.get().set("Foxes." + entity.getUniqueId(), null);
fileManager.saveConfig("foxes.yml");
}
}
public boolean isTamableFox(org.bukkit.entity.Entity entity) {
return ((CraftEntity) entity).getHandle().getClass().getName().contains("TamableFox")
|| ((CraftEntity) entity).getHandle() instanceof EntityTamableFox;
}
public List<UUID> getFoxesOf(Player player) {
return foxUUIDs.entrySet().stream().filter(foxPlayer -> foxPlayer.getValue() != null && foxPlayer.getValue().equals(player.getUniqueId()))
.map(Map.Entry::getKey).collect(Collectors.toList());
}
public FileManager getFileManager() {
return fileManager;
}
public FileManager.Config getMainConfig() {
return config;
}
public FileManager.Config getConfigFoxes() {
return configFoxes;
}
public EntityTypes getCustomType() {
return customType;
}
public Map<UUID, UUID> getFoxUUIDs() {
return foxUUIDs;
}
public static String getPrefix() {
//return ChatColor.translateAlternateColorCodes('&', (String) config.get("prefix"));
return ChatColor.RED + "[Tamable Foxes] ";
}
public boolean isShowOwnerFoxName() {
return (boolean) config.get("show-owner-in-fox-name");
}
public boolean isShowNameTags() {
return (boolean) config.get("show-nametags");
}
public boolean isTamedAttackRabbitChicken() {
return (boolean) config.get("tamed-behavior.no-attack-chicken-rabbit");
}
}

View File

@ -41,18 +41,26 @@ public class CommandSpawnTamableFox implements TabExecutor {
if (args.length != 0) { if (args.length != 0) {
switch (args[0]) { switch (args[0]) {
case "red": case "red":
EntityTamableFox fox = (EntityTamableFox) plugin.spawnTamableFox(player.getLocation(), EntityFox.Type.RED); try {
plugin.getSpawnedFoxes().add(fox); EntityTamableFox fox = (EntityTamableFox) plugin.spawnTamableFox(player.getLocation(), EntityFox.Type.RED);
plugin.sqLiteSetterGetter.saveFox(fox); plugin.getSpawnedFoxes().add(fox);
plugin.sqLiteSetterGetter.saveFox(fox);
player.sendMessage(plugin.getPrefix() + ChatColor.RESET + "Spawned a " + ChatColor.RED + "Red" + ChatColor.WHITE + " fox."); player.sendMessage(plugin.getPrefix() + ChatColor.RESET + "Spawned a " + ChatColor.RED + "Red" + ChatColor.WHITE + " fox.");
} catch (Exception e) {
player.sendMessage(plugin.getPrefix() + ChatColor.RED + "Failed to spawn fox, check console!");
}
break; break;
case "snow": case "snow":
EntityTamableFox spawnedFox = (EntityTamableFox) plugin.spawnTamableFox(player.getLocation(), EntityFox.Type.SNOW); try {
plugin.getSpawnedFoxes().add(spawnedFox); EntityTamableFox spawnedFox = (EntityTamableFox) plugin.spawnTamableFox(player.getLocation(), EntityFox.Type.SNOW);
plugin.sqLiteSetterGetter.saveFox(spawnedFox); plugin.getSpawnedFoxes().add(spawnedFox);
plugin.sqLiteSetterGetter.saveFox(spawnedFox);
player.sendMessage(plugin.getPrefix() + ChatColor.RESET + "Spawned a " + ChatColor.AQUA + "Snow" + ChatColor.WHITE + " fox."); player.sendMessage(plugin.getPrefix() + ChatColor.RESET + "Spawned a " + ChatColor.AQUA + "Snow" + ChatColor.WHITE + " fox.");
} catch (Exception e) {
player.sendMessage(plugin.getPrefix() + ChatColor.RED + "Failed to spawn fox, check console!");
}
break; break;
case "verbose": case "verbose":
player.sendMessage(plugin.getFoxUUIDs().toString()); player.sendMessage(plugin.getFoxUUIDs().toString());

View File

@ -1,4 +1,4 @@
package net.seanomik.tamablefoxes.sqllite; package net.seanomik.tamablefoxes.sqlite;
import net.seanomik.tamablefoxes.TamableFoxes; import net.seanomik.tamablefoxes.TamableFoxes;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -18,7 +18,7 @@ public class SQLiteHandler {
String url = "jdbc:sqlite:" + baseLoc + "plugins/TamableFoxes/foxes.db"; String url = "jdbc:sqlite:" + baseLoc + "plugins/TamableFoxes/foxes.db";
connection = DriverManager.getConnection(url); connection = DriverManager.getConnection(url);
Bukkit.getConsoleSender().sendMessage(TamableFoxes.getPrefix() + "Connection to SQLite has been established."); //Bukkit.getConsoleSender().sendMessage(TamableFoxes.getPrefix() + "Connection to SQLite has been established.");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -1,20 +1,26 @@
package net.seanomik.tamablefoxes.sqllite; package net.seanomik.tamablefoxes.sqlite;
import net.minecraft.server.v1_15_R1.EntityFox;
import net.minecraft.server.v1_15_R1.EnumItemSlot; import net.minecraft.server.v1_15_R1.EnumItemSlot;
import net.seanomik.tamablefoxes.EntityTamableFox; import net.seanomik.tamablefoxes.EntityTamableFox;
import net.seanomik.tamablefoxes.TamableFoxes; import net.seanomik.tamablefoxes.TamableFoxes;
import org.bukkit.plugin.Plugin; import org.apache.commons.lang.ObjectUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
public class SQLiteSetterGetter { public class SQLiteSetterGetter {
public static Plugin plugin; public static TamableFoxes plugin;
public static SQLiteHandler sqLiteHandler; public static SQLiteHandler sqLiteHandler;
public void createTablesIfNotExist() { public void createTablesIfNotExist() {
@ -24,9 +30,13 @@ public class SQLiteSetterGetter {
String foxesTable = String foxesTable =
"CREATE TABLE IF NOT EXISTS `foxes` ( " + "CREATE TABLE IF NOT EXISTS `foxes` ( " +
"`OWNER_UUID` TEXT PRIMARY KEY , " + "`ID` INTEGER PRIMARY KEY AUTOINCREMENT , " +
"`NAME` TEXT NOT NULL , " + "`OWNER_UUID` TEXT NOT NULL , " +
"`NAME` TEXT , " +
"`LOCATION` TEXT NOT NULL , " + "`LOCATION` TEXT NOT NULL , " +
"`TYPE` TEXT NOT NULL , " +
"`SITTING` INTEGER NOT NULL , " +
"`SLEEPING` INTEGER NOT NULL , " +
"`MOUTH_ITEM` TEXT NOT NULL);"; "`MOUTH_ITEM` TEXT NOT NULL);";
try { try {
@ -57,14 +67,100 @@ public class SQLiteSetterGetter {
plugin = TamableFoxes.getPlugin(TamableFoxes.class); plugin = TamableFoxes.getPlugin(TamableFoxes.class);
try { try {
sqLiteHandler.connect(); sqLiteHandler.connect();
PreparedStatement statement = sqLiteHandler.getConnection()
.prepareStatement("INSERT INTO foxes (OWNER_UUID,NAME,LOCATION,MOUTH_ITEM) VALUES (?,?,?,?)");
statement.setString(1, (fox.getOwner().getUniqueID() == null) ? "none" : fox.getOwner().getUniqueID().toString()); PreparedStatement statement = sqLiteHandler.getConnection().prepareStatement("INSERT INTO foxes (OWNER_UUID,NAME,LOCATION,TYPE,MOUTH_ITEM,SITTING,SLEEPING) VALUES (?,?,?,?,?,?,?)");
if (fox.databaseID != -1) {
statement = sqLiteHandler.getConnection().prepareStatement("UPDATE foxes SET OWNER_UUID=?, NAME=?, LOCATION=?, TYPE=?, MOUTH_ITEM=?, SITTING=?, SLEEPING=? WHERE ID=" + fox.databaseID);
}
statement.setString(1, (fox.getOwner() == null) ? "none" : fox.getOwner().getUniqueID().toString());
statement.setString(2, fox.getChosenName()); statement.setString(2, fox.getChosenName());
statement.setString(3, fox.getWorld().worldData.getName() + "," + fox.locX() + "," + fox.locY() + "," + fox.locZ());
statement.setString(4, fox.getFoxType().toString());
statement.setString(5, fox.getEquipment(EnumItemSlot.MAINHAND).toString().toUpperCase().substring(fox.getEquipment(EnumItemSlot.MAINHAND).toString().indexOf(' ')+1));
statement.setInt(6, (fox.isSitting()) ? 1 : 0);
statement.setInt(7, (fox.isSleeping()) ? 1 : 0);
statement.executeUpdate();
statement.setString(3, fox.locX() + "," + fox.locY() + "," + fox.locY()); ResultSet result = statement.getGeneratedKeys();
statement.setString(4, fox.getEquipment(EnumItemSlot.MAINHAND).toString()); while (result.next()) {
fox.databaseID = result.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (sqLiteHandler.getConnection() != null) {
try {
sqLiteHandler.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public void saveFoxes(List<EntityTamableFox> foxes) { // @TODO: Optimize
for (EntityTamableFox fox : foxes) {
saveFox(fox);
}
}
public List<EntityTamableFox> spawnFoxes() {
plugin = TamableFoxes.getPlugin(TamableFoxes.class);
try {
sqLiteHandler.connect();
PreparedStatement statement = sqLiteHandler.getConnection().prepareStatement("SELECT * FROM foxes");
ResultSet results = statement.executeQuery();
List<EntityTamableFox> foxList = new ArrayList<>();
while (results.next()) { // Loop through each row
List<String> locationList = Arrays.asList(results.getString("LOCATION").split("\\s*,\\s*"));
Location loc = new Location(Bukkit.getWorld(locationList.get(0)), Double.parseDouble(locationList.get(1)), Double.parseDouble(locationList.get(2)), Double.parseDouble(locationList.get(3)));
EntityTamableFox spawnedFox = (EntityTamableFox) plugin.spawnTamableFox(loc, EntityFox.Type.valueOf(results.getString("TYPE")));
spawnedFox.databaseID = results.getInt("ID");
spawnedFox.setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(new ItemStack(Material.valueOf(results.getString("MOUTH_ITEM")), 1)));
spawnedFox.setSitting(results.getInt("SITTING") == 1);
spawnedFox.setSleeping(results.getInt("SLEEPING") == 1);
if (!results.getString("OWNER_UUID").equals("none")) {
UUID ownerUUID = UUID.fromString(results.getString("OWNER_UUID"));
OfflinePlayer owner = plugin.getServer().getOfflinePlayer(ownerUUID);
if (owner.isOnline()) {
spawnedFox.setOwner(((CraftPlayer) owner.getPlayer()).getHandle());
}
plugin.getFoxUUIDs().put(spawnedFox.getUniqueID(), ownerUUID);
spawnedFox.setChosenName(results.getString("NAME"));
spawnedFox.setTamed(true);
}
foxList.add(spawnedFox);
}
return foxList;
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (sqLiteHandler.getConnection() != null) {
try {
sqLiteHandler.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
public void removeFox(int databaseID) {
plugin = TamableFoxes.getPlugin(TamableFoxes.class);
try {
sqLiteHandler.connect();
PreparedStatement statement = sqLiteHandler.getConnection().prepareStatement("DELETE FROM foxes WHERE ID=" + databaseID);
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -79,42 +175,7 @@ public class SQLiteSetterGetter {
} }
} }
public List<EntityTamableFox> spawnFoxes() { public void removeFox(EntityTamableFox fox) {
plugin = Dexun.getPlugin(Dexun.class); removeFox(fox.databaseID);
try {
sqLiteHandler.connect();
PreparedStatement statement = sqLiteHandler.getConnection()
.prepareStatement("SELECT * FROM foxes");
ResultSet results = statement.executeQuery();
results.next();
String banReasonsSTR = results.getString("REASONS");
String banDatesSTR = results.getString("ON_DATES");
String banEndDatesSTR = results.getString("END_DATES");
String unbanReasonsSTR = results.getString("UNBAN_REASONS");
List<String> banReasons = new LinkedList<String>(Arrays.asList(banReasonsSTR.substring(1).split(",")));
List<String> banDates = new LinkedList<String>(Arrays.asList(banDatesSTR.substring(1).split(",")));
List<String> banEndDates = new LinkedList<String>(Arrays.asList(banEndDatesSTR.substring(1).split(",")));
List<String> unbanReasons = new LinkedList<String>(Arrays.asList(unbanReasonsSTR.substring(1).split(",")));
List<List<String>> bans = new ArrayList<List<String>>();
bans.add(banReasons);
bans.add(banDates);
bans.add(banEndDates);
bans.add(unbanReasons);
return bans;
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (sqLiteHandler.getConnection() != null) {
try {
sqLiteHandler.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} }
} }

View File

@ -3,4 +3,4 @@ show-owner-in-fox-name: true
show-nametags: true show-nametags: true
tamed-behavior: tamed-behavior:
no-attack-chicken-rabbit: true attack-chicken-rabbit: true

View File

@ -3,4 +3,4 @@ show-owner-in-fox-name: true
show-nametags: true show-nametags: true
tamed-behavior: tamed-behavior:
no-attack-chicken-rabbit: true attack-chicken-rabbit: true

View File

@ -8,6 +8,7 @@ net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalBeg.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomStrollLand.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomStrollLand.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLunge.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLunge.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFloat.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFloat.class
net\seanomik\tamablefoxes\TamableFoxes$SaveFoxRunnable.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalMeleeAttack.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalMeleeAttack.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomTargetNonTamed.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomTargetNonTamed.class
net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFleeSun.class net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFleeSun.class

View File

@ -1,21 +1,21 @@
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomStrollLand.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFloat.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomTargetNonTamed.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomTargetNonTamed.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLunge.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\command\CommandSpawnTamableFox.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\command\CommandSpawnTamableFox.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalOwnerHurtByTarget.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\TamableFoxes.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\sqlite\SQLiteHandler.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalBeg.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\EntityTamableFox.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalPickBushes.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalMeleeAttack.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalBreed.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalHurtByTarget.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalMeleeAttack.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalSit.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\EntityTamableFox.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalOwnerHurtTarget.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFleeSun.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalPickBushes.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\sqlite\SQLiteHandler.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalBreed.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLungeUNKNOWN_USE.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\io\FileManager.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalOwnerHurtByTarget.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalBeg.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalOwnerHurtTarget.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLungeUNKNOWN_USE.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalSit.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\sqlite\SQLiteSetterGetter.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\sqlite\SQLiteSetterGetter.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\TamableFoxes.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFloat.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalLunge.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\io\FileManager.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalRandomStrollLand.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalHurtByTarget.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFollowOwner.java
D:\Code\java\spigotPlugins\myPlugins\GitTamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFollowOwner.java C:\code\java\TamableFoxes\src\main\java\net\seanomik\tamablefoxes\pathfinding\FoxPathfindGoalFleeSun.java