Version 1.4.0:

* Added 1.18 and 1.18.1 support
* Migrated to NBT-API (thanks Jowcey!)
* Added MaxUses setting (thanks Jowcey!)
* Added fixed price and currency settings for both ingredients (Item1 and Item2) of a trade (thanks Jowcey!)
* Fixed config updater (thanks tchristofferson!)
* Updated readme
This commit is contained in:
PretzelJohn 2021-12-15 15:30:01 -05:00
parent 1d680d581d
commit 98be139384
11 changed files with 422 additions and 201 deletions

3
.gitignore vendored
View File

@ -7,4 +7,5 @@ bin
.classpath
*.iml
/.idea/
/.git/
/.git/
/out/

View File

@ -124,6 +124,18 @@
<td><code>.MaxDemand:</code></td>
<td>Sets the maximum demand for this item (-1, or 0+)</td>
</tr>
<tr>
<td><code>.MaxUses:</code></td>
<td>Sets the maximum number of times a player can make the trade before the villager is out of stock</td>
</tr>
<tr>
<td><code>.Item1.Material:</code><br><code>.Item2.Material:</code></td>
<td>Sets the material of the 1st or 2nd item in the trade</td>
</tr>
<tr>
<td><code>.Item1.Amount:</code><br><code>.Item2.Amount:</code></td>
<td>Sets the amount of the 1st or 2nd item in the trade</td>
</tr>
</table>
</li>
<li>

14
pom.xml
View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.pretzel.dev</groupId>
<artifactId>VillagerTradeLimiter</artifactId>
<version>1.3.0</version>
<version>1.4.0</version>
<properties>
<java.version>1.8</java.version>
@ -37,20 +37,10 @@
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.18-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.17-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<version>1.18.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>

View File

