A fundamental rewrite

Created module system.
Converted auto breeding into a module.
Renamed auto harvest to auto collect and converted it to a module.
Covered all modules with the farm animation.
Added auto butcher.
Added farm types.
Removed EntityTask.
Made the breeding module upgradable.
Made modules toggleable.
Added heart animation to breeding.


Did a lot more but my patch notes got fried in a power surge.
This commit is contained in:
Brianna 2019-10-16 22:44:27 -04:00
parent 44574abac2
commit 4d84b62eb9
20 changed files with 1003 additions and 476 deletions

View File

@ -13,16 +13,21 @@ import com.songoda.epicfarming.boost.BoostManager;
import com.songoda.epicfarming.commands.*;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.FarmManager;
import com.songoda.epicfarming.farming.Level;
import com.songoda.epicfarming.farming.LevelManager;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.farming.levels.Level;
import com.songoda.epicfarming.farming.levels.LevelManager;
import com.songoda.epicfarming.farming.levels.modules.Module;
import com.songoda.epicfarming.farming.levels.modules.ModuleAutoBreeding;
import com.songoda.epicfarming.farming.levels.modules.ModuleAutoButcher;
import com.songoda.epicfarming.farming.levels.modules.ModuleAutoCollect;
import com.songoda.epicfarming.listeners.BlockListeners;
import com.songoda.epicfarming.listeners.EntityListeners;
import com.songoda.epicfarming.listeners.InteractListeners;
import com.songoda.epicfarming.listeners.UnloadListeners;
import com.songoda.epicfarming.settings.Settings;
import com.songoda.epicfarming.storage.Storage;
import com.songoda.epicfarming.storage.StorageRow;
import com.songoda.epicfarming.storage.types.StorageYaml;
import com.songoda.epicfarming.tasks.EntityTask;
import com.songoda.epicfarming.tasks.FarmTask;
import com.songoda.epicfarming.tasks.GrowthTask;
import com.songoda.epicfarming.tasks.HopperTask;
@ -35,6 +40,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -58,7 +64,6 @@ public class EpicFarming extends SongodaPlugin {
private GrowthTask growthTask;
private FarmTask farmTask;
private EntityTask entityTask;
private Storage storage;
@ -138,11 +143,17 @@ public class EpicFarming extends SongodaPlugin {
if (configPlacedBy != null) {
placedBY = UUID.fromString(configPlacedBy);
}
FarmType farmType = FarmType.BOTH;
String farmTypeStr = row.get("farmtype").asString();
if (farmTypeStr != null)
farmType = FarmType.valueOf(farmTypeStr);
Farm farm = new Farm(location, levelManager.getLevel(level), placedBY);
farm.setFarmType(farmType);
farm.setItems(items);
Bukkit.getScheduler().runTask(EpicFarming.getInstance(), () -> {
farmManager.addFarm(location, farm);
});
Bukkit.getScheduler().runTask(EpicFarming.getInstance(), () ->
farmManager.addFarm(location, farm));
}
}
@ -171,6 +182,7 @@ public class EpicFarming extends SongodaPlugin {
// Register Listeners
guiManager.init();
PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new EntityListeners(this), this);
pluginManager.registerEvents(new BlockListeners(this), this);
pluginManager.registerEvents(new InteractListeners(this), this);
pluginManager.registerEvents(new UnloadListeners(this), this);
@ -178,7 +190,6 @@ public class EpicFarming extends SongodaPlugin {
// Start tasks
this.growthTask = GrowthTask.startTask(this);
this.farmTask = FarmTask.startTask(this);
this.entityTask = EntityTask.startTask(this);
Bukkit.getScheduler().runTaskLater(this, () -> {
if (!Bukkit.getPluginManager().isPluginEnabled("EpicHoppers"))
@ -202,7 +213,7 @@ public class EpicFarming extends SongodaPlugin {
}
private void loadLevelManager() {
if (!levelsFile.getFile().exists())
if (!new File(this.getDataFolder(), "levels.yml").exists())
this.saveResource("levels.yml", false);
levelsFile.load();
@ -214,24 +225,51 @@ public class EpicFarming extends SongodaPlugin {
*/
for (String levelName : levelsFile.getKeys(false)) {
ConfigurationSection levels = levelsFile.getConfigurationSection(levelName);
if (levels.get("Auto-Harvest") != null) {
levels.set("Auto-Collect", levels.getBoolean("Auto-Harvest"));
levels.set("Auto-Harvest", null);
}
int level = Integer.parseInt(levelName.split("-")[1]);
int costExperiance = levels.getInt("Cost-xp");
int costEconomy = levels.getInt("Cost-eco");
int radius = levels.getInt("Radius");
double speedMultiplier = levels.getDouble("Speed-Multiplier");
boolean autoHarvest = levels.getBoolean("Auto-Harvest");
boolean autoCollect = levels.getBoolean("Auto-Collect");
boolean autoReplant = levels.getBoolean("Auto-Replant");
boolean autoBreeding = levels.getBoolean("Auto-Breeding");
int pages = levels.getInt("Pages", 1);
levelManager.addLevel(level, costExperiance, costEconomy, speedMultiplier, radius, autoHarvest, autoReplant, autoBreeding, pages);
if (levels.get("Auto-Breeding") instanceof Boolean) {
levels.set("Auto-Breeding", 15);
}
ArrayList<Module> modules = new ArrayList<>();
for (String key : levels.getKeys(false)) {
if (key.equals("Auto-Breeding") && levels.getInt("Auto-Breeding") != 0) {
modules.add(new ModuleAutoBreeding(this, levels.getInt("Auto-Breeding")));
} else if (key.equals("Auto-Butcher") && levels.getInt("Auto-Butcher") != 0) {
modules.add(new ModuleAutoButcher(this, levels.getInt("Auto-Butcher")));
} else if (key.equals("Auto-Collect")) {
modules.add(new ModuleAutoCollect(this));
}
}
levelManager.addLevel(level, costExperiance, costEconomy, speedMultiplier, radius, autoCollect, autoReplant, pages, modules);
}
levelsFile.saveChanges();
}
/*
* Saves registered farms to file.
*/
private void saveToFile() {
if (levelManager != null) {
for (Level level : levelManager.getLevels().values())
for (Module module : level.getRegisteredModules())
module.saveDataToFile();
}
storage.doSave();
}
@ -277,10 +315,6 @@ public class EpicFarming extends SongodaPlugin {
return farmTask;
}
public EntityTask getEntityTask() {
return entityTask;
}
public GuiManager getGuiManager() {
return guiManager;
}

View File

@ -2,7 +2,7 @@ package com.songoda.epicfarming.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Level;
import com.songoda.epicfarming.farming.levels.Level;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

View File

@ -5,9 +5,13 @@ import com.songoda.core.compatibility.CompatibleParticleHandler;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.levels.Level;
import com.songoda.epicfarming.gui.OverviewGui;
import com.songoda.epicfarming.settings.Settings;
import org.bukkit.*;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
@ -27,6 +31,10 @@ public class Farm {
private UUID viewing = null;
private long lastCached = 0;
private FarmType farmType = FarmType.BOTH;
private final Map<String, Object> moduleCache = new HashMap<>();
public Farm(Location location, Level level, UUID placedBy) {
this.location = location;
this.level = level;
@ -89,9 +97,8 @@ public class Farm {
instance.getLocale().getMessage("event.upgrade.successmaxed")
.processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player);
}
tillLand();
Location loc = location.clone().add(.5, .5, .5);
tillLand(location);
CompatibleParticleHandler.spawnParticles(Settings.PARTICLE_TYPE.getString(), loc, 200, .5, .5, .5);
if (instance.getLevelManager().getHighestLevel() != level) {
@ -105,7 +112,7 @@ public class Farm {
}
}
public boolean tillLand(Location location) {
public boolean tillLand() {
if (Settings.DISABLE_AUTO_TIL_LAND.getBoolean()) return true;
Block block = location.getBlock();
int radius = level.getRadius();
@ -252,4 +259,46 @@ public class Farm {
public void close() {
this.opened = null;
}
public Object getDataFromModuleCache(String key) {
return this.moduleCache.getOrDefault(key, null);
}
public void addDataToModuleCache(String key, Object data) {
this.moduleCache.put(key, data);
}
public boolean isDataCachedInModuleCache(String key) {
return this.moduleCache.containsKey(key);
}
public void removeDataFromModuleCache(String key) {
this.moduleCache.remove(key);
}
public void clearModuleCache() {
this.moduleCache.clear();
}
public FarmType getFarmType() {
return farmType;
}
public void toggleFarmType() {
switch (farmType) {
case CROPS:
farmType = FarmType.LIVESTOCK;
break;
case LIVESTOCK:
farmType = FarmType.BOTH;
break;
case BOTH:
farmType = FarmType.CROPS;
break;
}
}
public void setFarmType(FarmType farmType) {
this.farmType = farmType;
}
}

View File

@ -0,0 +1,13 @@
package com.songoda.epicfarming.farming;
import com.songoda.epicfarming.EpicFarming;
public enum FarmType {
CROPS, LIVESTOCK, BOTH;
public String translate() {
return EpicFarming.getInstance().getLocale().getMessage("general.interface." + name().toLowerCase()).getMessage();
}
}

View File

@ -1,31 +1,33 @@
package com.songoda.epicfarming.farming;
package com.songoda.epicfarming.farming.levels;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.levels.modules.Module;
import java.util.ArrayList;
import java.util.List;
public class Level {
private int level, costExperiance, costEconomy, radius, pages;
private double speedMultiplier;
private boolean autoHarvest, autoReplant, autoBreeding;
private final ArrayList<Module> registeredModules;
private List<String> description = new ArrayList<>();
private int level, costExperiance, costEconomy, radius, pages;
private double speedMultiplier;
private boolean autoReplant;
Level(int level, int costExperiance, int costEconomy, double speedMultiplier, int radius, boolean autoHarvest, boolean autoReplant, boolean autoBreeding, int pages) {
Level(int level, int costExperiance, int costEconomy, double speedMultiplier, int radius, boolean autoReplant, int pages, ArrayList<Module> registeredModules) {
this.level = level;
this.costExperiance = costExperiance;
this.costEconomy = costEconomy;
this.speedMultiplier = speedMultiplier;
this.radius = radius;
this.autoHarvest = autoHarvest;
this.autoReplant = autoReplant;
this.autoBreeding = autoBreeding;
this.pages = pages;
this.registeredModules = registeredModules;
buildDescription();
}
public void buildDescription() {
EpicFarming instance = EpicFarming.getInstance();
description.add(instance.getLocale().getMessage("interface.button.radius")
@ -34,22 +36,20 @@ public class Level {
description.add(instance.getLocale().getMessage("interface.button.speed")
.processPlaceholder("speed", speedMultiplier).getMessage());
if (autoHarvest)
description.add(instance.getLocale().getMessage("interface.button.autoharvest")
.processPlaceholder("status", autoHarvest).getMessage());
if (autoReplant)
description.add(instance.getLocale().getMessage("interface.button.autoreplant")
.processPlaceholder("status", autoReplant).getMessage());
if (autoBreeding)
description.add(instance.getLocale().getMessage("interface.button.autobreeding")
.processPlaceholder("status", autoBreeding).getMessage());
.processPlaceholder("status",
instance.getLocale().getMessage("general.interface.unlocked")
.getMessage()).getMessage());
if (pages > 1)
description.add(instance.getLocale().getMessage("interface.button.pages")
.processPlaceholder("amount", pages).getMessage());
for (Module module : registeredModules) {
description.add(module.getDescription());
}
}
public List<String> getDescription() {
@ -64,18 +64,10 @@ public class Level {
return radius;
}
public boolean isAutoHarvest() {
return autoHarvest;
}
public boolean isAutoReplant() {
return autoReplant;
}
public boolean isAutoBreeding() {
return autoBreeding;
}
public int getPages() {
return pages;
}
@ -91,4 +83,18 @@ public class Level {
public int getCostEconomy() {
return costEconomy;
}
public ArrayList<Module> getRegisteredModules() {
return new ArrayList<>(registeredModules);
}
public void addModule(Module module) {
registeredModules.add(module);
buildDescription();
}
public Module getModule(String name) {
return registeredModules == null ? null :
registeredModules.stream().filter(module -> module.getName().equals(name)).findFirst().orElse(null);
}
}

View File

@ -1,16 +1,15 @@
package com.songoda.epicfarming.farming;
package com.songoda.epicfarming.farming.levels;
import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import com.songoda.epicfarming.farming.levels.modules.Module;
import java.util.*;
public class LevelManager {
private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>();
public void addLevel(int level, int costExperiance, int costEconomy, double speedMultiplier, int radius, boolean autoHarvest, boolean autoReplant, boolean autobreeding, int pages) {
registeredLevels.put(level, new Level(level, costExperiance, costEconomy, speedMultiplier, radius, autoHarvest, autoReplant, autobreeding, pages));
public void addLevel(int level, int costExperiance, int costEconomy, double speedMultiplier, int radius, boolean autoCollect, boolean autoReplant, int pages, ArrayList<Module> modules) {
registeredLevels.put(level, new Level(level, costExperiance, costEconomy, speedMultiplier, radius, autoReplant, pages, modules));
}
public Level getLevel(int level) {

View File

@ -0,0 +1,90 @@
package com.songoda.epicfarming.farming.levels.modules;
import com.songoda.core.configuration.Config;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public abstract class Module {
private static final Map<String, Config> configs = new HashMap<>();
protected final EpicFarming plugin;
private final Config config;
public Module(EpicFarming plugin) {
this.plugin = plugin;
if (!configs.containsKey(getName())) {
Config config = new Config(plugin, File.separator + "modules", getName() + ".yml");
configs.put(getName(), config);
config.load();
}
this.config = configs.get(getName());
}
public abstract String getName();
public abstract int runEveryXTicks();
private int currentTick = 0;
public void run(Farm farm, Collection<LivingEntity> entitiesAroundFarm) {
if (currentTick >= runEveryXTicks()) {
runFinal(farm, entitiesAroundFarm);
currentTick = 0;
return;
}
currentTick++;
}
public abstract void runFinal(Farm farm, Collection<LivingEntity> entitiesAroundFarm);
public abstract ItemStack getGUIButton(Farm farm);
public abstract void runButtonPress(Player player, Farm farm, ClickType type);
public abstract String getDescription();
public void saveData(Farm farm, String setting, Object value) {
saveData(farm, setting, value, value);
}
public void saveData(Farm farm, String setting, Object value, Object toCache) {
config.set("data." + Methods.serializeLocation(farm.getLocation()) + "." + setting, value);
modifyDataCache(farm, setting, toCache);
}
public void modifyDataCache(Farm farm, String setting, Object value) {
farm.addDataToModuleCache(getName() + "." + setting, value);
}
protected Object getData(Farm farm, String setting) {
String cacheStr = getName() + "." + setting;
if (farm.isDataCachedInModuleCache(cacheStr))
return farm.getDataFromModuleCache(cacheStr);
Object data = config.get("data." + Methods.serializeLocation(farm.getLocation()) + "." + setting);
modifyDataCache(farm, setting, data);
return data;
}
public void clearData(Farm farm) {
config.set("data." + Methods.serializeLocation(farm.getLocation()), null);
farm.clearModuleCache();
}
public void saveDataToFile() {
config.save();
}
}

View File

@ -0,0 +1,156 @@
package com.songoda.epicfarming.farming.levels.modules;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleParticleHandler;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.hooks.EntityStackerManager;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.utils.EntityInfo;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.*;
import java.util.stream.Collectors;
public class ModuleAutoBreeding extends Module {
private final int autoBreedCap;
public ModuleAutoBreeding(EpicFarming plugin, int autoBreedCap) {
super(plugin);
this.autoBreedCap = autoBreedCap;
}
@Override
public String getName() {
return "AutoBreeding";
}
@Override
public int runEveryXTicks() {
return 5;
}
@Override
public void runFinal(Farm farm, Collection<LivingEntity> entitiesAroundFarm) {
if (!isEnabled(farm) || farm.getFarmType() == FarmType.CROPS) return;
List<LivingEntity> entities = new ArrayList<>(entitiesAroundFarm);
Collections.shuffle(entities);
if (entities.size() >= autoBreedCap)
return;
entities.removeIf(e -> !(e instanceof Ageable) || !((Ageable) e).isAdult() || e.hasMetadata("breedCooldown") || e.isDead());
Map<EntityType, Long> counts =
entities.stream().collect(Collectors.groupingBy(Entity::getType, Collectors.counting()));
for (LivingEntity entity : entities) {
int stackSize = EntityStackerManager.getSize(entity);
if (stackSize == 0) stackSize = 1;
counts.put(entity.getType(),
counts.get(entity.getType()) - 1 + stackSize);
}
for (Map.Entry<EntityType, Long> entry : counts.entrySet()) {
boolean mate1 = false;
for (LivingEntity entity : entities) {
if (entry.getKey() != entity.getType()) continue;
int count = EntityStackerManager.getSize(entity) == 0 ? 1 : EntityStackerManager.getSize(entity);
if (mate1) {
if (count > 1)
handleStackedBreed(entity);
else
handleBreed(entity);
Methods.animate(farm.getLocation(), Material.EGG);
return;
}
if (entry.getValue() >= 2) {
EntityType entityType = entry.getKey();
for (ItemStack item : new ArrayList<>(farm.getItems())) {
try {
if (item.getType() != EntityInfo.valueOf(entityType.name()).getMaterial() || item.getAmount() < 2)
continue;
} catch (IllegalArgumentException e) {
continue;
}
farm.removeMaterial(item.getType(), 2);
Location location = entity.getLocation();
CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.HEART,
location, 5, .5, .5, .5);
Entity newSpawn = location.getWorld().spawnEntity(location, entityType);
((Ageable) newSpawn).setBaby();
if (count > 1) {
handleStackedBreed(entity);
if (count - 1 > 1) {
handleStackedBreed(entity);
} else {
handleBreed(entity);
}
return;
}
handleBreed(entity);
mate1 = true;
}
}
}
}
}
@Override
public ItemStack getGUIButton(Farm farm) {
return GuiUtils.createButtonItem(CompatibleMaterial.EGG, plugin.getLocale().getMessage("interface.button.autobreeding")
.processPlaceholder("status", isEnabled(farm)
? plugin.getLocale().getMessage("general.interface.on").getMessage()
: plugin.getLocale().getMessage("general.interface.off").getMessage()).getMessage(),
plugin.getLocale().getMessage("interface.button.functiontoggle").getMessage());
}
@Override
public void runButtonPress(Player player, Farm farm, ClickType type) {
toggleEnabled(farm);
}
@Override
public String getDescription() {
return plugin.getLocale().getMessage("interface.button.autobreeding")
.processPlaceholder("status", autoBreedCap).getMessage();
}
private void handleStackedBreed(LivingEntity entity) {
EntityStackerManager.removeOne(entity);
LivingEntity spawned = (LivingEntity) entity.getWorld().spawnEntity(entity.getLocation(), entity.getType());
handleBreed(spawned);
}
private void handleBreed(Entity entity) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () ->
entity.removeMetadata("breedCooldown", plugin), 5 * 20 * 60);
entity.setMetadata("breedCooldown", new FixedMetadataValue(plugin, true));
}
private boolean isEnabled(Farm farm) {
Object obj = getData(farm, "enabled");
return obj == null || (boolean) obj;
}
private void toggleEnabled(Farm farm) {
saveData(farm, "enabled", !isEnabled(farm));
}
}

View File

@ -0,0 +1,93 @@
package com.songoda.epicfarming.farming.levels.modules;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.hooks.EntityStackerManager;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.*;
public class ModuleAutoButcher extends Module {
private final int autoButcherDelay;
public ModuleAutoButcher(EpicFarming plugin, int autoButcherDelay) {
super(plugin);
this.autoButcherDelay = autoButcherDelay;
}
@Override
public String getName() {
return "AutoButcher";
}
@Override
public int runEveryXTicks() {
return autoButcherDelay;
}
@Override
public void runFinal(Farm farm, Collection<LivingEntity> entitiesAroundFarm) {
if (!isEnabled(farm)|| farm.getFarmType() == FarmType.CROPS) return;
List<LivingEntity> entities = new ArrayList<>(entitiesAroundFarm);
Collections.shuffle(entities);
entities.removeIf(e -> e instanceof Ageable && !((Ageable) e).isAdult() || e.isDead());
int count = 0;
for (LivingEntity entity : entities) {
int stackSize = EntityStackerManager.getSize(entity);
if (stackSize == 0) stackSize = 1;
count = stackSize;
}
if (count <= 2 || !farm.willFit(new ItemStack(Material.STONE))) return;
for (LivingEntity entity : entities) {
entity.setMetadata("EFA-TAGGED", new FixedMetadataValue(plugin, farm.getLocation()));
entity.getLocation().getWorld().playSound(entity.getLocation(),
CompatibleSound.ENTITY_PLAYER_ATTACK_SWEEP.getSound(), 1L, 1L);
entity.damage(99999999);
Methods.animate(farm.getLocation(), Material.IRON_SWORD);
return;
}
}
@Override
public ItemStack getGUIButton(Farm farm) {
return GuiUtils.createButtonItem(CompatibleMaterial.STONE_SWORD, plugin.getLocale().getMessage("interface.button.autobutcher")
.processPlaceholder("status", isEnabled(farm)
? plugin.getLocale().getMessage("general.interface.on").getMessage()
: plugin.getLocale().getMessage("general.interface.off").getMessage()).getMessage(),
plugin.getLocale().getMessage("interface.button.functiontoggle").getMessage());
}
@Override
public void runButtonPress(Player player, Farm farm, ClickType type) {
toggleEnabled(farm);
}
@Override
public String getDescription() {
return plugin.getLocale().getMessage("interface.button.autobutcher")
.processPlaceholder("status", autoButcherDelay).getMessage();
}
private boolean isEnabled(Farm farm) {
Object obj = getData(farm, "enabled");
return obj == null || (boolean) obj;
}
private void toggleEnabled(Farm farm) {
saveData(farm, "enabled", !isEnabled(farm));
}
}

View File

@ -0,0 +1,252 @@
package com.songoda.epicfarming.farming.levels.modules;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.BlockUtils;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.boost.BoostData;
import com.songoda.epicfarming.farming.Crop;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.utils.CropType;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Wool;
import java.util.*;
public class ModuleAutoCollect extends Module {
private static Map<Entity, Integer> lastTicksLived = new HashMap<>();
private static final Map<Entity, Integer> ticksLived = new HashMap<>();
private Random random = new Random();
public ModuleAutoCollect(EpicFarming plugin) {
super(plugin);
}
@Override
public String getName() {
return "AutoCollect";
}
@Override
public int runEveryXTicks() {
return 1;
}
@Override
public void runFinal(Farm farm, Collection<LivingEntity> entitiesAroundFarm) {
if (farm.getFarmType() != FarmType.LIVESTOCK)
collectCrops(farm);
if (farm.getFarmType() != FarmType.CROPS)
collectLivestock(farm, entitiesAroundFarm);
}
private void collectCrops(Farm farm) {
HashMap<Material, Boolean> hasDropped = new HashMap();
for (Block block : getCrops(farm, true)) {
Material mat = block.getType();
if (!CropType.isCrop(mat)) continue;
if (!BlockUtils.isCropFullyGrown(block)) {
// Add to GrowthTask
plugin.getGrowthTask().addLiveCrop(block.getLocation(), new Crop(block.getLocation(), farm));
} else if (isEnabled(farm) && !hasDropped.getOrDefault(mat, false) && doCropDrop(farm, mat)) {
hasDropped.put(mat, true);
if (farm.getLevel().isAutoReplant()) {
BlockUtils.resetGrowthStage(block);
continue;
}
block.setType(Material.AIR);
}
}
}
private void collectLivestock(Farm farm, Collection<LivingEntity> entitiesAroundFarm) {
for (Entity entity : entitiesAroundFarm) {
if (!ticksLived.containsKey(entity)) ticksLived.put(entity, 0);
int lived = ticksLived.get(entity);
ticksLived.put(entity, lived + 20);
int min = (int) Math.floor(getMin(entity) / farm.getLevel().getSpeedMultiplier());
int max = (int) Math.floor(getMax(entity) / farm.getLevel().getSpeedMultiplier());
int rand = random.nextInt((int) Math.floor(100 / farm.getLevel().getSpeedMultiplier()));
if (lived < min) continue;
if (rand != 5 && lived < max) continue;
if (entity instanceof Chicken) {
if (!((Ageable) entity).isAdult()) continue;
entity.getLocation().getWorld().playSound(entity.getLocation(), Sound.ENTITY_CHICKEN_EGG, 1, 2);
if (!isEnabled(farm)) {
ticksLived.remove(entity);
entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemStack(Material.EGG));
} else {
doLivestockDrop(farm, new ItemStack(Material.EGG, 1));
}
Methods.animate(farm.getLocation(), Material.EGG);
} else if (entity instanceof Sheep) {
if (!((Ageable) entity).isAdult()) continue;
((Sheep) entity).setSheared(true);
Wool woolColor = new Wool(((Sheep) entity).getColor());
ItemStack wool = woolColor.toItemStack((int) Math.round(1 + (Math.random() * 3)));
if (!isEnabled(farm)) {
entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), wool);
} else {
doLivestockDrop(farm, wool);
}
Methods.animate(farm.getLocation(), wool.getType());
}
ticksLived.put(entity, 0);
}
for (Map.Entry<Entity, Integer> entry : lastTicksLived.entrySet()) {
int last = entry.getValue();
if (!ticksLived.containsKey(entry.getKey())) continue;
int current = ticksLived.get(entry.getKey());
if (last == current) {
ticksLived.remove(entry.getKey());
}
}
lastTicksLived = new HashMap<>(ticksLived);
}
@Override
public ItemStack getGUIButton(Farm farm) {
return GuiUtils.createButtonItem(CompatibleMaterial.BUCKET, plugin.getLocale().getMessage("interface.button.autocollect")
.processPlaceholder("status", isEnabled(farm)
? plugin.getLocale().getMessage("general.interface.on").getMessage()
: plugin.getLocale().getMessage("general.interface.off").getMessage()).getMessage(),
plugin.getLocale().getMessage("interface.button.functiontoggle").getMessage());
}
@Override
public void runButtonPress(Player player, Farm farm, ClickType type) {
toggleEnabled(farm);
}
@Override
public String getDescription() {
return plugin.getLocale().getMessage("interface.button.autocollect")
.processPlaceholder("status",
plugin.getLocale().getMessage("general.interface.unlocked")
.getMessage()).getMessage();
}
public boolean isEnabled(Farm farm) {
Object obj = getData(farm, "enabled");
return obj == null || (boolean) obj;
}
private void toggleEnabled(Farm farm) {
saveData(farm, "enabled", !isEnabled(farm));
}
private boolean useBoneMeal(Farm farm) {
for (ItemStack item : farm.getItems()) {
if (item.getType() != CompatibleMaterial.BONE_MEAL.getMaterial()) continue;
farm.removeMaterial(CompatibleMaterial.BONE_MEAL.getMaterial(), 1);
return true;
}
return false;
}
public static List<Block> getCrops(Farm farm, boolean add) {
if (((System.currentTimeMillis() - farm.getLastCached()) > (30 * 1000)) || !add) {
farm.setLastCached(System.currentTimeMillis());
if (add) farm.clearCache();
Block block = farm.getLocation().getBlock();
int radius = farm.getLevel().getRadius();
int bx = block.getX();
int by = block.getY();
int bz = block.getZ();
for (int fx = -radius; fx <= radius; fx++) {
for (int fy = -2; fy <= 1; fy++) {
for (int fz = -radius; fz <= radius; fz++) {
Block b2 = block.getWorld().getBlockAt(bx + fx, by + fy, bz + fz);
CompatibleMaterial mat = CompatibleMaterial.getMaterial(b2.getType());
if (!mat.isCrop()) continue;
if (add) {
farm.addCachedCrop(b2);
continue;
}
farm.removeCachedCrop(b2);
EpicFarming.getInstance().getGrowthTask().removeCropByLocation(b2.getLocation());
}
}
}
}
return farm.getCachedCrops();
}
private int getMin(Entity entity) {
switch (entity.getType()) {
case SHEEP:
return 0;
case CHICKEN:
return 6000;
default:
return 0;
}
}
private int getMax(Entity entity) {
switch (entity.getType()) {
case SHEEP:
return 6000;
case CHICKEN:
return 12000;
default:
return 0;
}
}
private boolean doCropDrop(Farm farm, Material material) {
CropType cropTypeData = CropType.getCropType(material);
if (material == null || farm == null || cropTypeData == null) return false;
BoostData boostData = plugin.getBoostManager().getBoost(farm.getPlacedBy());
ItemStack stack = new ItemStack(cropTypeData.getYieldMaterial(), (useBoneMeal(farm) ? random.nextInt(2) + 2 : 1) * (boostData == null ? 1 : boostData.getMultiplier()));
ItemStack seedStack = new ItemStack(cropTypeData.getSeedMaterial(), random.nextInt(3) + 1 + (useBoneMeal(farm) ? 1 : 0));
if (!farm.willFit(stack) || !farm.willFit(seedStack)) return false;
Methods.animate(farm.getLocation(), cropTypeData.getYieldMaterial());
farm.addItem(stack);
farm.addItem(seedStack);
return true;
}
private boolean doLivestockDrop(Farm farm, ItemStack stack) {
BoostData boostData = plugin.getBoostManager().getBoost(farm.getPlacedBy());
stack.setAmount(stack.getAmount() * (boostData == null ? 1 : boostData.getMultiplier()));
if (!farm.willFit(stack)) return false;
farm.addItem(stack);
return true;
}
public static Map<Entity, Integer> getTicksLived() {
return Collections.unmodifiableMap(ticksLived);
}
}

View File

@ -6,17 +6,20 @@ import com.songoda.core.gui.GuiUtils;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.boost.BoostData;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.Level;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.farming.UpgradeType;
import com.songoda.epicfarming.farming.levels.Level;
import com.songoda.epicfarming.farming.levels.modules.Module;
import com.songoda.epicfarming.settings.Settings;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
public class OverviewGui extends Gui {
@ -107,7 +110,7 @@ public class OverviewGui extends Gui {
setItem(13, GuiUtils.createButtonItem(Settings.FARM_BLOCK_MATERIAL.getMaterial(CompatibleMaterial.END_ROD),
plugin.getLocale().getMessage("general.nametag.farm")
.processPlaceholder("level", level.getLevel()).getMessage(),
.processPlaceholder("level", level.getLevel()).getMessage(),
farmLore));
if (player != null && Settings.UPGRADE_WITH_XP.getBoolean() && player.hasPermission("EpicFarming.Upgrade.XP")) {
@ -134,16 +137,76 @@ public class OverviewGui extends Gui {
? plugin.getLocale().getMessage("interface.button.upgradewitheconomylore")
.processPlaceholder("cost", Methods.formatEconomy(nextLevel.getCostEconomy())).getMessage()
: plugin.getLocale().getMessage("event.upgrade.maxed").getMessage()), (event) -> {
farm.upgrade(UpgradeType.ECONOMY, player);
onClose(guiManager, player);
farm.view(player, true);
});
farm.upgrade(UpgradeType.ECONOMY, player);
onClose(guiManager, player);
farm.view(player, true);
});
}
Material farmTypeMaterial = CompatibleMaterial.WHEAT.getMaterial();
if (farm.getFarmType() == FarmType.LIVESTOCK)
farmTypeMaterial = CompatibleMaterial.BEEF.getMaterial();
else if (farm.getFarmType() == FarmType.BOTH)
farmTypeMaterial = CompatibleMaterial.GOLD_NUGGET.getMaterial();
ItemStack farmType = new ItemStack(farmTypeMaterial, 1);
ItemMeta farmTypeMeta = farmType.getItemMeta();
farmTypeMeta.setDisplayName(plugin.getLocale().getMessage("interface.button.farmtype")
.processPlaceholder("type", farm.getFarmType().translate())
.getMessage());
farmTypeMeta.setLore(Collections.singletonList(plugin.getLocale().getMessage("interface.button.farmtypelore")
.getMessage()));
farmType.setItemMeta(farmTypeMeta);
Map<Integer, Integer[]> layouts = new HashMap<>();
layouts.put(1, new Integer[]{22});
layouts.put(2, new Integer[]{22, 4});
layouts.put(3, new Integer[]{22, 3, 5});
layouts.put(4, new Integer[]{23, 3, 5, 21});
layouts.put(5, new Integer[]{23, 3, 5, 21, 22});
layouts.put(6, new Integer[]{23, 3, 4, 5, 21, 22});
layouts.put(7, new Integer[]{23, 3, 4, 5, 21, 22, 12});
layouts.put(8, new Integer[]{23, 3, 4, 5, 21, 22, 12, 14});
layouts.put(9, new Integer[]{23, 3, 4, 5, 21, 22, 12, 14, 20});
layouts.put(10, new Integer[]{23, 3, 4, 5, 21, 22, 12, 14, 20, 24});
List<Module> modules = level.getRegisteredModules().stream().filter(module ->
module.getGUIButton(farm) != null).collect(Collectors.toList());
int amount = modules.size();
if (amount > 0) amount++;
Integer[] layout = layouts.get(amount);
for (int ii = 0; ii < amount; ii++) {
int slot = layout[ii];
if (ii == 0 && level.getRegisteredModules().stream().map(Module::getName).anyMatch(s -> s.equals("AutoCollect"))) {
setButton(slot, farmType,
(event) -> {
farm.toggleFarmType();
if (farm.getFarmType() != FarmType.LIVESTOCK)
farm.tillLand();
showPage();
});
} else {
if (modules.isEmpty()) break;
Module module = modules.get(0);
modules.remove(module);
setButton(slot, module.getGUIButton(farm),
(event) -> module.runButtonPress(player, farm, event.clickType));
}
}
}
private void runTask() {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this::updateFarm, 2L, 1L);
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
updateFarm();
showPage();
}, 2L, 1L);
}
public void updateInventory() {

View File

@ -4,32 +4,22 @@ import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.FarmManager;
import com.songoda.epicfarming.farming.Level;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.farming.levels.Level;
import com.songoda.epicfarming.farming.levels.modules.ModuleAutoCollect;
import com.songoda.epicfarming.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Chicken;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.SheepRegrowWoolEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionAttachmentInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Created by songoda on 3/14/2017.
*/
@ -44,13 +34,15 @@ public class BlockListeners implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent e) {
if (checkForFarm(e.getBlock().getLocation()))
Farm farm = checkForFarm(e.getBlock().getLocation());
if (farm != null && farm.getFarmType() != FarmType.LIVESTOCK)
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onGrow(BlockGrowEvent e) {
if (checkForFarm(e.getNewState().getLocation()))
Farm farm = checkForFarm(e.getBlock().getLocation());
if (farm != null && farm.getFarmType() != FarmType.LIVESTOCK)
e.setCancelled(true);
}
@ -91,7 +83,7 @@ public class BlockListeners implements Listener {
Location location = e.getBlock().getLocation();
if (e.getBlockPlaced().getType().equals(Material.MELON_SEEDS) || e.getBlockPlaced().getType().equals(Material.PUMPKIN_SEEDS)) {
if (checkForFarm(location)) {
if (checkForFarm(location) != null) {
instance.getLocale().getMessage("event.warning.noauto").sendPrefixedMessage(e.getPlayer());
}
}
@ -106,11 +98,11 @@ public class BlockListeners implements Listener {
Farm farm = new Farm(location, instance.getLevelManager().getLevel(level), e.getPlayer().getUniqueId());
instance.getFarmManager().addFarm(location, farm);
farm.tillLand(e.getBlock().getLocation());
farm.tillLand();
}, 1);
}
private boolean checkForFarm(Location location) {
private Farm checkForFarm(Location location) {
Material farmBlock = Settings.FARM_BLOCK_MATERIAL.getMaterial(CompatibleMaterial.END_ROD).getBlockMaterial();
FarmManager farmManager = instance.getFarmManager();
@ -127,16 +119,17 @@ public class BlockListeners implements Listener {
for (int fz = -radius; fz <= radius; fz++) {
Block b2 = block.getWorld().getBlockAt(bx + fx, by + fy, bz + fz);
if (b2.getType() == farmBlock) {
if (!farmManager.getFarms().containsKey(b2.getLocation())) continue;
Farm farm = farmManager.getFarms().get(b2.getLocation());
if (farm == null) continue;
if (level.getRadius() != farmManager.getFarm(b2.getLocation()).getLevel().getRadius())
continue;
return true;
return farm;
}
}
}
}
}
return false;
return null;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -148,7 +141,7 @@ public class BlockListeners implements Listener {
if (farm == null) return;
instance.getFarmTask().getCrops(farm, false);
ModuleAutoCollect.getCrops(farm, false);
event.setCancelled(true);
@ -164,71 +157,6 @@ public class BlockListeners implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
if (item.getItemStack().getType() != Material.EGG) return;
Location location = event.getEntity().getLocation();
Collection<Entity> nearby = location.getWorld().getNearbyEntities(location, 0.01, 0.3, 0.01);
Entity entity = null;
for (Entity e : nearby) {
if (e instanceof Player) return;
if (e instanceof Chicken) entity = e;
}
if (instance.getEntityTask().getTicksLived().containsKey(entity)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSpawn(SheepRegrowWoolEvent event) {
if (instance.getEntityTask().getTicksLived().containsKey(event.getEntity())) {
event.setCancelled(true);
Block block = event.getEntity().getLocation().getBlock().getRelative(BlockFace.DOWN);
if (block.getType() == Material.DIRT) {
block.setType(Material.GRASS_BLOCK);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlow(EntityExplodeEvent event) {
List<Block> destroyed = event.blockList();
Iterator<Block> it = destroyed.iterator();
List<Block> toCancel = new ArrayList<>();
while (it.hasNext()) {
Block block = it.next();
if (block.getType() != Settings.FARM_BLOCK_MATERIAL.getMaterial(CompatibleMaterial.END_ROD).getMaterial())
continue;
Farm farm = instance.getFarmManager().getFarm(block.getLocation());
if (farm == null) continue;
toCancel.add(block);
}
for (Block block : toCancel) {
event.blockList().remove(block);
Farm farm = instance.getFarmManager().removeFarm(block.getLocation());
instance.getFarmTask().getCrops(farm, false);
ItemStack item = instance.makeFarmItem(farm.getLevel());
block.setType(Material.AIR);
block.getLocation().getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item);
for (ItemStack itemStack : farm.getItems()) {
farm.getLocation().getWorld().dropItemNaturally(farm.getLocation().add(.5, .5, .5), itemStack);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
if (event.getBlock().getType() != Settings.FARM_BLOCK_MATERIAL.getMaterial(CompatibleMaterial.END_ROD).getMaterial())
@ -237,7 +165,7 @@ public class BlockListeners implements Listener {
Farm farm = instance.getFarmManager().removeFarm(event.getBlock().getLocation());
if (farm == null) return;
instance.getFarmTask().getCrops(farm, false);
ModuleAutoCollect.getCrops(farm, false);
event.setCancelled(true);

View File

@ -0,0 +1,120 @@
package com.songoda.epicfarming.listeners;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.farming.levels.modules.Module;
import com.songoda.epicfarming.farming.levels.modules.ModuleAutoCollect;
import com.songoda.epicfarming.settings.Settings;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.SheepRegrowWoolEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class EntityListeners implements Listener {
private EpicFarming instance;
public EntityListeners(EpicFarming instance) {
this.instance = instance;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDeath(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
if (!entity.hasMetadata("EFA-TAGGED")) return;
Location location = (Location) entity.getMetadata("EFA-TAGGED").get(0).value();
Farm farm = instance.getFarmManager().getFarm(location);
boolean autoCollect = false;
for (Module module : farm.getLevel().getRegisteredModules()) {
if (module instanceof ModuleAutoCollect && ((ModuleAutoCollect) module).isEnabled(farm))
autoCollect = true;
}
if (autoCollect) {
for (ItemStack item : event.getDrops())
farm.addItem(item);
event.getDrops().clear();
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
if (item.getItemStack().getType() != Material.EGG) return;
Location location = event.getEntity().getLocation();
Collection<Entity> nearby = location.getWorld().getNearbyEntities(location, 0.01, 0.3, 0.01);
Entity entity = null;
for (Entity e : nearby) {
if (e instanceof Player) return;
if (e instanceof Chicken) entity = e;
}
if (ModuleAutoCollect.getTicksLived().containsKey(entity)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSpawn(SheepRegrowWoolEvent event) {
if (ModuleAutoCollect.getTicksLived().containsKey(event.getEntity())) {
event.setCancelled(true);
Block block = event.getEntity().getLocation().getBlock().getRelative(BlockFace.DOWN);
if (block.getType() == Material.DIRT) {
block.setType(Material.GRASS_BLOCK);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlow(EntityExplodeEvent event) {
List<Block> destroyed = event.blockList();
Iterator<Block> it = destroyed.iterator();
List<Block> toCancel = new ArrayList<>();
while (it.hasNext()) {
Block block = it.next();
if (block.getType() != Settings.FARM_BLOCK_MATERIAL.getMaterial(CompatibleMaterial.END_ROD).getMaterial())
continue;
Farm farm = instance.getFarmManager().getFarm(block.getLocation());
if (farm == null) continue;
toCancel.add(block);
}
for (Block block : toCancel) {
event.blockList().remove(block);
Farm farm = instance.getFarmManager().removeFarm(block.getLocation());
ModuleAutoCollect.getCrops(farm, false);
ItemStack item = instance.makeFarmItem(farm.getLevel());
block.setType(Material.AIR);
block.getLocation().getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item);
for (ItemStack itemStack : farm.getItems()) {
farm.getLocation().getWorld().dropItemNaturally(farm.getLocation().add(.5, .5, .5), itemStack);
}
}
}
}

View File

@ -22,13 +22,10 @@ public class Settings {
public static final ConfigSetting PARTICLE_TYPE = new ConfigSetting(config, "Main.Upgrade Particle Type", "SPELL_WITCH",
"The type of particle shown when a furnace is upgraded.");
public static final ConfigSetting FARM_TICK_SPEED = new ConfigSetting(config, "Main.Farm Tick Speed", 70,
public static final ConfigSetting FARM_TICK_SPEED = new ConfigSetting(config, "Main.Farm Tick Speed", 20,
"The delay in ticks between each farm growth event.");
public static final ConfigSetting ENTITY_TICK_SPEED = new ConfigSetting(config, "Main.Entity Tick Speed", 100,
"The delay in ticks between each farm entity event.");
public static final ConfigSetting GROWTH_TICK_SPEED = new ConfigSetting(config, "Main.Growth Tick Speed", 20,
public static final ConfigSetting GROWTH_TICK_SPEED = new ConfigSetting(config, "Main.Growth Tick Speed", 70,
"The delay in ticks between each farm entity event.");
public static final ConfigSetting FARM_BLOCK_MATERIAL = new ConfigSetting(config, "Main.Farm Block Material", ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9) ? "END_ROD" : "TORCH",
@ -37,9 +34,6 @@ public class Settings {
public static final ConfigSetting NON_COMMAND_FARMS = new ConfigSetting(config, "Main.Allow Non Command Issued Farm Items", false,
"Should farm item materials found in the wild work as farms?");
public static final ConfigSetting AUTO_BREEDING_CAP = new ConfigSetting(config, "Main.Auto Breeding Cap", 15,
"How many entities should auto breeding stop at?");
public static final ConfigSetting ANIMATE = new ConfigSetting(config, "Main.Animate", true,
"Should the processed farm item be animated above the farm item?");
@ -81,6 +75,10 @@ public class Settings {
config.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
}
if (Settings.FARM_TICK_SPEED.getInt() == 70)
config.set(FARM_TICK_SPEED.getKey(), 20);
config.saveChanges();
}
}

View File

@ -34,6 +34,7 @@ public abstract class Storage {
|| farm.getLocation().getWorld() == null) continue;
String locstr = Methods.serializeLocation(farm.getLocation());
prepareSaveItem("farms", new StorageItem("location", locstr),
new StorageItem("farmtype", farm.getFarmType().name()),
new StorageItem("level", farm.getLevel().getLevel()),
new StorageItem("placedby", farm.getPlacedBy() == null ? null : farm.getPlacedBy().toString()),
new StorageItem("contents", farm.getItems()));

View File

@ -1,224 +0,0 @@
package com.songoda.epicfarming.tasks;
import com.songoda.core.hooks.EntityStackerManager;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.boost.BoostData;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.settings.Settings;
import com.songoda.epicfarming.utils.EntityInfo;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Wool;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.stream.Collectors;
public class EntityTask extends BukkitRunnable {
private static final Random random = new Random();
private static Map<Entity, Integer> lastTicksLived = new HashMap<>();
private static final Map<Entity, Integer> ticksLived = new HashMap<>();
private static EntityTask instance;
private static EpicFarming plugin;
private final int autoBreedCap = Settings.AUTO_BREEDING_CAP.getInt();
public static EntityTask startTask(EpicFarming pl) {
if (instance != null && !instance.isCancelled()) {
instance.cancel();
}
instance = new EntityTask();
instance.runTaskTimer(plugin = pl, 0, Settings.ENTITY_TICK_SPEED.getInt());
return instance;
}
@Override
public void run() {
for (Farm farm : plugin.getFarmManager().getFarms().values()) {
if (farm.getLocation() == null) continue;
Location location = farm.getLocation();
location.add(.5, .5, .5);
double radius = farm.getLevel().getRadius() + .5;
Collection<LivingEntity> amt = location.getWorld().getNearbyEntities(location, radius, radius, radius)
.stream().filter(e -> !(e instanceof Player) && e instanceof LivingEntity && !(e instanceof ArmorStand))
.map(entity -> (LivingEntity) entity).collect(Collectors.toCollection(ArrayList::new));
if (farm.getLevel().isAutoBreeding()) doAutoBreeding(farm, amt);
for (Entity entity : amt) {
if (!ticksLived.containsKey(entity)) ticksLived.put(entity, 0);
int lived = ticksLived.get(entity);
ticksLived.put(entity, lived + 100);
int min = (int) Math.floor(getMin(entity) / farm.getLevel().getSpeedMultiplier());
int max = (int) Math.floor(getMax(entity) / farm.getLevel().getSpeedMultiplier());
int rand = random.nextInt((int) Math.floor(100 / farm.getLevel().getSpeedMultiplier()));
if (lived < min) continue;
if (rand != 5 && lived < max) continue;
if (entity instanceof Chicken) {
if (!((Ageable) entity).isAdult()) continue;
entity.getLocation().getWorld().playSound(entity.getLocation(), Sound.ENTITY_CHICKEN_EGG, 1, 2);
if (!farm.getLevel().isAutoHarvest()) {
ticksLived.remove(entity);
entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemStack(Material.EGG));
} else {
doDrop(farm, new ItemStack(Material.EGG, 1));
}
Methods.animate(farm.getLocation(), Material.EGG);
} else if (entity instanceof Sheep) {
if (!((Ageable) entity).isAdult()) continue;
((Sheep) entity).setSheared(true);
Wool woolColor = new Wool(((Sheep) entity).getColor());
ItemStack wool = woolColor.toItemStack((int) Math.round(1 + (Math.random() * 3)));
if (!farm.getLevel().isAutoHarvest()) {
entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), wool);
} else {
doDrop(farm, wool);
}
Methods.animate(farm.getLocation(), wool.getType());
}
ticksLived.put(entity, 0);
}
}
for (Map.Entry<Entity, Integer> entry : lastTicksLived.entrySet()) {
int last = entry.getValue();
if (!ticksLived.containsKey(entry.getKey())) continue;
int current = ticksLived.get(entry.getKey());
if (last == current) {
ticksLived.remove(entry.getKey());
}
}
lastTicksLived = new HashMap<>(ticksLived);
}
private int getMin(Entity entity) {
switch (entity.getType()) {
case SHEEP:
return 0;
case CHICKEN:
return 6000;
default:
return 0;
}
}
private int getMax(Entity entity) {
switch (entity.getType()) {
case SHEEP:
return 6000;
case CHICKEN:
return 12000;
default:
return 0;
}
}
private void doAutoBreeding(Farm farm, Collection<LivingEntity> entities1) {
List<LivingEntity> entities = new ArrayList<>(entities1);
Collections.shuffle(entities);
entities.removeIf(e -> !(e instanceof Ageable) || !((Ageable) e).isAdult());
Map<EntityType, Long> counts =
entities.stream().collect(Collectors.groupingBy(Entity::getType, Collectors.counting()));
for (LivingEntity entity : entities) {
counts.put(entity.getType(),
counts.get(entity.getType()) - 1 + EntityStackerManager.getSize(entity));
}
boolean mate1 = false;
for (Map.Entry<EntityType, Long> entry : counts.entrySet()) {
for (LivingEntity entity : entities) {
if (entry.getKey() != entity.getType()) continue;
if (mate1) {
int count = EntityStackerManager.getSize(entity);
if (count > 1)
handleStackedBreed(entity);
else
handleBreed(entity);
return;
}
if (entry.getValue() >= 2 && entry.getValue() < autoBreedCap) {
EntityType entityType = entry.getKey();
for (ItemStack item : farm.getItems()) {
try {
if (item.getType() != EntityInfo.valueOf(entityType.name()).getMaterial() || item.getAmount() < 2)
continue;
} catch (IllegalArgumentException e) {
continue;
}
farm.removeMaterial(item.getType(), 2);
Location location = entity.getLocation();
Entity newSpawn = location.getWorld().spawnEntity(location, entityType);
((Ageable) newSpawn).setBaby();
int count = EntityStackerManager.getSize(entity);
if (count > 1) {
handleStackedBreed(entity);
if (count - 1 > 1) {
handleStackedBreed(entity);
} else {
handleBreed(entity);
}
return;
}
handleBreed(entity);
mate1 = true;
}
}
}
}
}
private void handleStackedBreed(LivingEntity entity) {
EntityStackerManager.removeOne(entity);
LivingEntity spawned = (LivingEntity) entity.getWorld().spawnEntity(entity.getLocation(), entity.getType());
handleBreed(spawned);
}
private void handleBreed(Entity entity) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () ->
entity.removeMetadata("breedCooldown", plugin), 5 * 20 * 60);
entity.setMetadata("breedCooldown", new FixedMetadataValue(plugin, true));
}
private boolean doDrop(Farm farm, ItemStack stack) {
BoostData boostData = plugin.getBoostManager().getBoost(farm.getPlacedBy());
stack.setAmount(stack.getAmount() * (boostData == null ? 1 : boostData.getMultiplier()));
if (!farm.willFit(stack)) return false;
farm.addItem(stack);
return true;
}
public Map<Entity, Integer> getTicksLived() {
return Collections.unmodifiableMap(ticksLived);
}
}

View File

@ -1,124 +1,58 @@
package com.songoda.epicfarming.tasks;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.utils.BlockUtils;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.boost.BoostData;
import com.songoda.epicfarming.farming.Crop;
import com.songoda.epicfarming.farming.Farm;
import com.songoda.epicfarming.settings.Settings;
import com.songoda.epicfarming.utils.CropType;
import com.songoda.epicfarming.utils.Methods;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.inventory.Inventory;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.*;
import java.util.stream.Collectors;
public class FarmTask extends BukkitRunnable {
private static FarmTask instance;
private static EpicFarming plugin;
Random random = new Random();
public static FarmTask startTask(EpicFarming pl) {
if (instance != null && !instance.isCancelled()) {
instance.cancel();
}
instance = new FarmTask();
instance.runTaskTimer(plugin = pl, 0, Settings.GROWTH_TICK_SPEED.getInt());
instance.runTaskTimer(plugin = pl, 0, Settings.FARM_TICK_SPEED.getInt());
return instance;
}
@Override
public void run() {
HashMap<Material, Boolean> hasDropped = new HashMap();
for (Farm farm : plugin.getFarmManager().getFarms().values()) {
if (!farm.isInLoadedChunk()) continue;
hasDropped.clear();
Location location = farm.getLocation();
location.add(.5, .5, .5);
for (Block block : getCrops(farm, true)) {
Material mat = block.getType();
if (!CropType.isCrop(mat)) continue;
double radius = farm.getLevel().getRadius() + .5;
Collection<LivingEntity> entitiesAroundFarm = location.getWorld().getNearbyEntities(location, radius, radius, radius)
.stream().filter(e -> !(e instanceof Player) && e instanceof LivingEntity && !(e instanceof ArmorStand))
.map(entity -> (LivingEntity) entity).collect(Collectors.toCollection(ArrayList::new));
if (!BlockUtils.isCropFullyGrown(block)) {
// Add to GrowthTask
plugin.getGrowthTask().addLiveCrop(block.getLocation(), new Crop(block.getLocation(), farm));
} else if (farm.getLevel().isAutoHarvest() && !hasDropped.getOrDefault(mat, false) && doDrop(farm, mat)) {
hasDropped.put(mat, true);
if (farm.getLevel().isAutoReplant()) {
BlockUtils.resetGrowthStage(block);
continue;
}
block.setType(Material.AIR);
}
}
// Cycle through modules.
farm.getLevel().getRegisteredModules().stream()
.filter(module -> module != null)
.forEach(module -> {
// Run Module
module.run(farm, entitiesAroundFarm);
});
}
}
private boolean doDrop(Farm farm, Material material) {
CropType cropTypeData = CropType.getCropType(material);
if (material == null || farm == null || cropTypeData == null) return false;
BoostData boostData = plugin.getBoostManager().getBoost(farm.getPlacedBy());
ItemStack stack = new ItemStack(cropTypeData.getYieldMaterial(), (useBoneMeal(farm) ? random.nextInt(2) + 2 : 1) * (boostData == null ? 1 : boostData.getMultiplier()));
ItemStack seedStack = new ItemStack(cropTypeData.getSeedMaterial(), random.nextInt(3) + 1 + (useBoneMeal(farm) ? 1 : 0));
if (!farm.willFit(stack) || !farm.willFit(seedStack)) return false;
Methods.animate(farm.getLocation(), cropTypeData.getYieldMaterial());
farm.addItem(stack);
farm.addItem(seedStack);
return true;
}
private boolean useBoneMeal(Farm farm) {
for (ItemStack item : farm.getItems()) {
if (item.getType() != CompatibleMaterial.BONE_MEAL.getMaterial()) continue;
farm.removeMaterial(CompatibleMaterial.BONE_MEAL.getMaterial(), 1);
return true;
}
return false;
}
public List<Block> getCrops(Farm farm, boolean add) {
if (((System.currentTimeMillis() - farm.getLastCached()) > (30 * 1000)) || !add) {
farm.setLastCached(System.currentTimeMillis());
if (add) farm.clearCache();
Block block = farm.getLocation().getBlock();
int radius = farm.getLevel().getRadius();
int bx = block.getX();
int by = block.getY();
int bz = block.getZ();
for (int fx = -radius; fx <= radius; fx++) {
for (int fy = -2; fy <= 1; fy++) {
for (int fz = -radius; fz <= radius; fz++) {
Block b2 = block.getWorld().getBlockAt(bx + fx, by + fy, bz + fz);
CompatibleMaterial mat = CompatibleMaterial.getMaterial(b2.getType());
if (!mat.isCrop()) continue;
if (add) {
farm.addCachedCrop(b2);
continue;
}
farm.removeCachedCrop(b2);
plugin.getGrowthTask().removeCropByLocation(b2.getLocation());
}
}
}
}
return farm.getCachedCrops();
}
}

View File

@ -3,6 +3,7 @@ package com.songoda.epicfarming.tasks;
import com.songoda.core.utils.BlockUtils;
import com.songoda.epicfarming.EpicFarming;
import com.songoda.epicfarming.farming.Crop;
import com.songoda.epicfarming.farming.FarmType;
import com.songoda.epicfarming.settings.Settings;
import com.songoda.epicfarming.utils.CropType;
import org.bukkit.Location;
@ -23,7 +24,7 @@ public class GrowthTask extends BukkitRunnable {
instance.cancel();
}
instance = new GrowthTask();
instance.runTaskTimer(plugin, 0, Settings.FARM_TICK_SPEED.getInt());
instance.runTaskTimer(plugin, 0, Settings.GROWTH_TICK_SPEED.getInt());
return instance;
}
@ -32,6 +33,7 @@ public class GrowthTask extends BukkitRunnable {
List<Crop> toRemove = new ArrayList<>();
for (Crop crop : liveCrops.values()) {
if (crop.getFarm().getFarmType() == FarmType.LIVESTOCK) continue;
Location cropLocation = crop.getLocation();
int x = cropLocation.getBlockX() >> 4;

View File

@ -5,6 +5,12 @@ general.nametag.farm = "&eLevel %level% &fFarm"
general.nametag.lore = ""
general.interface.next = "Next"
general.interface.previous = "Previous"
general.interface.unlocked = "Unlocked"
general.interface.on = "On"
general.interface.off = "Off"
general.interface.both = "Both"
general.interface.crops = "Crops"
general.interface.livestock = "Livestock"
#Interface Messages
@ -15,11 +21,15 @@ interface.button.upgradewitheconomylore = "&7Cost: &a$%cost%"
interface.button.level = "&6Next Level &7%level%"
interface.button.radius = "&7Radius: &6%radius%"
interface.button.speed = "&7Speed: &6%speed%x"
interface.button.autoharvest = "&7Auto Harvest: &6%status%"
interface.button.autocollect = "&7Auto Collect: &6%status%"
interface.button.autoreplant = "&7Auto Replant: &6%status%"
interface.button.autobreeding = "&7Auto Breeding: &6%status%"
interface.button.autobutcher = "&7Auto Butcher: &6%status%"
interface.button.pages = "&7Pages: &6%amount%"
interface.button.boostedstats = "&a&lCurrently boosted!|&7Yield rate multiplied by &6%amount%x&7.|&7Expires in &6%time%&7."
interface.button.farmtype = "&7Farm type: &6%type%"
interface.button.farmtypelore = "&7Click to switch your farm type."
interface.button.functiontoggle = "&7Click to toggle this function."
#Command Messages

View File

@ -14,7 +14,7 @@ Level-3:
Speed-Multiplier: 1.5
Auto-Harvest: true
Auto-Replant: true
Auto-Breeding: true
Auto-Breeding: 5
Cost-xp: 25
Cost-eco: 7500
Level-4:
@ -22,7 +22,8 @@ Level-4:
Speed-Multiplier: 2
Auto-Harvest: true
Auto-Replant: true
Auto-Breeding: true
Auto-Breeding: 10
Auto-Butcher: 25
Pages: 2
Cost-xp: 30
Cost-eco: 10000
@ -31,7 +32,8 @@ Level-5:
Speed-Multiplier: 2.5
Auto-Harvest: true
Auto-Replant: true
Auto-Breeding: true
Auto-Breeding: 15
Auto-Butcher: 20
Pages: 2
Cost-xp: 35
Cost-eco: 12000
@ -40,7 +42,8 @@ Level-6:
Speed-Multiplier: 3
Auto-Harvest: true
Auto-Replant: true
Auto-Breeding: true
Auto-Breeding: 20
Auto-Butcher: 15
Pages: 2
Cost-xp: 40
Cost-eco: 25000