@ -7,10 +7,13 @@ import com.pretzel.dev.villagertradelimiter.lib.Util;
import com.pretzel.dev.villagertradelimiter.listeners.PlayerListener;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
public class VillagerTradeLimiter extends JavaPlugin {
public static final String PLUGIN_NAME = "VillagerTradeLimiter";
@ -43,8 +46,12 @@ public class VillagerTradeLimiter extends JavaPlugin {
//Load config.yml
final String mainPath = this.getDataFolder().getPath()+"/";
final File file = new File(mainPath, "config.yml");
ConfigUpdater updater = new ConfigUpdater(this.getTextResource("config.yml"), file);
this.cfg = updater.updateConfig(file, PREFIX);
try {
ConfigUpdater.update(this, "config.yml", file, Collections.singletonList("Overrides"));
} catch (IOException e) {
Util.errorMsg(e);
}
this.cfg = YamlConfiguration.loadConfiguration(file);
}
private void loadBStats() {

View File

@ -1,83 +1,246 @@
package com.pretzel.dev.villagertradelimiter.lib;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import com.google.common.base.Preconditions;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/*
* Code by tchristofferson
* https://github.com/tchristofferson/Config-Updater
*/
public class ConfigUpdater {
private final String[] cfgDefault;
private String[] cfgActive;
public ConfigUpdater(final Reader def, final File active) {
this.cfgDefault = Util.readFile(def);
this.cfgActive = this.cfgDefault;
try {
this.cfgActive = Util.readFile(new FileReader(active));
} catch (Exception e) {
Util.errorMsg(e);
//Used for separating keys in the keyBuilder inside parseComments method
private static final char SEPARATOR = '.';
public static void update(Plugin plugin, String resourceName, File toUpdate, String... ignoredSections) throws IOException {
update(plugin, resourceName, toUpdate, Arrays.asList(ignoredSections));
}
public static void update(Plugin plugin, String resourceName, File toUpdate, List<String> ignoredSections) throws IOException {
Preconditions.checkArgument(toUpdate.exists(), "The toUpdate file doesn't exist!");
FileConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8));
FileConfiguration currentConfig = YamlConfiguration.loadConfiguration(toUpdate);
Map<String, String> comments = parseComments(plugin, resourceName, defaultConfig);
Map<String, String> ignoredSectionsValues = parseIgnoredSections(toUpdate, currentConfig, comments, ignoredSections == null ? Collections.emptyList() : ignoredSections);
// will write updated config file "contents" to a string
StringWriter writer = new StringWriter();
write(defaultConfig, currentConfig, new BufferedWriter(writer), comments, ignoredSectionsValues);
String value = writer.toString(); // config contents
Path toUpdatePath = toUpdate.toPath();
if (!value.equals(new String(Files.readAllBytes(toUpdatePath), StandardCharsets.UTF_8))) { // if updated contents are not the same as current file contents, update
Files.write(toUpdatePath, value.getBytes(StandardCharsets.UTF_8));
}
}
private String getVersion(String[] cfg) {
for(String x : cfg)
if(x.startsWith("#") && x.endsWith("#") && x.contains("Version: "))
return x.split(": ")[1].replace("#", "").trim();
return "0";
}
private static void write(FileConfiguration defaultConfig, FileConfiguration currentConfig, BufferedWriter writer, Map<String, String> comments, Map<String, String> ignoredSectionsValues) throws IOException {
//Used for converting objects to yaml, then cleared
FileConfiguration parserConfig = new YamlConfiguration();
public FileConfiguration updateConfig(File file, String prefix) {
final FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
if(this.isUpdated()) return cfg;
Util.consoleMsg(prefix+"Updating config.yml...");
keyLoop: for (String fullKey : defaultConfig.getKeys(true)) {
String indents = KeyBuilder.getIndents(fullKey, SEPARATOR);
String out = "";
for(int i = 0; i < cfgDefault.length; i++) {
String line = cfgDefault[i];
if(line.startsWith("#") || line.replace(" ", "").isEmpty()) {
if(!line.startsWith(" ")) out += line+"\n";
} else if(!line.startsWith(" ")) {
if(line.contains(": ")) {
out += matchActive(line.split(": ")[0], line)+"\n";
} else if(line.contains(":")) {
String set = matchActive(line, "");
if(set.contains("none")) {
out += set+"\n";
continue;
}
out += line+"\n";
boolean found = false;
for(String line2 : cfgActive) {
if (line2.startsWith(" ") && !line2.replace(" ", "").isEmpty()) {
out += line2 + "\n";
found = true;
}
}
if(!found) {
while(i < cfgDefault.length-1) {
i++;
String line2 = cfgDefault[i];
out += line2+"\n";
if(!line2.startsWith(" ")) break;
}
if (ignoredSectionsValues.isEmpty()) {
writeCommentIfExists(comments, writer, fullKey, indents);
} else {
for (Map.Entry<String, String> entry : ignoredSectionsValues.entrySet()) {
if (entry.getKey().equals(fullKey)) {
writer.write(entry.getValue() + "\n");
continue keyLoop;
} else if (KeyBuilder.isSubKeyOf(entry.getKey(), fullKey, SEPARATOR)) {
continue keyLoop;
} else {
writeCommentIfExists(comments, writer, fullKey, indents);
}
}
}
Object currentValue = currentConfig.get(fullKey);
if (currentValue == null)
currentValue = defaultConfig.get(fullKey);
String[] splitFullKey = fullKey.split("[" + SEPARATOR + "]");
String trailingKey = splitFullKey[splitFullKey.length - 1];
if (currentValue instanceof ConfigurationSection) {
writer.write(indents + trailingKey + ":");
if (!((ConfigurationSection) currentValue).getKeys(false).isEmpty())
writer.write("\n");
else
writer.write(" {}\n");
continue;
}
parserConfig.set(trailingKey, currentValue);
String yaml = parserConfig.saveToString();
yaml = yaml.substring(0, yaml.length() - 1).replace("\n", "\n" + indents);
String toWrite = indents + yaml + "\n";
parserConfig.set(trailingKey, null);
writer.write(toWrite);
}
Util.writeFile(file, out+"\n");
return YamlConfiguration.loadConfiguration(file);
String danglingComments = comments.get(null);
if (danglingComments != null)
writer.write(danglingComments);
writer.close();
}
public boolean isUpdated() {
return getVersion(cfgActive).contains(getVersion(cfgDefault));
//Returns a map of key comment pairs. If a key doesn't have any comments it won't be included in the map.
private static Map<String, String> parseComments(Plugin plugin, String resourceName, FileConfiguration defaultConfig) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource(resourceName)));
Map<String, String> comments = new LinkedHashMap<>();
StringBuilder commentBuilder = new StringBuilder();
KeyBuilder keyBuilder = new KeyBuilder(defaultConfig, SEPARATOR);
String line;
while ((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
//Only getting comments for keys. A list/array element comment(s) not supported
if (trimmedLine.startsWith("-")) {
continue;
}
if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) {//Is blank line or is comment
commentBuilder.append(trimmedLine).append("\n");
} else {//is a valid yaml key
keyBuilder.parseLine(trimmedLine);
String key = keyBuilder.toString();
//If there is a comment associated with the key it is added to comments map and the commentBuilder is reset
if (commentBuilder.length() > 0) {
comments.put(key, commentBuilder.toString());
commentBuilder.setLength(0);
}
//Remove the last key from keyBuilder if current path isn't a config section or if it is empty to prepare for the next key
if (!keyBuilder.isConfigSectionWithKeys()) {
keyBuilder.removeLastKey();
}
}
}
reader.close();
if (commentBuilder.length() > 0)
comments.put(null, commentBuilder.toString());
return comments;
}
private String matchActive(String start, String def) {
for(String x : cfgActive)
if(x.startsWith(start))
return x;
return def;
private static Map<String, String> parseIgnoredSections(File toUpdate, FileConfiguration currentConfig, Map<String, String> comments, List<String> ignoredSections) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(toUpdate));
Map<String, String> ignoredSectionsValues = new LinkedHashMap<>(ignoredSections.size());
KeyBuilder keyBuilder = new KeyBuilder(currentConfig, SEPARATOR);
StringBuilder valueBuilder = new StringBuilder();
String currentIgnoredSection = null;
String line;
lineLoop : while ((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
if (trimmedLine.isEmpty() || trimmedLine.startsWith("#"))
continue;
if (trimmedLine.startsWith("-")) {
for (String ignoredSection : ignoredSections) {
boolean isIgnoredParent = ignoredSection.equals(keyBuilder.toString());
if (isIgnoredParent || keyBuilder.isSubKeyOf(ignoredSection)) {
valueBuilder.append("\n").append(line);
continue lineLoop;
}
}
}
keyBuilder.parseLine(trimmedLine);
String fullKey = keyBuilder.toString();
//If building the value for an ignored section and this line is no longer a part of the ignored section,
// write the valueBuilder, reset it, and set the current ignored section to null
if (currentIgnoredSection != null && !KeyBuilder.isSubKeyOf(currentIgnoredSection, fullKey, SEPARATOR)) {
ignoredSectionsValues.put(currentIgnoredSection, valueBuilder.toString());
valueBuilder.setLength(0);
currentIgnoredSection = null;
}
for (String ignoredSection : ignoredSections) {
boolean isIgnoredParent = ignoredSection.equals(fullKey);
if (isIgnoredParent || keyBuilder.isSubKeyOf(ignoredSection)) {
if (valueBuilder.length() > 0)
valueBuilder.append("\n");
String comment = comments.get(fullKey);
if (comment != null) {
String indents = KeyBuilder.getIndents(fullKey, SEPARATOR);
valueBuilder.append(indents).append(comment.replace("\n", "\n" + indents));//Should end with new line (\n)
valueBuilder.setLength(valueBuilder.length() - indents.length());//Get rid of trailing \n and spaces
}
valueBuilder.append(line);
//Set the current ignored section for future iterations of while loop
//Don't set currentIgnoredSection to any ignoredSection sub-keys
if (isIgnoredParent)
currentIgnoredSection = fullKey;
break;
}
}
}
reader.close();
if (valueBuilder.length() > 0)
ignoredSectionsValues.put(currentIgnoredSection, valueBuilder.toString());
return ignoredSectionsValues;
}
private static void writeCommentIfExists(Map<String, String> comments, BufferedWriter writer, String fullKey, String indents) throws IOException {
String comment = comments.get(fullKey);
//Comments always end with new line (\n)
if (comment != null)
//Replaces all '\n' with '\n' + indents except for the last one
writer.write(indents + comment.substring(0, comment.length() - 1).replace("\n", "\n" + indents) + "\n");
}
//Input: 'key1.key2' Result: 'key1'
private static void removeLastKey(StringBuilder keyBuilder) {
if (keyBuilder.length() == 0)
return;
String keyString = keyBuilder.toString();
//Must be enclosed in brackets in case a regex special character is the separator
String[] split = keyString.split("[" + SEPARATOR + "]");
//Makes sure begin index isn't < 0 (error). Occurs when there is only one key in the path
int minIndex = Math.max(0, keyBuilder.length() - split[split.length - 1].length() - 1);
keyBuilder.replace(minIndex, keyBuilder.length(), "");
}
private static void appendNewLine(StringBuilder builder) {
if (builder.length() > 0)
builder.append("\n");
}
}

View File

@ -0,0 +1,120 @@
package com.pretzel.dev.villagertradelimiter.lib;
import org.bukkit.configuration.file.FileConfiguration;
/*
* Code by tchristofferson
* https://github.com/tchristofferson/Config-Updater
*/
public class KeyBuilder implements Cloneable {
private final FileConfiguration config;
private final char separator;
private final StringBuilder builder;
public KeyBuilder(FileConfiguration config, char separator) {
this.config = config;
this.separator = separator;
this.builder = new StringBuilder();
}
private KeyBuilder(KeyBuilder keyBuilder) {
this.config = keyBuilder.config;
this.separator = keyBuilder.separator;
this.builder = new StringBuilder(keyBuilder.toString());
}
public void parseLine(String line) {
line = line.trim();
String[] currentSplitLine = line.split(":");
//Checks keyBuilder path against config to see if the path is valid.
//If the path doesn't exist in the config it keeps removing last key in keyBuilder.
while (builder.length() > 0 && !config.contains(builder.toString() + separator + currentSplitLine[0])) {
removeLastKey();
}
//Add the separator if there is already a key inside keyBuilder
//If currentSplitLine[0] is 'key2' and keyBuilder contains 'key1' the result will be 'key1.' if '.' is the separator
if (builder.length() > 0)
builder.append(separator);
//Appends the current key to keyBuilder
//If keyBuilder is 'key1.' and currentSplitLine[0] is 'key2' the resulting keyBuilder will be 'key1.key2' if separator is '.'
builder.append(currentSplitLine[0]);
}
public String getLastKey() {
if (builder.length() == 0)
return "";
return builder.toString().split("[" + separator + "]")[0];
}
public boolean isEmpty() {
return builder.length() == 0;
}
//Checks to see if the full key path represented by this instance is a sub-key of the key parameter
public boolean isSubKeyOf(String parentKey) {
return isSubKeyOf(parentKey, builder.toString(), separator);
}
//Checks to see if subKey is a sub-key of the key path this instance represents
public boolean isSubKey(String subKey) {
return isSubKeyOf(builder.toString(), subKey, separator);
}
public static boolean isSubKeyOf(String parentKey, String subKey, char separator) {
if (parentKey.isEmpty())
return false;
return subKey.startsWith(parentKey)
&& subKey.substring(parentKey.length()).startsWith(String.valueOf(separator));
}
public static String getIndents(String key, char separator) {
String[] splitKey = key.split("[" + separator + "]");
StringBuilder builder = new StringBuilder();
for (int i = 1; i < splitKey.length; i++) {
builder.append(" ");
}
return builder.toString();
}
public boolean isConfigSection() {
String key = builder.toString();
return config.isConfigurationSection(key);
}
public boolean isConfigSectionWithKeys() {
String key = builder.toString();
return config.isConfigurationSection(key) && !config.getConfigurationSection(key).getKeys(false).isEmpty();
}
//Input: 'key1.key2' Result: 'key1'
public void removeLastKey() {
if (builder.length() == 0)
return;
String keyString = builder.toString();
//Must be enclosed in brackets in case a regex special character is the separator
String[] split = keyString.split("[" + separator + "]");
//Makes sure begin index isn't < 0 (error). Occurs when there is only one key in the path
int minIndex = Math.max(0, builder.length() - split[split.length - 1].length() - 1);
builder.replace(minIndex, builder.length(), "");
}
@Override
public String toString() {
return builder.toString();
}
@Override
protected KeyBuilder clone() {
return new KeyBuilder(this);
}
}

View File

@ -2,21 +2,14 @@ package com.pretzel.dev.villagertradelimiter.lib;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import net.md_5.bungee.api.ChatColor;
@ -102,50 +95,4 @@ public class Util {
errorMsg(e);
}
}
public static final String stacksToBase64(final ItemStack[] contents) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeInt(contents.length);
for (ItemStack stack : contents) dataOutput.writeObject(stack);
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray()).replace("\n", "").replace("\r", "");
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
public static final ItemStack[] stacksFromBase64(final String data) {
if (data == null || Base64Coder.decodeLines(data).equals(null))
return new ItemStack[]{};
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = null;
ItemStack[] stacks = null;
try {
dataInput = new BukkitObjectInputStream(inputStream);
stacks = new ItemStack[dataInput.readInt()];
} catch (IOException e) {
Util.errorMsg(e);
}
for (int i = 0; i < stacks.length; i++) {
try {
stacks[i] = (ItemStack) dataInput.readObject();
} catch (IOException | ClassNotFoundException e) {
try { dataInput.close(); }
catch (IOException ignored) {}
Util.errorMsg(e);
return null;
}
}
try { dataInput.close(); }
catch (IOException ignored) {}
return stacks;
}
}

View File

@ -3,6 +3,7 @@ package com.pretzel.dev.villagertradelimiter.listeners;
import com.pretzel.dev.villagertradelimiter.VillagerTradeLimiter;
import com.pretzel.dev.villagertradelimiter.lib.Util;
import com.pretzel.dev.villagertradelimiter.nms.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection;
@ -13,22 +14,27 @@ import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PlayerListener implements Listener {
private static final Material[] MATERIALS = new Material[] { Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.BELL, Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.SHIELD, Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.FILLED_MAP, Material.FISHING_ROD, Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.LEATHER_HORSE_ARMOR, Material.SADDLE, Material.ENCHANTED_BOOK, Material.STONE_AXE, Material.STONE_SHOVEL, Material.STONE_PICKAXE, Material.STONE_HOE, Material.IRON_AXE, Material.IRON_SHOVEL, Material.IRON_PICKAXE, Material.DIAMOND_AXE, Material.DIAMOND_SHOVEL, Material.DIAMOND_PICKAXE, Material.DIAMOND_HOE, Material.IRON_SWORD, Material.DIAMOND_SWORD, Material.NETHERITE_AXE, Material.NETHERITE_HOE, Material.NETHERITE_PICKAXE, Material.NETHERITE_SHOVEL, Material.NETHERITE_SWORD, Material.NETHERITE_HELMET, Material.NETHERITE_CHESTPLATE, Material.NETHERITE_LEGGINGS, Material.NETHERITE_BOOTS };
private final VillagerTradeLimiter instance;
private final HashMap<Villager, List<MerchantRecipe>> originalRecipes;
public PlayerListener(VillagerTradeLimiter instance) {
this.instance = instance;
this.originalRecipes = new HashMap<>();
}
//Handles villager trading event
@EventHandler
public void onPlayerInteract(PlayerInteractEntityEvent event) {
if(!(event.getRightClicked() instanceof Villager)) return;
@ -56,71 +62,10 @@ public class PlayerListener implements Listener {
final Player player = event.getPlayer();
if(Util.isNPC(player)) return; //Skips NPCs
this.hotv(player);
this.setIngredients(villager);
this.setData(villager);
this.maxDiscount(villager, player);
this.maxDemand(villager);
}
private void setIngredients(final Villager villager) {
final ConfigurationSection overrides = instance.getCfg().getConfigurationSection("Overrides");
final NBTEntity villagerNBT = new NBTEntity(villager);
NBTCompoundList recipes = villagerNBT.getCompound("Offers").getCompoundList("Recipes");
for (NBTCompound recipe : recipes) {
if(overrides != null) {
for(final String override : overrides.getKeys(false)) {
final ConfigurationSection item = this.getItem(recipe, override);
if(item != null) {
if (item.contains("item-1-material"))
recipe.getCompound("buy").setString("id", "minecraft:" + item.getString("item-1-material"));
if (item.contains("item-2-material"))
recipe.getCompound("buyB").setString("id", "minecraft:" + item.getString("item-2-material"));
if (recipe.getCompound("buy").getString("id") != "minecraft:air" && item.contains("item-1-amount")) {
int cost = item.getInt("item-1-amount");
if (cost <= 0)
cost = 1;
else if (cost > 64)
cost = 64;
recipe.getCompound("buy").setInteger("Count", cost);
}
if (recipe.getCompound("buyB").getString("id") != "minecraft:air" && item.contains("item-2-amount")) {
int cost2 = item.getInt("item-2-amount");
if (cost2 <= 0)
cost2 = 1;
else if (cost2 > 64)
cost2 = 64;
recipe.getCompound("buyB").setInteger("Count", cost2);
}
break;
}
}
}
}
}
private void setData(final Villager villager) {
final ConfigurationSection overrides = instance.getCfg().getConfigurationSection("Overrides");
final NBTEntity villagerNBT = new NBTEntity(villager);
NBTCompoundList recipes = villagerNBT.getCompound("Offers").getCompoundList("Recipes");
for (NBTCompound recipe : recipes) {
if(overrides != null) {
for(final String override : overrides.getKeys(false)) {
final ConfigurationSection item = this.getItem(recipe, override);
if(item != null) {
if (item.contains("uses")) {
int uses = item.getInt("uses");
if (uses > 0)
recipe.setInteger("maxUses", uses);
}
break;
}
}
}
}
}
//Hero of the Village effect limiter feature
private void hotv(final Player player) {
final PotionEffectType effect = PotionEffectType.HERO_OF_THE_VILLAGE;
@ -131,12 +76,27 @@ public class PlayerListener implements Listener {
if(maxHeroLevel <= 0) return; //Skips when disabled in config.yml
final PotionEffect pot = player.getPotionEffect(effect);
if(pot == null) return;
if(pot.getAmplifier() > maxHeroLevel-1) {
player.removePotionEffect(effect);
player.addPotionEffect(new PotionEffect(effect, pot.getDuration(), maxHeroLevel-1));
}
}
//Sets an ingredient for a trade
private void setIngredient(ConfigurationSection item, NBTCompound recipe, String nbtKey, String itemKey) {
if(!item.contains(itemKey) || recipe.getCompound(nbtKey).getString("id").equals("minecraft:air")) return;
if(item.contains(itemKey+".Material")) {
recipe.getCompound(nbtKey).setString("id", "minecraft:" + item.getString(itemKey+".Material"));
}
if(item.contains(itemKey+".Amount")) {
int cost = item.getInt(itemKey+".Amount");
cost = Math.min(cost, 64);
cost = Math.max(cost, 1);
recipe.getCompound(nbtKey).setInteger("Count", cost);
}
}
//MaxDiscount feature - limits the lowest discounted price to a % of the base price
private void maxDiscount(final Villager villager, final Player player) {
int majorPositiveValue = 0, minorPositiveValue = 0, tradingValue = 0, minorNegativeValue = 0, majorNegativeValue = 0;
@ -144,13 +104,13 @@ public class PlayerListener implements Listener {
NBTEntity nbtEntity = new NBTEntity(villager);
final NBTEntity playerNBT = new NBTEntity(player);
final String playerUUID = Util.intArrayToString(playerNBT.getIntArray("UUID"));
if (nbtEntity.hasKey("Gossips")) {
if(nbtEntity.hasKey("Gossips")) {
NBTCompoundList gossips = nbtEntity.getCompoundList("Gossips");
for (NBTCompound gossip : gossips) {
for(NBTCompound gossip : gossips) {
final String type = gossip.getString("Type");
final String targetUUID = Util.intArrayToString(gossip.getIntArray("Target"));
final int value = gossip.getInteger("Value");
if (targetUUID == playerUUID) {
if(targetUUID.equals(playerUUID)) {
switch (type) {
case "trading": tradingValue = value; break;
case "minor_positive": minorPositiveValue = value; break;
@ -162,8 +122,11 @@ public class PlayerListener implements Listener {
}
}
}
final ConfigurationSection overrides = instance.getCfg().getConfigurationSection("Overrides");
if(!originalRecipes.containsKey(villager)) {
originalRecipes.put(villager, villager.getRecipes());
}
final ConfigurationSection overrides = instance.getCfg().getConfigurationSection("Overrides");
final NBTEntity villagerNBT = new NBTEntity(villager);
NBTCompoundList recipes = villagerNBT.getCompound("Offers").getCompoundList("Recipes");
List<NBTCompound> remove = new ArrayList<>();
@ -178,8 +141,19 @@ public class PlayerListener implements Listener {
for(final String override : overrides.getKeys(false)) {
final ConfigurationSection item = this.getItem(recipe, override);
if(item != null) {
//Set whether trade is disabled and max discount
disabled = item.getBoolean("Disabled", false);
maxDiscount = item.getDouble("MaxDiscount", maxDiscount);
//Set 1st and 2nd ingredients
setIngredient(item, recipe, "buy", "Item1");
setIngredient(item, recipe, "buyB", "Item2");
//Set max uses
if(item.contains("MaxUses")) {
int uses = item.getInt("MaxUses");
if(uses > 0) recipe.setInteger("maxUses", uses);
}
break;
}
}
@ -193,10 +167,10 @@ public class PlayerListener implements Listener {
} else {
recipe.setFloat("priceMultiplier", priceMultiplier);
}
if(disabled)
remove.add(recipe);
if(disabled) remove.add(recipe);
}
remove.forEach(rem -> { recipes.remove(rem); });
remove.forEach(recipes::remove);
Bukkit.getScheduler().runTaskLater(instance, () -> villager.setRecipes(originalRecipes.get(villager)), 1);
}
//MaxDemand feature - limits demand-based price increases

View File

@ -1,6 +1,6 @@
#---------------------------------------------------------------------------------#
# VTL ~ VillagerTradeLimiter #
# Version: 1.3.0 #
# Version: 1.4.0 #
# By: PretzelJohn #
#---------------------------------------------------------------------------------#
@ -11,8 +11,8 @@ bStats: true
# Add world names for worlds that you want to completely disable ALL villager trading. Set to [] to disable this feature.
DisableTrading:
- world_nether
- world_the_end
- world_nether
- world_the_end
# The maximum level of the "Hero of the Village" (HotV) effect that a player can have. This limits HotV price decreases.
# * Set to -1 to disable this feature and keep vanilla behavior.
@ -46,6 +46,13 @@ Overrides:
name_tag:
MaxDiscount: -1.0
MaxDemand: 60
Item1:
Material: "paper"
Amount: 64
Item2:
Material: "ink_sac"
Amount: 32
MaxUses: 64
clock:
MaxDemand: 12
paper:

View File

@ -1,7 +1,7 @@
name: VillagerTradeLimiter
author: PretzelJohn
main: com.pretzel.dev.villagertradelimiter.VillagerTradeLimiter
version: 1.3.0
version: 1.4.0
api-version: 1.14
commands: