diff --git a/README.md b/README.md index 63a67faf4..e54310fc6 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,11 @@ Nouveau plugin collaboratif pour un serveur : VOTRE serveur ! 3. Une fois qu'une fonctionnalité est implémentée et fonctionnelle, créez une pull request. 4. Après approbation, elle sera disponible sur le serveur de développement pour les tests. -Serveur de test : `dev.openmc.fr` (1.21.5 Java Edition) +Serveur de test : `dev.openmc.fr` (1.21.8 Java Edition) -Serveur de la beta : `beta.openmc.fr` (1.21.5 Java Edition) +Serveur de la beta : `beta.openmc.fr` (1.21.8 Java Edition) -Serveur de jeu : `play.openmc.fr` (1.21.5 Java Edition) +Serveur de jeu : `play.openmc.fr` (1.21.8 Java Edition) ## 📘 En apprendre plus. Vous voulez en savoir plus ? Vous voulez avoir des tutoriels à propos d'OpenMC ? @@ -24,9 +24,5 @@ Cliquez [ici](https://github.com/ServerOpenMC/PluginV2/wiki) afin d'accéder au ## 📃 License Projet sous [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/). -## Crédits -Ce projet intègre du code provenant de la repo [SignGUI](https://github.com/Rapha149/SignGUI), spécifiquement de la [Pull Request #30](https://github.com/Rapha149/SignGUI/pull/30) pour la mise à jour de compatibilité avec Minecraft 1.21.5. -La repo originale est sous licence [MIT](https://github.com/Rapha149/SignGUI/blob/main/LICENSE). - --- Merci à @MathiasDPX pour la nouvelle configuration du repo. diff --git a/build.gradle b/build.gradle index 05459f9b2..a25d4061c 100644 --- a/build.gradle +++ b/build.gradle @@ -51,16 +51,17 @@ repositories { } dependencies { - paperweight.paperDevBundle '1.21.5-R0.1-SNAPSHOT' + paperweight.paperDevBundle '1.21.8-R0.1-SNAPSHOT' compileOnly 'com.github.LoneDev6:API-ItemsAdder:3.6.3-beta-14' - compileOnly 'net.luckperms:api:5.4' + compileOnly 'net.luckperms:api:5.5' compileOnly 'me.clip:placeholderapi:2.11.6' - compileOnly 'com.sk89q.worldguard:worldguard-bukkit:7.0.9' - compileOnly 'com.sk89q.worldedit:worldedit-bukkit:7.2.9' - compileOnly 'com.github.dmulloy2:ProtocolLib:5.3.0' - compileOnly 'de.oliver:FancyNpcs:2.5.0' + compileOnly 'com.sk89q.worldguard:worldguard-bukkit:7.0.14' + compileOnly 'com.github.dmulloy2:ProtocolLib:-SNAPSHOT' + compileOnly 'de.oliver:FancyNpcs:2.6.0' + compileOnly 'com.github.dmulloy2:ProtocolLib:5.3.0' + implementation 'org.jetbrains:annotations:24.1.0' implementation 'com.github.Revxrsal.Lamp:common:3.2.1' implementation 'com.github.Revxrsal.Lamp:bukkit:3.2.1' @@ -72,7 +73,6 @@ dependencies { testCompileOnly 'org.projectlombok:lombok:1.18.34' testAnnotationProcessor 'org.projectlombok:lombok:1.18.34' - testImplementation 'com.sk89q.worldedit:worldedit-bukkit:7.2.9' testImplementation 'org.slf4j:slf4j-simple:2.0.16' testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' diff --git a/src/main/java/fr/openmc/api/input/DialogInput.java b/src/main/java/fr/openmc/api/input/DialogInput.java new file mode 100644 index 000000000..ccfdbb0f1 --- /dev/null +++ b/src/main/java/fr/openmc/api/input/DialogInput.java @@ -0,0 +1,58 @@ +package fr.openmc.api.input; + +import fr.openmc.core.utils.dialog.ButtonType; +import io.papermc.paper.dialog.Dialog; +import io.papermc.paper.registry.data.dialog.ActionButton; +import io.papermc.paper.registry.data.dialog.DialogBase; +import io.papermc.paper.registry.data.dialog.action.DialogAction; +import io.papermc.paper.registry.data.dialog.body.DialogBody; +import io.papermc.paper.registry.data.dialog.type.DialogType; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickCallback; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; + +public class DialogInput { + + public static void send(Player player, Component lore, int maxLength, Consumer callback) { + + List body = new ArrayList<>(); + + body.add(DialogBody.plainMessage(lore)); + + Dialog inputDialog = Dialog.create(builder -> builder.empty() + .base(DialogBase.builder(Component.text("Rentrer du Texte")) + .body(body) + .inputs(Arrays.asList( + io.papermc.paper.registry.data.dialog.input.DialogInput + .text("inputtextomc", + Component.text("Rentrer du texte ici") + ) + .maxLength(maxLength) + .build() + ) + ) + .canCloseWithEscape(true) + .build() + ) + .type(DialogType.confirmation( + ActionButton.builder(Component.text(ButtonType.CONFIRM.getLabel())) + .action(DialogAction.customClick((response, audience) -> { + callback.accept(response.getText("inputtextomc")); + }, ClickCallback.Options.builder().build())) + .build(), ActionButton.builder(Component.text(ButtonType.CANCEL.getLabel())) + .action(DialogAction.customClick((response, audience) -> { + callback.accept(null); + }, ClickCallback.Options.builder().build())) + .build() + ) + ) + ); + + player.showDialog(inputDialog); + } +} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignEditor.java b/src/main/java/fr/openmc/api/input/signgui/SignEditor.java deleted file mode 100644 index b9bc38295..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignEditor.java +++ /dev/null @@ -1,37 +0,0 @@ -package fr.openmc.api.input.signgui; - -import io.netty.channel.ChannelPipeline; -import org.bukkit.Location; - -// Ce code est basé sur le fichier SignEditor.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -public class SignEditor { - - private final Object sign; - private final Location location; - private final Object blockPosition; - private final ChannelPipeline pipeline; - - public SignEditor(Object sign, Location location, Object blockPosition, ChannelPipeline pipeline) { - this.sign = sign; - this.location = location; - this.blockPosition = blockPosition; - this.pipeline = pipeline; - } - - public Object getSign() { - return sign; - } - - public Location getLocation() { - return location; - } - - public Object getBlockPosition() { - return blockPosition; - } - - public ChannelPipeline getPipeline() { - return pipeline; - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUI.java b/src/main/java/fr/openmc/api/input/signgui/SignGUI.java deleted file mode 100644 index 641059669..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUI.java +++ /dev/null @@ -1,142 +0,0 @@ -package fr.openmc.api.input.signgui; - -import fr.openmc.api.input.signgui.exception.SignGUIException; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; -import fr.openmc.api.input.signgui.wrapper.MojangWrapper; -import org.apache.commons.lang3.Validate; -import org.bukkit.Bukkit; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.List; - -// Ce code est basé sur le fichier SignGUI.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * The base class of this api. Use {@link SignGUI#builder()} to get a new instance. - */ -public class SignGUI { - - /** - * Constructs a new SignGUIBuilder. - * - * @return The new {@link SignGUIBuilder} instance - * @throws SignGUIVersionException If the server version is not supported by this api. - */ - public static SignGUIBuilder builder() throws SignGUIVersionException { - return new SignGUIBuilder(MojangWrapper.get()); - } - - private final String[] lines; - private final Object[] adventureLines; - private final Material type; - private final DyeColor color; - private final boolean glow; - private final Location signLoc; - private final SignGUIFinishHandler handler; - private final boolean callHandlerSynchronously; - private final JavaPlugin plugin; - - /** - * Constructs a new SignGUI. Use {@link SignGUI#builder()} to get a new instance. - */ - SignGUI(String[] lines, Object[] adventureLines, Material type, DyeColor color, boolean glow, Location signLoc, SignGUIFinishHandler handler, boolean callHandlerSynchronously, JavaPlugin plugin) { - this.lines = lines; - this.adventureLines = adventureLines; - this.type = type; - this.color = color; - this.glow = glow; - this.signLoc = signLoc; - this.handler = handler; - this.callHandlerSynchronously = callHandlerSynchronously; - this.plugin = plugin; - } - - /** - * Opens the sign gui for the player. - *

- * Note: if there already is a sign gui open for the player, it will be closed and the {@link SignGUIFinishHandler} will not be called. - * It is recommended to avoid opening a sign gui for a player that already has one open. - * - * @param player The player to open the gui for. - * @throws SignGUIException If an error occurs while opening the gui. - */ - public void open(Player player) throws SignGUIException { - Validate.notNull(player, "The player cannot be null"); - - try { - MojangWrapper.get().openSignEditor(player, lines, adventureLines, type, color, glow, signLoc, (signEditor, resultLines) -> { - Runnable runnable = () -> { - Runnable close = () -> { - try { - MojangWrapper.get().closeSignEditor(player, signEditor); - } catch (Exception e) { - throw new SignGUIException("Failed to close sign editor", e); - } - }; - List actions = handler.onFinish(player, new SignGUIResult(resultLines)); - - if (actions == null || actions.isEmpty()) { - close.run(); - return; - } - - boolean keepOpen = false; - for (SignGUIAction action : actions) { - SignGUIAction.SignGUIActionInfo info = action.getInfo(); - for (SignGUIAction otherAction : actions) { - if (action == otherAction) - continue; - - SignGUIAction.SignGUIActionInfo otherInfo = otherAction.getInfo(); - if (info.isConflicting(otherInfo)) { - close.run(); - throw new IllegalArgumentException("The actions " + info.getName() + " and " + otherInfo.getName() + " are conflicting"); - } - } - - if (info.isKeepOpen()) - keepOpen = true; - } - - if (!keepOpen) - close.run(); - for (SignGUIAction action : actions) - action.execute(this, signEditor, player); - }; - - if (callHandlerSynchronously) - Bukkit.getScheduler().runTask(plugin, runnable); - else - runnable.run(); - }); - } catch (Exception e) { - throw new SignGUIException("Failed to open sign gui", e); - } - } - - /** - * Sets the lines that are shown on the sign. - * This is called when {@link SignGUIAction#displayNewLines(String...)} is returned as an action after the player has finished editing. - * - * @param lines The lines, must be exactly 4. - * @param adventureLines The lines using Adventure components (1.20.5+). Must be exactly 4. May be null. - * @throws java.lang.IllegalArgumentException If lines is null or not exactly 4 lines. - * @throws SignGUIException If an error occurs while setting the lines. - */ - void displayNewLines(Player player, SignEditor signEditor, String[] lines, Object[] adventureLines) { - Validate.notNull(lines, "The lines cannot be null"); - Validate.isTrue(lines.length == 4, "The lines must have a length of 4"); - if (adventureLines != null) - Validate.isTrue(adventureLines.length == 4, "The adventure lines must null or have a length of 4"); - - try { - MojangWrapper.get().displayNewLines(player, signEditor, lines, adventureLines); - } catch (Exception e) { - throw new SignGUIException("Failed to display new lines", e); - } - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUIAction.java b/src/main/java/fr/openmc/api/input/signgui/SignGUIAction.java deleted file mode 100644 index 7238a27d7..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUIAction.java +++ /dev/null @@ -1,231 +0,0 @@ -package fr.openmc.api.input.signgui; - -import org.apache.commons.lang3.Validate; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.Arrays; - -// Ce code est basé sur le fichier SignGUIAuction.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * An interface used for handling the action after the player finished editing the sign. - */ -public interface SignGUIAction { - - /** - * @return The {@link SignGUIAction.SignGUIActionInfo} instance containing information about this action - */ - SignGUIActionInfo getInfo(); - - /** - * Called to execute the actions after the player finished editing the sign. - * - * @param gui The {@link SignGUI} instance - * @param signEditor The {@link SignEditor} instance - * @param player The player who edited the sign - */ - void execute(SignGUI gui, SignEditor signEditor, Player player); - - /** - * Creates a new SignGUIAction that opens the sign gui again with the new lines. - * - * @param lines The new lines, may be less then 4 - * @return The new {@link SignGUIAction} instance - * @throws IllegalArgumentException If lines is null. - */ - static SignGUIAction displayNewLines(String... lines) { - Validate.notNull(lines, "The lines cannot be null"); - - return new SignGUIAction() { - - private SignGUIActionInfo info = new SignGUIActionInfo("displayNewLines", true, 1); - - @Override - public SignGUIActionInfo getInfo() { - return info; - } - - @Override - public void execute(SignGUI gui, SignEditor signEditor, Player player) { - gui.displayNewLines(player, signEditor, Arrays.copyOf(lines, 4), null); - } - }; - } - - /** - * Creates a new SignGUIAction that opens the sign gui again with the new lines using the Adventure component (1.20.5+). - * Lines set using this method are only shown when using a mojang-mapped Paper plugin. - * If you want to set fallback lines to use when Adventure components cannot be used, use {@link #displayNewAdventureLines(Object[], String[])}. - * Please note that if you use this method and the Adventure components cannot be used, the sign will be empty. - * - * @param adventureLines The new adventure lines, may be less then 4 - * @return The new {@link SignGUIAction} instance - * @throws IllegalArgumentException If adventure lines is null. - * @see #displayNewAdventureLines(Object[], String[]) - */ - static SignGUIAction displayNewAdventureLines(Object... adventureLines) { - return displayNewAdventureLines(adventureLines, null); - } - - /** - * Creates a new SignGUIAction that opens the sign gui again with the new lines using the Adventure component (1.20.5+). - * Lines set using this method are only shown when using a mojang-mapped Paper plugin. - * Please note that if you use don't submit fallback lines'and the Adventure components cannot be used, the sign will be empty. - * - * @param adventureLines The new lines, may be less then 4 - * @param fallbackLines The fallback lines, may be less then 4. These are used when the Adventure components cannot be used. May be null. - * @return The new {@link SignGUIAction} instance - * @throws IllegalArgumentException If adventure lines is null. - * @see #displayNewLines(String...) - */ - static SignGUIAction displayNewAdventureLines(Object[] adventureLines, String[] fallbackLines) { - Validate.notNull(adventureLines, "The lines cannot be null"); - - return new SignGUIAction() { - - private SignGUIActionInfo info = new SignGUIActionInfo("displayNewLines", true, 1); - - @Override - public SignGUIActionInfo getInfo() { - return info; - } - - @Override - public void execute(SignGUI gui, SignEditor signEditor, Player player) { - gui.displayNewLines(player, signEditor, fallbackLines != null ? Arrays.copyOf(fallbackLines, 4) : new String[4], - Arrays.copyOf(adventureLines, 4)); - } - }; - } - - /** - * Creates a new SignGUIAction that opens an inventory. - * The inventory is opened synchronously by calling the method {@link org.bukkit.scheduler.BukkitScheduler#runTask(org.bukkit.plugin.Plugin, Runnable)} - * - * @param plugin Your {@link org.bukkit.plugin.java.JavaPlugin} instance - * @param inventory The inventory to open - * @return The new {@link SignGUIAction} instance - */ - static SignGUIAction openInventory(JavaPlugin plugin, Inventory inventory) { - Validate.notNull(plugin, "The plugin cannot be null"); - Validate.notNull(inventory, "The inventory cannot be null"); - - return new SignGUIAction() { - - private SignGUIActionInfo info = new SignGUIActionInfo("openInventory", false, 1); - - @Override - public SignGUIActionInfo getInfo() { - return info; - } - - @Override - public void execute(SignGUI gui, SignEditor signEditor, Player player) { - Bukkit.getScheduler().runTask(plugin, () -> player.openInventory(inventory)); - } - }; - } - - /** - * Creates a new SignGUIAction that runs a runnable. - * The runnable will be run asynchronously. - * - * @param runnable The runnable to run - * @return The new {@link SignGUIAction} instance - */ - static SignGUIAction run(Runnable runnable) { - Validate.notNull(runnable, "The runnable cannot be null"); - - return new SignGUIAction() { - - private SignGUIActionInfo info = new SignGUIActionInfo("run", false, 0); - - @Override - public SignGUIActionInfo getInfo() { - return info; - } - - @Override - public void execute(SignGUI gui, SignEditor signEditor, Player player) { - runnable.run(); - } - }; - } - - /** - * Creates a new SignGUIAction that runs a runnable synchronously. - * - * @param plugin Your {@link org.bukkit.plugin.java.JavaPlugin} instance - * @param runnable The runnable to run - * @return The new {@link SignGUIAction} instance - */ - static SignGUIAction runSync(JavaPlugin plugin, Runnable runnable) { - Validate.notNull(plugin, "The plugin cannot be null"); - Validate.notNull(runnable, "The runnable cannot be null"); - - return new SignGUIAction() { - - private SignGUIActionInfo info = new SignGUIActionInfo("runSync", false, 0); - - @Override - public SignGUIActionInfo getInfo() { - return info; - } - - @Override - public void execute(SignGUI gui, SignEditor signEditor, Player player) { - Bukkit.getScheduler().runTask(plugin, runnable); - } - }; - } - - /** - * Describes a {@link SignGUIAction} - */ - class SignGUIActionInfo { - - private final String name; - private final boolean keepOpen; - private final int conflicting; - - /** - * Creates a new SignGUIActionInfo. - * - * @param name The name of the action - * @param keepOpen Whether the sign gui should be kept open - * @param conflicting The conflicting int - */ - public SignGUIActionInfo(String name, boolean keepOpen, int conflicting) { - this.name = name; - this.keepOpen = keepOpen; - this.conflicting = conflicting; - } - - /** - * @return The name of the action - */ - public String getName() { - return name; - } - - /** - * @return Whether the sign gui should be kept open. - */ - public boolean isKeepOpen() { - return keepOpen; - } - - /** - * Checks whether the result is conflicting with another result. - * - * @param other The conflicting int of the other result - * @return Whether the result is conflicting with the other result - */ - public boolean isConflicting(SignGUIActionInfo other) { - return (conflicting & other.conflicting) != 0; - } - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUIBuilder.java b/src/main/java/fr/openmc/api/input/signgui/SignGUIBuilder.java deleted file mode 100644 index 1cf5fdb40..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUIBuilder.java +++ /dev/null @@ -1,193 +0,0 @@ -package fr.openmc.api.input.signgui; - -import fr.openmc.api.input.signgui.wrapper.MojangWrapper; -import org.apache.commons.lang3.Validate; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.Arrays; -import java.util.stream.Collectors; - -// Ce code est basé sur le fichier SignGUIBuilder.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * Builder for {@link SignGUI}. - */ -public class SignGUIBuilder { - - private static String availableSignTypes; - - private static String getAvailableSignTypes(MojangWrapper wrapper) { - if (availableSignTypes == null) - availableSignTypes = wrapper.getSignTypes().stream().map(Material::toString).collect(Collectors.joining(", ")); - return availableSignTypes; - } - - private MojangWrapper wrapper; - private String[] lines = new String[4]; - private Object[] adventureLines = null; - private Material type; - private DyeColor color = DyeColor.BLACK; - private boolean glow = false; - private Location loc; - private SignGUIFinishHandler handler; - private boolean callHandlerSynchronously = false; - private JavaPlugin plugin; - - /** - * Constructs a new SignGUIBuilder. Use {@link SignGUI#builder()} to get a new instance. - */ - SignGUIBuilder(MojangWrapper wrapper) { - this.wrapper = wrapper; - this.type = wrapper.getDefaultType(); - } - - /** - * Sets the lines that are shown on the sign. - * - * @param lines The lines, may be less than 4. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If lines is null. - */ - public SignGUIBuilder setLines(String... lines) { - Validate.notNull(lines, "The lines cannot be null"); - this.lines = Arrays.copyOf(lines, 4); - return this; - } - - /** - * Sets a specific line that is shown on the sign. - * - * @param index The index of the line. - * @param line The line. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If the index is below 0 or above 4. - */ - public SignGUIBuilder setLine(int index, String line) { - Validate.isTrue(index >= 0 && index <= 3, "Index out of range"); - lines[index] = line; - return this; - } - - /** - * Sets the lines that are shown on the sign using an Adventure component (1.20.5+) - * Lines set using this method are only shown when using a mojang-mapped Paper plugin. - * It is recommended to also set fallback lines using {@link #setLines(String...)} as these will be used if the Adventure components cannot be used for some reason. - * - * @param adventureLines The lines, may be less than 4. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If lines is null. - */ - public SignGUIBuilder setAdventureLines(Object... adventureLines) { - Validate.notNull(adventureLines, "The adventure lines cannot be null"); - this.adventureLines = Arrays.copyOf(adventureLines, 4); - return this; - } - - /** - * Sets a specific line that is shown on the sign using an Adventure component (1.20.5+) - * Lines set using this method are only shown when using a mojang-mapped Paper plugin. - * It is recommended to also set fallback lines using {@link #setLine(int, String)} as these will be used if the Adventure components cannot be used for some reason. - * - * @param index The index of the line. - * @param component Adventure component - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If the index is below 0 or above 4. - */ - public SignGUIBuilder setAdventureLine(int index, Object component) { - Validate.isTrue(index >= 0 && index <= 3, "Index out of range"); - if (adventureLines == null) - adventureLines = new Object[4]; - adventureLines[index] = component; - return this; - } - - /** - * Sets the type of the sign. - * - * @param type The type. Must be a sign type. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If type is null or not a sign type. - */ - public SignGUIBuilder setType(Material type) { - Validate.notNull(type, "The type cannot be null"); - Validate.isTrue(wrapper.getSignTypes().contains(type), type + " is not a sign type. Available sign types: " + getAvailableSignTypes(wrapper)); - this.type = type; - return this; - } - - /** - * Sets the color of the sign. (1.14+) - * - * @param color The color. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If color is null. - */ - public SignGUIBuilder setColor(DyeColor color) { - Validate.notNull(color, "The color cannot be null"); - this.color = color; - return this; - } - - /** - * Sets if the sign's text should glow. (1.17+) - * - * @param glow If the sign's text should glow. - * @return The {@link SignGUIBuilder} instance - */ - public SignGUIBuilder setGlow(boolean glow) { - this.glow = glow; - return this; - } - - /** - * Sets the location of the sign. Set to null for the default location which is a few blocks behind the player. - * - * @param loc The location. - * @return The {@link SignGUIBuilder} instance - */ - public SignGUIBuilder setLocation(Location loc) { - this.loc = loc; - return this; - } - - /** - * Sets the handler that is called when the player finishes the sign gui. - * See {@link SignGUIFinishHandler#onFinish(Player, SignGUIResult)} for more information. - * - * @param handler The handler. - * @return The {@link SignGUIBuilder} instance - * @throws java.lang.IllegalArgumentException If handler is null. - */ - public SignGUIBuilder setHandler(SignGUIFinishHandler handler) { - Validate.notNull(handler, "The handler cannot be null"); - this.handler = handler; - return this; - } - - /** - * If called the handler will be called synchronously by calling the method {@link org.bukkit.scheduler.BukkitScheduler#runTask(Plugin, Runnable)} - * - * @param plugin Your {@link org.bukkit.plugin.java.JavaPlugin} instance. - * @return The {@link SignGUIBuilder} instance - */ - public SignGUIBuilder callHandlerSynchronously(JavaPlugin plugin) { - this.callHandlerSynchronously = true; - this.plugin = plugin; - return this; - } - - /** - * Builds the SignGUI. - * - * @return The SignGUI. - */ - public SignGUI build() { - Validate.notNull(handler, "handler must be set"); - return new SignGUI(lines, adventureLines, type, color, glow, loc, handler, callHandlerSynchronously, plugin); - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUIChannelHandler.java b/src/main/java/fr/openmc/api/input/signgui/SignGUIChannelHandler.java deleted file mode 100644 index a9a993d8d..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUIChannelHandler.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.openmc.api.input.signgui; - -import io.netty.handler.codec.MessageToMessageDecoder; - -// Ce code est basé sur le fichier SignGUIChannelHandler.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -public abstract class SignGUIChannelHandler extends MessageToMessageDecoder { - - public abstract Object getBlockPosition(); - - public abstract void close(); -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUIFinishHandler.java b/src/main/java/fr/openmc/api/input/signgui/SignGUIFinishHandler.java deleted file mode 100644 index 1f7f06a4d..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUIFinishHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package fr.openmc.api.input.signgui; - -import org.bukkit.entity.Player; - -import java.util.List; - -// Ce code est basé sur le fichier SignGUIFinishHandler.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * A functional interface used for handling the result of the sign editing. - */ -@FunctionalInterface -public interface SignGUIFinishHandler { - - /** - * Called when the player finished editing the sign. - * Return a list of actions that should be executed after the editing is finished. The actions are executed in the order they are in the list. - * If {@link SignGUIAction#displayNewLines(String...)} is not included, the sign gui will be closed. - * If you just want to close the sign gui, return an empty list or null. - * - * @param player The player who edited the sign. - * @param result The result of the editing. - * @return The list of actions. - */ - List onFinish(Player player, SignGUIResult result); -} diff --git a/src/main/java/fr/openmc/api/input/signgui/SignGUIResult.java b/src/main/java/fr/openmc/api/input/signgui/SignGUIResult.java deleted file mode 100644 index bfaa5a9b3..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/SignGUIResult.java +++ /dev/null @@ -1,59 +0,0 @@ -package fr.openmc.api.input.signgui; - -import org.bukkit.ChatColor; - -// Ce code est basé sur le fichier SignGUIResult.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * The result of the sign editing. - */ -public class SignGUIResult { - - private final String[] lines; - - SignGUIResult(String[] lines) { - this.lines = lines; - } - - /** - * @return The lines of the sign when the player finished editing. - */ - public String[] getLines() { - return lines; - } - - /** - * Used for getting a specific line of the sign. - * @param index The index of the desired line. - * @return The line at the given index. - */ - public String getLine(int index) { - return lines[index]; - } - - /** - * Used for getting the lines of the sign without color codes. - * Calls {@link org.bukkit.ChatColor#stripColor(String)} on each line. - * This method only strips color codes with § (not with {@literal &} for example). - * - * @return The lines of the sign without color codes. - */ - public String[] getLinesWithoutColor() { - String[] linesWithoutColor = new String[lines.length]; - for (int i = 0; i < lines.length; i++) - linesWithoutColor[i] = ChatColor.stripColor(lines[i]); - return linesWithoutColor; - } - - /** - * Used for getting a specific line of the sign without color codes. - * Calls {@link org.bukkit.ChatColor#stripColor(String)} on the line. - * This method only strips color codes with § (not with {@literal &} for example). - * - * @param index The index of the desired line. - * @return The line at the given index without color codes. - */ - public String getLineWithoutColor(int index) { - return ChatColor.stripColor(lines[index]); - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIException.java b/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIException.java deleted file mode 100644 index 9977e5ecf..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIException.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.openmc.api.input.signgui.exception; - -// Ce code est basé sur le fichier SignGUIException.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * An exception thrown when an error occurs while using this api. - */ -public class SignGUIException extends RuntimeException { - - /** - * {@inheritDoc} - */ - public SignGUIException() { - } - - /** - * {@inheritDoc} - */ - public SignGUIException(String message) { - super(message); - } - - /** - * {@inheritDoc} - */ - public SignGUIException(String message, Throwable cause) { - super(message, cause); - } - - /** - * {@inheritDoc} - */ - public SignGUIException(Throwable cause) { - super(cause); - } - - /** - * {@inheritDoc} - */ - public SignGUIException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIVersionException.java b/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIVersionException.java deleted file mode 100644 index 46e9f08ab..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/exception/SignGUIVersionException.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.openmc.api.input.signgui.exception; - -// Ce code est basé sur le fichier SignGUIVersionException.java du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI). Licence originale : MIT. -/** - * An exception thrown when the server version is not supported by this api or an error occured during initialization. - */ -public class SignGUIVersionException extends Exception { - - /** - * {@inheritDoc} - */ - public SignGUIVersionException() { - } - - /** - * {@inheritDoc} - */ - public SignGUIVersionException(String message) { - super(message); - } - - /** - * {@inheritDoc} - */ - public SignGUIVersionException(String message, Throwable cause) { - super(message, cause); - } - - /** - * {@inheritDoc} - */ - public SignGUIVersionException(Throwable cause) { - super(cause); - } - - /** - * {@inheritDoc} - */ - public SignGUIVersionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/src/main/java/fr/openmc/api/input/signgui/wrapper/MojangWrapper.java b/src/main/java/fr/openmc/api/input/signgui/wrapper/MojangWrapper.java deleted file mode 100644 index 329c7e9af..000000000 --- a/src/main/java/fr/openmc/api/input/signgui/wrapper/MojangWrapper.java +++ /dev/null @@ -1,175 +0,0 @@ -package fr.openmc.api.input.signgui.wrapper; - -import fr.openmc.api.input.signgui.SignEditor; -import fr.openmc.api.input.signgui.SignGUIChannelHandler; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPipeline; -import io.papermc.paper.adventure.AdventureComponent; -import net.minecraft.core.BlockPos; -import net.minecraft.network.Connection; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientboundOpenSignEditorPacket; -import net.minecraft.network.protocol.game.ServerboundSignUpdatePacket; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.level.block.entity.SignText; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.entity.Player; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; - -// Ce code provient de la Pull Request #30 du dépôt SignGUI -// (https://github.com/Rapha149/SignGUI/pull/30), qui ajoute -// une compatibilité avec Minecraft 1.21.5. Code original écrit par Leon-JavaScript. -public class MojangWrapper { - private static final MojangWrapper INSTANCE = new MojangWrapper(); - private static final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(0); - - public Material getDefaultType() { - return Material.OAK_SIGN; - } - - public List getSignTypes() { - return Arrays.asList(Material.OAK_SIGN, Material.BIRCH_SIGN, Material.SPRUCE_SIGN, Material.JUNGLE_SIGN, - Material.ACACIA_SIGN, Material.DARK_OAK_SIGN, Material.CRIMSON_SIGN, Material.WARPED_SIGN, - Material.CHERRY_SIGN, Material.MANGROVE_SIGN, Material.BAMBOO_SIGN, Material.PALE_OAK_SIGN - ); - } - - private static Component[] createLines(String[] textLines, Object[] adventureLines) { - Component[] lines = new Component[4]; - if (adventureLines != null) { - for (int i = 0; i < adventureLines.length; i++) { - Object line = adventureLines[i]; - if (line instanceof net.kyori.adventure.text.Component component) { - lines[i] = new AdventureComponent(component); - } else if (line == null) { - lines[i] = Component.empty(); - } else { - throw new IllegalArgumentException("line at index " + i + " is not net.kyori.adventure.text.Component"); - } - } - } else { - for (int i = 0; i < textLines.length; i++) - lines[i] = Component.nullToEmpty(textLines[i]); - } - return lines; - } - - public void openSignEditor(Player player, String[] textLines, Object[] adventureLines, Material type, DyeColor color, boolean glow, Location signLoc, BiConsumer onFinish) { - ServerPlayer p = ((CraftPlayer) player).getHandle(); - ServerGamePacketListenerImpl conn = p.connection; - - Location loc = signLoc != null ? signLoc : getDefaultLocation(player); - BlockPos pos = new BlockPos(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - - SignBlockEntity sign = new SignBlockEntity(pos, Blocks.OAK_SIGN.defaultBlockState()); - SignText signText = sign.getText(true) // flag = front/back of sign - .setColor(net.minecraft.world.item.DyeColor.valueOf(color.toString())) - .setHasGlowingText(glow); - - Component[] lines = createLines(textLines, adventureLines); - for (int i = 0; i < lines.length; i++) - signText = signText.setMessage(i, lines[i]); - sign.setText(signText, true); - - boolean schedule = false; - Connection manager = conn.connection; - ChannelPipeline pipeline = manager.channel.pipeline(); - if (pipeline.names().contains("SignGUI")) { - ChannelHandler handler = pipeline.get("SignGUI"); - if (handler instanceof SignGUIChannelHandler signGUIHandler) { - signGUIHandler.close(); - schedule = signGUIHandler.getBlockPosition().equals(pos); - } - - if (pipeline.names().contains("SignGUI")) - pipeline.remove("SignGUI"); - } - - Runnable runnable = () -> { - player.sendBlockChange(loc, type.createBlockData()); - sign.setLevel(p.level()); - conn.send(sign.getUpdatePacket()); - sign.setLevel(null); - conn.send(new ClientboundOpenSignEditorPacket(pos, true)); // flag = front/back of sign - - SignEditor signEditor = new SignEditor(sign, loc, pos, pipeline); - pipeline.addAfter("decoder", "SignGUI", new SignGUIChannelHandler>() { - - @Override - public Object getBlockPosition() { - return pos; - } - - @Override - public void close() { - closeSignEditor(player, signEditor); - } - - @Override - protected void decode(ChannelHandlerContext chc, Packet packet, List out) { - try { - if (packet instanceof ServerboundSignUpdatePacket updateSign) { - if (updateSign.getPos().equals(pos)) - onFinish.accept(signEditor, updateSign.getLines()); - } - } catch (Exception e) { - e.printStackTrace(); - } - - out.add(packet); - } - }); - }; - - if (schedule) - SCHEDULER.schedule(runnable, 200, TimeUnit.MILLISECONDS); - else - runnable.run(); - } - - public void displayNewLines(Player player, SignEditor signEditor, String[] textLines, Object[] adventureLines) { - SignBlockEntity sign = (SignBlockEntity)signEditor.getSign(); - - SignText newSignText = sign.getText(true); - Component[] lines = createLines(textLines, adventureLines); - for(int i = 0; i < textLines.length; ++i) - newSignText = newSignText.setMessage(i, lines[i]); - sign.setText(newSignText, true); - - ServerPlayer p = ((CraftPlayer)player).getHandle(); - ServerGamePacketListenerImpl conn = p.connection; - sign.setLevel(p.level()); - conn.send(sign.getUpdatePacket()); - sign.setLevel(null); - conn.send(new ClientboundOpenSignEditorPacket((BlockPos)signEditor.getBlockPosition(), true)); - } - - public void closeSignEditor(Player player, SignEditor signEditor) { - Location loc = signEditor.getLocation(); - signEditor.getPipeline().remove("SignGUI"); - player.sendBlockChange(loc, loc.getBlock().getBlockData()); - } - - private Location getDefaultLocation(Player player) { - Location loc = player.getEyeLocation(); - return loc.clone().add(loc.getDirection().multiply(-3)); - } - - public static MojangWrapper get() { - return INSTANCE; - } -} diff --git a/src/main/java/fr/openmc/core/ListenersManager.java b/src/main/java/fr/openmc/core/ListenersManager.java index d964d611d..9c6dfeb62 100644 --- a/src/main/java/fr/openmc/core/ListenersManager.java +++ b/src/main/java/fr/openmc/core/ListenersManager.java @@ -15,6 +15,7 @@ public class ListenersManager { public ListenersManager() { registerEvents( + new HappyGhastListener(), new SessionsListener(), new JoinMessageListener(), new UpdateListener(), diff --git a/src/main/java/fr/openmc/core/OMCPlugin.java b/src/main/java/fr/openmc/core/OMCPlugin.java index b9ad560c7..83ba9f8ac 100644 --- a/src/main/java/fr/openmc/core/OMCPlugin.java +++ b/src/main/java/fr/openmc/core/OMCPlugin.java @@ -111,7 +111,7 @@ public void onEnable() { PlayerSettingsManager.loadAllPlayerSettings(); - ParticleUtils.spawnParticlesInRegion("spawn", Bukkit.getWorld("world"), Particle.CHERRY_LEAVES, 50, 130); + ParticleUtils.spawnParticlesInRegion("spawn", Bukkit.getWorld("world"), Particle.CHERRY_LEAVES, 50, 70, 130); ParticleUtils.spawnContestParticlesInRegion("spawn", Bukkit.getWorld("world"), 10, 70, 135); getLogger().info("Plugin activé"); diff --git a/src/main/java/fr/openmc/core/features/city/City.java b/src/main/java/fr/openmc/core/features/city/City.java index c44744826..a92275165 100644 --- a/src/main/java/fr/openmc/core/features/city/City.java +++ b/src/main/java/fr/openmc/core/features/city/City.java @@ -1,6 +1,5 @@ package fr.openmc.core.features.city; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.api.cooldown.DynamicCooldownManager; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.city.events.*; @@ -18,6 +17,7 @@ import fr.openmc.core.features.city.sub.war.WarManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.CacheOfflinePlayer; +import fr.openmc.core.utils.ChunkPos; import fr.openmc.core.utils.InputUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; @@ -43,7 +43,7 @@ public class City { private String name; private final String cityUUID; private Set members; - private Set chunks; // Liste des chunks claims par la ville + private Set chunks; // Liste des chunks claims par la ville private HashMap> permissions; private Set cityRanks; private HashMap chestContent; @@ -70,9 +70,9 @@ public City(String id, String name, Player owner, CityType type, Chunk chunk) { this.type = type; this.freeClaims = 15; - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); CityManager.registerCity(this); @@ -81,16 +81,17 @@ public City(String id, String name, Player owner, CityType type, Chunk chunk) { this.cityRanks = new HashSet<>(); this.chunks = new HashSet<>(); this.chestContent = new HashMap<>(); - - addChunk(chunk); + + addChunk(chunk.getX(), chunk.getZ()); + addPlayer(owner.getUniqueId()); addPermission(owner.getUniqueId(), CPermission.OWNER); saveChestContent(1, null); CityManager.loadCityRanks(this); - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - Bukkit.getPluginManager().callEvent(new CityCreationEvent(this, owner)); - }); + Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> + Bukkit.getPluginManager().callEvent(new CityCreationEvent(this, owner)) + ); } /** @@ -130,7 +131,7 @@ public Set getMembers() { /** * Gets all the member of this city */ - public Set getChunks() { + public Set getChunks() { if (this.chunks == null) this.chunks = CityManager.getCityChunks(this); @@ -149,9 +150,9 @@ public String getUUID() { public void rename(String newName) { this.name = newName; - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); } public void setType(String type) { @@ -161,9 +162,9 @@ public void setType(String type) { this.type = CityType.PEACE; } - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); } public void changeType() { @@ -173,9 +174,9 @@ public void changeType() { this.type = CityType.WAR; } - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); } // ==================== Members Methods ==================== @@ -213,9 +214,9 @@ public void addPlayer(UUID player) { this.members = CityManager.getCityMembers(this); members.add(player); - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - Bukkit.getPluginManager().callEvent(new MemberJoinEvent(CacheOfflinePlayer.getOfflinePlayer(player), this)); - }); + Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> + Bukkit.getPluginManager().callEvent(new MemberJoinEvent(CacheOfflinePlayer.getOfflinePlayer(player), this)) + ); CityManager.addPlayerToCity(this, player); } @@ -230,10 +231,10 @@ public void removePlayer(UUID player) { this.members = CityManager.getCityMembers(this); members.remove(player); - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { + Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> Bukkit.getPluginManager() - .callEvent(new MemberLeaveEvent(CacheOfflinePlayer.getOfflinePlayer(player), this)); - }); + .callEvent(new MemberLeaveEvent(CacheOfflinePlayer.getOfflinePlayer(player), this)) + ); CityManager.removePlayerFromCity(this, player); } @@ -252,9 +253,9 @@ public void changeOwner(UUID player) { */ public void updateFreeClaims(int diff) { freeClaims += diff; - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); } // ==================== Chest Methods ==================== @@ -287,9 +288,9 @@ public void saveChestContent(int page, ItemStack[] content) { chestContent.put(page, content); - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveChestPage(this, page, content); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveChestPage(this, page, content) + ); } /** @@ -313,29 +314,19 @@ public void saveChestContent(int page, ItemStack[] content) { * Adds a chunk to the city's claimed chunks and updates the database * asynchronously. * - * @param chunk The chunk to be added. + * @param x The chunk X to be added. + * @param z The chunk Z to be added. */ - public void addChunk(Chunk chunk) { + public void addChunk(int x, int z) { if (this.chunks == null) this.chunks = CityManager.getCityChunks(this); - BlockVector2 coords = BlockVector2.at(chunk.getX(), chunk.getZ()); - if (chunks.contains(coords)) + ChunkPos chunkPos = new ChunkPos(x, z); + if (chunks.contains(chunkPos)) return; - chunks.add(coords); + chunks.add(chunkPos); - CityManager.claimChunk(this, coords); - } - - /** - * Adds a chunk to the city's claimed chunks by specifying its coordinates and updates the database asynchronously. - * - * @param x The X coordinate of the chunk to be added. - * @param z The Z coordinate of the chunk to be added. - */ - public void addChunk(int x, int z) { - Chunk chunk = Bukkit.getWorld("world").getChunkAt(x, z); - addChunk(chunk); + CityManager.claimChunk(this, chunkPos); } /** @@ -359,10 +350,10 @@ public void removeChunk(int chunkX, int chunkZ) { if (this.chunks == null) this.chunks = CityManager.getCityChunks(this); - BlockVector2 coords = BlockVector2.at(chunkX, chunkZ); - chunks.remove(coords); + ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ); + chunks.remove(chunkPos); - CityManager.unclaimChunk(this, coords); + CityManager.unclaimChunk(this, chunkPos); } /** @@ -372,11 +363,11 @@ public void removeChunk(int chunkX, int chunkZ) { * @param z The Z coordinate of the chunk to check. * @return True if the chunk is claimed, false otherwise. */ - public boolean hasChunk(double x, double z) { + public boolean hasChunk(int x, int z) { if (this.chunks == null) this.chunks = CityManager.getCityChunks(this); - return chunks.contains(BlockVector2.at(x, z)); + return chunks.contains(new ChunkPos(x, z)); } /** @@ -389,7 +380,7 @@ public boolean hasChunk(Chunk chunk) { if (this.chunks == null) this.chunks = CityManager.getCityChunks(this); - return chunks.contains(BlockVector2.at(chunk.getX(), chunk.getZ())); + return chunks.contains(new ChunkPos(chunk.getX(), chunk.getZ())); } // ==================== Economy Methods ==================== @@ -403,12 +394,12 @@ public boolean hasChunk(Chunk chunk) { public void setBalance(double value) { double before = balance; balance = value; - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - Bukkit.getPluginManager().callEvent(new CityMoneyUpdateEvent(this, before, balance)); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); + Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> + Bukkit.getPluginManager().callEvent(new CityMoneyUpdateEvent(this, before, balance)) + ); } /** @@ -574,14 +565,14 @@ public void addPermission(UUID playerUUID, CPermission permission) { playerPerms.add(permission); permissions.put(playerUUID, playerPerms); - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.addPlayerPermission(this, playerUUID, permission); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.addPlayerPermission(this, playerUUID, permission) + ); - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { + Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> Bukkit.getPluginManager().callEvent( - new CityPermissionChangeEvent(this, CacheOfflinePlayer.getOfflinePlayer(playerUUID), permission, true)); - }); + new CityPermissionChangeEvent(this, CacheOfflinePlayer.getOfflinePlayer(playerUUID), permission, true)) + ); } /** @@ -689,6 +680,7 @@ public boolean isImmune() { return getMascot().isImmunity() && !DynamicCooldownManager.isReady(cityUUID, "city:immunity"); } + /** * Updates the power of a City by adding or removing points. * @@ -696,9 +688,9 @@ public boolean isImmune() { */ public void updatePowerPoints(int diff) { powerPoints += diff; - Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - CityManager.saveCity(this); - }); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + CityManager.saveCity(this) + ); } /* =================== RANKS =================== */ diff --git a/src/main/java/fr/openmc/core/features/city/CityManager.java b/src/main/java/fr/openmc/core/features/city/CityManager.java index 39e9e357e..1501f1b98 100644 --- a/src/main/java/fr/openmc/core/features/city/CityManager.java +++ b/src/main/java/fr/openmc/core/features/city/CityManager.java @@ -6,7 +6,6 @@ import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.api.chronometer.Chronometer; import fr.openmc.api.cooldown.DynamicCooldownManager; import fr.openmc.core.CommandsManager; @@ -22,6 +21,7 @@ import fr.openmc.core.features.city.sub.mayor.managers.NPCManager; import fr.openmc.core.features.city.sub.war.WarManager; import fr.openmc.core.utils.CacheOfflinePlayer; +import fr.openmc.core.utils.ChunkPos; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.entity.Player; @@ -36,7 +36,7 @@ public class CityManager implements Listener { private static HashMap cities = new HashMap<>(); private static HashMap playerCities = new HashMap<>(); - private static HashMap claimedChunks = new HashMap<>(); + private static HashMap claimedChunks = new HashMap<>(); public CityManager() { OMCPlugin.registerEvents(this); @@ -131,10 +131,7 @@ private static void loadCities() { try { claimedChunks.clear(); claimsDao.queryForAll() - .forEach(claim -> { - if (getCity(claim.getCity()) != null) - claimedChunks.put(claim.getBlockVector(), getCity(claim.getCity())); - }); + .forEach(claim -> claimedChunks.put(claim.getChunkPos(), getCity(claim.getCity()))); } catch (SQLException e) { e.printStackTrace(); } @@ -149,6 +146,7 @@ private static void loadCities() { city.getRanks().add(rank); } }); + } catch (SQLException e) { e.printStackTrace(); } @@ -268,7 +266,7 @@ public static void saveChestPage(City city, int page, ItemStack[] content) { } } - public static void claimChunk(City city, BlockVector2 chunk) { + public static void claimChunk(City city, ChunkPos chunk) { claimedChunks.put(chunk, city); Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { @@ -280,13 +278,13 @@ public static void claimChunk(City city, BlockVector2 chunk) { }); } - public static void unclaimChunk(City city, BlockVector2 chunk) { + public static void unclaimChunk(City city, ChunkPos chunk) { claimedChunks.remove(chunk); Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { try { DeleteBuilder delete = claimsDao.deleteBuilder(); - delete.where().eq("city", city.getUUID()).and().eq("x", chunk.getX()).and().eq("z", chunk.getZ()); + delete.where().eq("city", city.getUUID()).and().eq("x", chunk.x()).and().eq("z", chunk.z()); claimsDao.delete(delete.prepare()); } catch (SQLException e) { @@ -362,12 +360,8 @@ public static City getCity(String city) { * @param inCity The cities whose chunks are requested * @return The cities claimed chunks */ - public static Set getCityChunks(City inCity) { - Set chunks = new HashSet<>(); - - claimedChunks.forEach( - (chunk, city) -> System.out.println(city + " - " + chunk) - ); + public static Set getCityChunks(City inCity) { + Set chunks = new HashSet<>(); claimedChunks.forEach((chunk, city) -> { if (city.getUUID().equals(inCity.getUUID())) @@ -413,7 +407,7 @@ public static City getPlayerCity(UUID player) { */ @Nullable public static City getCityFromChunk(int x, int z) { - return claimedChunks.get(BlockVector2.at(x, z)); + return claimedChunks.get(new ChunkPos(x, z)); } @@ -526,10 +520,10 @@ public static void deleteCity(City city) { } } - Iterator iterator = claimedChunks.keySet().iterator(); + Iterator iterator = claimedChunks.keySet().iterator(); while (iterator.hasNext()) { - BlockVector2 vector = iterator.next(); - City claimedCity = claimedChunks.get(vector); + ChunkPos chunkPos = iterator.next(); + City claimedCity = claimedChunks.get(chunkPos); if (claimedCity != null && claimedCity.equals(city)) { iterator.remove(); } diff --git a/src/main/java/fr/openmc/core/features/city/ProtectionsManager.java b/src/main/java/fr/openmc/core/features/city/ProtectionsManager.java index c8621fc73..6fe2c01d8 100644 --- a/src/main/java/fr/openmc/core/features/city/ProtectionsManager.java +++ b/src/main/java/fr/openmc/core/features/city/ProtectionsManager.java @@ -57,6 +57,8 @@ public static boolean canInteract(Player player, Location loc) { City cityAtLoc = CityManager.getCityFromChunk(loc.getChunk().getX(), loc.getChunk().getZ()); + if (cityAtLoc == null) return true; + if (cityAtLoc.isMember(player)) return true; War war = cityAtLoc.getWar(); diff --git a/src/main/java/fr/openmc/core/features/city/actions/CityClaimAction.java b/src/main/java/fr/openmc/core/features/city/actions/CityClaimAction.java index 79ceeec49..b0b94a5e5 100644 --- a/src/main/java/fr/openmc/core/features/city/actions/CityClaimAction.java +++ b/src/main/java/fr/openmc/core/features/city/actions/CityClaimAction.java @@ -1,12 +1,12 @@ package fr.openmc.core.features.city.actions; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.economy.EconomyManager; +import fr.openmc.core.items.CustomItemRegistry; +import fr.openmc.core.utils.ChunkPos; import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.api.WorldGuardApi; -import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -37,10 +37,10 @@ public static void startClaim(Player sender, int chunkX, int chunkZ) { return; } - BlockVector2 chunkVec2 = BlockVector2.at(chunkX, chunkZ); + ChunkPos chunkVec2 = new ChunkPos(chunkX, chunkZ); AtomicBoolean isFar = new AtomicBoolean(true); - for (BlockVector2 chnk : city.getChunks()) { + for (ChunkPos chnk : city.getChunks()) { if (chnk.distance(chunkVec2) == 1) { //Si c'est en diagonale alors ça sera sqrt(2) ≈1.41 isFar.set(false); break; @@ -80,7 +80,7 @@ public static void startClaim(Player sender, int chunkX, int chunkZ) { city.updateFreeClaims(-1); } - city.addChunk(chunk); + city.addChunk(chunkX, chunkZ); MessagesManager.sendMessage(sender, Component.text("Ta ville a été étendue"), Prefix.CITY, MessageType.SUCCESS, false); } diff --git a/src/main/java/fr/openmc/core/features/city/actions/CityRankAction.java b/src/main/java/fr/openmc/core/features/city/actions/CityRankAction.java index 8103aee12..985d69e98 100644 --- a/src/main/java/fr/openmc/core/features/city/actions/CityRankAction.java +++ b/src/main/java/fr/openmc/core/features/city/actions/CityRankAction.java @@ -1,9 +1,7 @@ package fr.openmc.core.features.city.actions; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.default_menu.ConfirmMenu; -import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.city.CPermission; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; @@ -11,19 +9,17 @@ import fr.openmc.core.features.city.menu.ranks.CityRankDetailsMenu; import fr.openmc.core.features.city.menu.ranks.CityRankMemberMenu; import fr.openmc.core.features.city.models.CityRank; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; -import java.util.Collections; import java.util.List; public class CityRankAction { + private static final int MAX_LENGTH_RANK_NAME = 16; public static void beginCreateRank(Player player) { City city = CityManager.getPlayerCity(player.getUniqueId()); @@ -31,32 +27,9 @@ public static void beginCreateRank(Player player) { return; } - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre nom"; - lines[3] = "de grade ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - CityRankAction.afterCreateRank(player, input); - }); - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le nom de votre grade"), MAX_LENGTH_RANK_NAME, input -> + CityRankAction.afterCreateRank(player, input) + ); } public static void afterCreateRank(Player player, String rankName) { @@ -79,44 +52,20 @@ public static void renameRank(Player player, String oldName) { return; } - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre nom"; - lines[3] = "de grade ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - if (!CityRankCondition.canRenameRank(city, player, oldName)) { - return; - } - - CityRank rank = city.getRankByName(oldName); - if (rank == null) { - MessagesManager.sendMessage(player, MessagesManager.Message.CITYRANKS_NOTEXIST.getMessage(), Prefix.CITY, MessageType.ERROR, false); - return; - } - - city.updateRank(rank, new CityRank(rank.getRankUUID(), city.getUUID(), input, rank.getPriority(), rank.getPermissionsSet(), rank.getIcon())); - MessagesManager.sendMessage(player, Component.text("Le nom du grade a été mis à jour : " + oldName + " → " + input), Prefix.CITY, MessageType.SUCCESS, false); - - }); - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } + DialogInput.send(player, Component.text("Entrez le nouveau nom de votre grade"), MAX_LENGTH_RANK_NAME, input -> { + if (!CityRankCondition.canRenameRank(city, player, oldName)) { + return; + } + + CityRank rank = city.getRankByName(oldName); + if (rank == null) { + MessagesManager.sendMessage(player, MessagesManager.Message.CITYRANKS_NOTEXIST.getMessage(), Prefix.CITY, MessageType.ERROR, false); + return; + } - gui.open(player); + city.updateRank(rank, new CityRank(rank.getRankUUID(), city.getUUID(), input, rank.getPriority(), rank.getPermissionsSet(), rank.getIcon())); + MessagesManager.sendMessage(player, Component.text("Le nom du grade a été mis à jour : " + oldName + " → " + input), Prefix.CITY, MessageType.SUCCESS, false); + }); } public static void deleteRank(Player player, String rankName) { diff --git a/src/main/java/fr/openmc/core/features/city/commands/CityCommands.java b/src/main/java/fr/openmc/core/features/city/commands/CityCommands.java index 6960b8a1b..ab41b977c 100644 --- a/src/main/java/fr/openmc/core/features/city/commands/CityCommands.java +++ b/src/main/java/fr/openmc/core/features/city/commands/CityCommands.java @@ -1,9 +1,7 @@ package fr.openmc.core.features.city.commands; import fr.openmc.api.chronometer.Chronometer; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; -import fr.openmc.core.OMCPlugin; +import fr.openmc.api.input.DialogInput; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.CityMessages; @@ -15,23 +13,25 @@ import fr.openmc.core.features.city.menu.NoCityMenu; import fr.openmc.core.features.city.menu.list.CityListMenu; import fr.openmc.core.utils.InputUtils; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; -import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import revxrsal.commands.annotation.Optional; import revxrsal.commands.annotation.*; import revxrsal.commands.bukkit.annotation.CommandPermission; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH_CITY; @Command({"ville", "city"}) public class CityCommands { @@ -82,32 +82,9 @@ void create(Player player, @Optional String name) { return; } - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre nom"; - lines[3] = "de ville ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - CityCreateAction.beginCreateCity(player, input); - }); - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le nom de la ville"), MAX_LENGTH_CITY, input -> + CityCreateAction.beginCreateCity(player, input) + ); } @Subcommand("delete") @@ -187,7 +164,7 @@ void rename(Player player, @Named("nouveau nom") String name) { if (!CityManageConditions.canCityRename(playerCity, player)) return; if (!InputUtils.isInputCityName(name)) { - MessagesManager.sendMessage(player, Component.text("Le nom de ville est invalide, il doit seulement comporter des caractères alphanumeriques et maximum 24 caractères."), Prefix.CITY, MessageType.ERROR, false); + MessagesManager.sendMessage(player, Component.text("Le nom de ville est invalide, il doit seulement comporter des caractères alphanumeriques et maximum " + MAX_LENGTH_CITY + " caractères."), Prefix.CITY, MessageType.ERROR, false); return; } diff --git a/src/main/java/fr/openmc/core/features/city/menu/CityModifyMenu.java b/src/main/java/fr/openmc/core/features/city/menu/CityModifyMenu.java index 03970bb57..0e024b30b 100644 --- a/src/main/java/fr/openmc/core/features/city/menu/CityModifyMenu.java +++ b/src/main/java/fr/openmc/core/features/city/menu/CityModifyMenu.java @@ -1,8 +1,7 @@ package fr.openmc.core.features.city.menu; import fr.openmc.api.cooldown.DynamicCooldownManager; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -15,7 +14,6 @@ import fr.openmc.core.features.city.conditions.CityManageConditions; import fr.openmc.core.utils.DateUtils; import fr.openmc.core.utils.InputUtils; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -27,12 +25,13 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH_CITY; + public class CityModifyMenu extends Menu { public CityModifyMenu(Player owner) { @@ -89,38 +88,17 @@ public void onInventoryClick(InventoryClickEvent click) { City cityCheck = CityManager.getPlayerCity(player.getUniqueId()); if (!CityManageConditions.canCityRename(cityCheck, player)) return; - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre"; - lines[3] = "nom ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - if (InputUtils.isInputCityName(input)) { - City playerCity = CityManager.getPlayerCity(player.getUniqueId()); - - playerCity.rename(input); - MessagesManager.sendMessage(player, Component.text("La ville a été renommée en " + input), Prefix.CITY, MessageType.SUCCESS, false); - - } else { - MessagesManager.sendMessage(player, Component.text("Veuillez mettre une entrée correcte"), Prefix.CITY, MessageType.ERROR, true); - } - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } + DialogInput.send(player, Component.text("Entrez le nom de la ville"), MAX_LENGTH_CITY, input -> { + if (InputUtils.isInputCityName(input)) { + City playerCity = CityManager.getPlayerCity(player.getUniqueId()); + + playerCity.rename(input); + MessagesManager.sendMessage(player, Component.text("La ville a été renommée en " + input), Prefix.CITY, MessageType.SUCCESS, false); - gui.open(player); + } else { + MessagesManager.sendMessage(player, Component.text("Veuillez mettre une entrée correcte"), Prefix.CITY, MessageType.ERROR, true); + } + }); })); diff --git a/src/main/java/fr/openmc/core/features/city/menu/NoCityMenu.java b/src/main/java/fr/openmc/core/features/city/menu/NoCityMenu.java index 4c9a54745..344890f02 100644 --- a/src/main/java/fr/openmc/core/features/city/menu/NoCityMenu.java +++ b/src/main/java/fr/openmc/core/features/city/menu/NoCityMenu.java @@ -1,8 +1,7 @@ package fr.openmc.core.features.city.menu; import fr.openmc.api.cooldown.DynamicCooldownManager; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -13,13 +12,11 @@ import fr.openmc.core.features.city.conditions.CityCreateConditions; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.DateUtils; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextDecoration; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; @@ -27,9 +24,14 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.function.Supplier; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH_CITY; + public class NoCityMenu extends Menu { public NoCityMenu(Player owner) { @@ -110,32 +112,9 @@ public void onInventoryClick(InventoryClickEvent click) { }).setOnClick(inventoryClickEvent -> { if (!DynamicCooldownManager.isReady(player.getUniqueId().toString(), "city:big")) return; - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre nom"; - lines[3] = "de ville ci dessus"; - - SignGUI gui = null; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - CityCreateAction.beginCreateCity(player, input); - }); - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le nom de la ville"), MAX_LENGTH_CITY, input -> + CityCreateAction.beginCreateCity(player, input) + ); }); }; diff --git a/src/main/java/fr/openmc/core/features/city/menu/playerlist/CityPlayerListMenu.java b/src/main/java/fr/openmc/core/features/city/menu/playerlist/CityPlayerListMenu.java index e19438272..343b25f6a 100644 --- a/src/main/java/fr/openmc/core/features/city/menu/playerlist/CityPlayerListMenu.java +++ b/src/main/java/fr/openmc/core/features/city/menu/playerlist/CityPlayerListMenu.java @@ -1,7 +1,6 @@ package fr.openmc.core.features.city.menu.playerlist; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.default_menu.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; @@ -14,9 +13,9 @@ import fr.openmc.core.features.city.actions.CityKickAction; import fr.openmc.core.features.city.commands.CityCommands; import fr.openmc.core.features.city.menu.CitizensPermsMenu; +import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.CacheOfflinePlayer; import fr.openmc.core.utils.InputUtils; -import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -34,6 +33,8 @@ import java.util.*; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH_PLAYERNAME; + public class CityPlayerListMenu extends PaginatedMenu { public CityPlayerListMenu(Player owner) { @@ -173,35 +174,14 @@ public Map getButtons() { itemMeta.displayName(Component.text("§7Inviter des §dpersonnes")); itemMeta.lore(List.of(Component.text("§7Vous pouvez inviter des personnes à votre ville pour la remplir !"))); }).setOnClick(inventoryClickEvent -> { - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez le nom du "; - lines[3] = "joueur ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(fr.openmc.core.utils.ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - if (InputUtils.isInputPlayer(input)) { - Player playerToInvite = Bukkit.getPlayer(input); - CityCommands.invite(player, playerToInvite); - } else { - MessagesManager.sendMessage(player, Component.text("Veuillez mettre une entrée correcte"), Prefix.CITY, MessageType.ERROR, true); - } - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le nom du joueur"), MAX_LENGTH_PLAYERNAME, input -> { + if (InputUtils.isInputPlayer(input)) { + Player playerToInvite = Bukkit.getPlayer(input); + CityCommands.invite(player, playerToInvite); + } else { + MessagesManager.sendMessage(player, Component.text("Veuillez mettre une entrée correcte"), Prefix.CITY, MessageType.ERROR, true); + } + }); })); return map; } diff --git a/src/main/java/fr/openmc/core/features/city/menu/ranks/CityRankIconMenu.java b/src/main/java/fr/openmc/core/features/city/menu/ranks/CityRankIconMenu.java index 050d67c67..bba87d735 100644 --- a/src/main/java/fr/openmc/core/features/city/menu/ranks/CityRankIconMenu.java +++ b/src/main/java/fr/openmc/core/features/city/menu/ranks/CityRankIconMenu.java @@ -1,20 +1,17 @@ package fr.openmc.core.features.city.menu.ranks; import dev.lone.itemsadder.api.CustomStack; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.models.CityRank; import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.ItemUtils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextDecoration; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; @@ -25,6 +22,8 @@ import java.util.*; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class CityRankIconMenu extends PaginatedMenu { private final CityRank rank; @@ -118,32 +117,9 @@ public Map getButtons() { itemMeta.displayName(Component.text("§bRechercher une icône")); itemMeta.lore(List.of(Component.text("§7Cliquez pour saisir un mot-clé"))); }).setOnClick(event -> { - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre nom"; - lines[3] = "de grade ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(getOwner())) - .setHandler((p, result) -> { - String input = result.getLine(0); - - Bukkit.getScheduler().runTask(OMCPlugin.getInstance(), () -> { - new CityRankIconMenu(getOwner(), city, 0, rank, input).open(); - }); - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(getOwner()); + DialogInput.send(getOwner(), Component.text("Entrez le nom d'un mot clé pour l'icône"), MAX_LENGTH, input -> { + new CityRankIconMenu(getOwner(), city, 0, rank, input).open(); + }); })); if (filter != null && !filter.isEmpty()) { diff --git a/src/main/java/fr/openmc/core/features/city/models/DBCityClaim.java b/src/main/java/fr/openmc/core/features/city/models/DBCityClaim.java index d2d7b251b..21f278653 100644 --- a/src/main/java/fr/openmc/core/features/city/models/DBCityClaim.java +++ b/src/main/java/fr/openmc/core/features/city/models/DBCityClaim.java @@ -2,8 +2,7 @@ import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; -import com.sk89q.worldedit.math.BlockVector2; - +import fr.openmc.core.utils.ChunkPos; import lombok.Getter; @DatabaseTable(tableName = "city_regions") @@ -20,13 +19,13 @@ public class DBCityClaim { // required for ORMLite } - public DBCityClaim(BlockVector2 chunk, String city) { + public DBCityClaim(ChunkPos chunk, String city) { this.city = city; - this.x = chunk.getX(); - this.z = chunk.getZ(); + this.x = chunk.x(); + this.z = chunk.z(); } - public BlockVector2 getBlockVector() { - return BlockVector2.at(x, z); + public ChunkPos getChunkPos() { + return new ChunkPos(x, z); } } diff --git a/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankDepositMenu.java b/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankDepositMenu.java index 62b3c4cca..9a4492658 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankDepositMenu.java +++ b/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankDepositMenu.java @@ -1,7 +1,6 @@ package fr.openmc.core.features.city.sub.bank.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -10,7 +9,6 @@ import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.sub.bank.conditions.CityBankConditions; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -23,11 +21,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class CityBankDepositMenu extends Menu { public CityBankDepositMenu(Player owner) { @@ -145,28 +144,9 @@ public void onInventoryClick(InventoryClickEvent click) { }).setOnClick(inventoryClickEvent -> { if (!CityBankConditions.canCityDeposit(city, player)) return; - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre"; - lines[3] = "montant ci dessus"; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - city.depositCityBank(player, input); - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le montant que vous voulez déposer"), MAX_LENGTH, input -> + city.depositCityBank(player, input) + ); })); diff --git a/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankWithdrawMenu.java b/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankWithdrawMenu.java index 49fbce66f..d3415bb3a 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankWithdrawMenu.java +++ b/src/main/java/fr/openmc/core/features/city/sub/bank/menu/CityBankWithdrawMenu.java @@ -1,7 +1,6 @@ package fr.openmc.core.features.city.sub.bank.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -10,7 +9,6 @@ import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.sub.bank.conditions.CityBankConditions; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -23,11 +21,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class CityBankWithdrawMenu extends Menu { public CityBankWithdrawMenu(Player owner) { @@ -147,28 +146,9 @@ public void onInventoryClick(InventoryClickEvent click) { }).setOnClick(inventoryClickEvent -> { if (!CityBankConditions.canCityWithdraw(city, player)) return; - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre"; - lines[3] = "montant ci dessus"; - - SignGUI gui = null; - try { - gui = SignGUI.builder() - .setLines(null, lines[1], lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - city.withdrawCityBank(player, input); - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); + DialogInput.send(player, Component.text("Entrez le montant que vous voulez retirer"), MAX_LENGTH, input -> + city.withdrawCityBank(player, input) + ); })); diff --git a/src/main/java/fr/openmc/core/features/city/sub/mayor/menu/MayorLawMenu.java b/src/main/java/fr/openmc/core/features/city/sub/mayor/menu/MayorLawMenu.java index 2f4ec5e40..ddfcf7f9a 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/mayor/menu/MayorLawMenu.java +++ b/src/main/java/fr/openmc/core/features/city/sub/mayor/menu/MayorLawMenu.java @@ -320,7 +320,7 @@ public void onClose(InventoryCloseEvent event) { MessagesManager.sendMessage(member, Component.text("Le §6Maire §fa déclenché la §eDissuasion Militaire §f!"), Prefix.MAYOR, MessageType.INFO, false); } - MilitaryDissuasion.spawnIronMan(city, 10); + MilitaryDissuasion.startEvent(city, 10); DynamicCooldownManager.use(city.getUUID(), "city:military_dissuasion", 10 * 60 * 1000L); // 10 minutes DynamicCooldownManager.use(mayor.getUUID().toString(), "mayor:law-perk-event", PerkManager.getPerkEvent(mayor).getCooldown()); diff --git a/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/IdyllicRain.java b/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/IdyllicRain.java index a5a78a903..3c3378254 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/IdyllicRain.java +++ b/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/IdyllicRain.java @@ -1,10 +1,10 @@ package fr.openmc.core.features.city.sub.mayor.perks.event; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.items.CustomItemRegistry; +import fr.openmc.core.utils.ChunkPos; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; @@ -33,13 +33,13 @@ public class IdyllicRain implements Listener { * @param totalItems The total number of items to spawn. */ public static void spawnAywenite(City city, int totalItems) { - Set chunks = city.getChunks(); + Set chunks = city.getChunks(); if (chunks.isEmpty()) return; World world = Bukkit.getWorld("world"); if (world == null) return; - List chunkList = new ArrayList<>(chunks); + List chunkList = new ArrayList<>(chunks); Random random = new Random(); NamespacedKey key = new NamespacedKey(OMCPlugin.getInstance(), "city_aywenite"); @@ -53,9 +53,9 @@ public void run() { return; } - BlockVector2 chunk = chunkList.get(random.nextInt(chunkList.size())); - int chunkX = chunk.getBlockX(); - int chunkZ = chunk.getBlockZ(); + ChunkPos chunk = chunkList.get(random.nextInt(chunkList.size())); + int chunkX = chunk.x(); + int chunkZ = chunk.z(); int x = (chunkX << 4) + random.nextInt(16); int z = (chunkZ << 4) + random.nextInt(16); diff --git a/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/MilitaryDissuasion.java b/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/MilitaryDissuasion.java index 84b9ca887..97b16f27c 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/MilitaryDissuasion.java +++ b/src/main/java/fr/openmc/core/features/city/sub/mayor/perks/event/MilitaryDissuasion.java @@ -1,9 +1,9 @@ package fr.openmc.core.features.city.sub.mayor.perks.event; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; +import fr.openmc.core.utils.ChunkPos; import net.kyori.adventure.text.Component; import org.bukkit.*; import org.bukkit.entity.Entity; @@ -27,14 +27,14 @@ public class MilitaryDissuasion implements Listener { * @param city The city where the golems will be spawned. * @param golemsToSpawn The number of golems to spawn. */ - public static void spawnIronMan(City city, int golemsToSpawn) { - Set chunks = city.getChunks(); + public static void startEvent(City city, int golemsToSpawn) { + Set chunks = city.getChunks(); if (chunks.isEmpty()) return; World world = Bukkit.getWorld("world"); if (world == null) return; - List chunkList = new ArrayList<>(chunks); + List chunkList = new ArrayList<>(chunks); Random random = new Random(); int spawned = 0; @@ -43,10 +43,10 @@ public static void spawnIronMan(City city, int golemsToSpawn) { while (spawned < golemsToSpawn && attempts < golemsToSpawn * 10) { attempts++; - BlockVector2 chunk = chunkList.get(spawned % chunkList.size()); + ChunkPos chunk = chunkList.get(spawned % chunkList.size()); - int chunkX = chunk.getBlockX(); - int chunkZ = chunk.getBlockZ(); + int chunkX = chunk.x(); + int chunkZ = chunk.z(); int x = (chunkX << 4) + 8 + random.nextInt(8); int z = (chunkZ << 4) + 8 + random.nextInt(8); diff --git a/src/main/java/fr/openmc/core/features/city/sub/war/WarManager.java b/src/main/java/fr/openmc/core/features/city/sub/war/WarManager.java index b3042aa95..fa5b1a866 100644 --- a/src/main/java/fr/openmc/core/features/city/sub/war/WarManager.java +++ b/src/main/java/fr/openmc/core/features/city/sub/war/WarManager.java @@ -1,6 +1,5 @@ package fr.openmc.core.features.city.sub.war; -import com.sk89q.worldedit.math.BlockVector2; import fr.openmc.api.cooldown.DynamicCooldownManager; import fr.openmc.core.CommandsManager; import fr.openmc.core.OMCPlugin; @@ -11,6 +10,7 @@ import fr.openmc.core.features.city.sub.war.listeners.TntPlaceListener; import fr.openmc.core.features.city.sub.war.listeners.WarKillListener; import fr.openmc.core.features.economy.EconomyManager; +import fr.openmc.core.utils.ChunkPos; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.entity.LivingEntity; @@ -319,22 +319,22 @@ public static void broadcastWarResult(War war, City winner, City loser, WinReaso public static int transferChunksAfterWar(City winner, City loser, int claimAmount) { if (claimAmount <= 0) return 0; - BlockVector2 mascotVec = BlockVector2.at( + ChunkPos mascotVec = new ChunkPos( loser.getMascot().getChunk().getX(), loser.getMascot().getChunk().getZ() ); - Set adjacentChunks = new HashSet<>(); - for (BlockVector2 wChunk : winner.getChunks()) { - int wx = wChunk.getX(), wz = wChunk.getZ(); + Set adjacentChunks = new HashSet<>(); + for (ChunkPos wChunk : winner.getChunks()) { + int wx = wChunk.x(), wz = wChunk.z(); - BlockVector2[] neighbors = { - BlockVector2.at(wx + 1, wz), - BlockVector2.at(wx - 1, wz), - BlockVector2.at(wx, wz + 1), - BlockVector2.at(wx, wz - 1) + ChunkPos[] neighbors = { + new ChunkPos(wx + 1, wz), + new ChunkPos(wx - 1, wz), + new ChunkPos(wx, wz + 1), + new ChunkPos(wx, wz - 1) }; - for (BlockVector2 nb : neighbors) { + for (ChunkPos nb : neighbors) { if (nb.equals(mascotVec)) continue; if (loser.getChunks().contains(nb)) { @@ -345,23 +345,23 @@ public static int transferChunksAfterWar(City winner, City loser, int claimAmoun final int[] transferred = {0}; - BiConsumer, Set> bfsCapture = (queue, visited) -> { + BiConsumer, Set> bfsCapture = (queue, visited) -> { while (!queue.isEmpty() && transferred[0] < claimAmount) { - BlockVector2 current = queue.poll(); - int cx = current.getX(), cz = current.getZ(); - - BlockVector2[] neighs = { - BlockVector2.at(cx + 1, cz), - BlockVector2.at(cx - 1, cz), - BlockVector2.at(cx, cz + 1), - BlockVector2.at(cx, cz - 1) + ChunkPos current = queue.poll(); + int cx = current.x(), cz = current.z(); + + ChunkPos[] neighs = { + new ChunkPos(cx + 1, cz), + new ChunkPos(cx - 1, cz), + new ChunkPos(cx, cz + 1), + new ChunkPos(cx, cz - 1) }; - for (BlockVector2 nb : neighs) { + for (ChunkPos nb : neighs) { if (visited.contains(nb) || nb.equals(mascotVec)) continue; if (loser.getChunks().contains(nb)) { - loser.removeChunk(nb.getX(), nb.getZ()); - winner.addChunk(nb.getX(), nb.getZ()); + loser.removeChunk(nb.x(), nb.z()); + winner.addChunk(nb.x(), nb.z()); visited.add(nb); queue.add(nb); transferred[0]++; @@ -372,14 +372,14 @@ public static int transferChunksAfterWar(City winner, City loser, int claimAmoun }; if (!adjacentChunks.isEmpty()) { - List toSteal = new ArrayList<>(adjacentChunks); + List toSteal = new ArrayList<>(adjacentChunks); int initialSteal = Math.min(toSteal.size(), claimAmount); - Queue queue = new LinkedList<>(); - Set visited = new HashSet<>(); + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); for (int i = 0; i < initialSteal; i++) { - BlockVector2 c = toSteal.get(i); - loser.removeChunk(c.getX(), c.getZ()); - winner.addChunk(c.getX(), c.getZ()); + ChunkPos c = toSteal.get(i); + loser.removeChunk(c.x(), c.z()); + winner.addChunk(c.x(), c.z()); queue.add(c); visited.add(c); transferred[0]++; @@ -387,18 +387,18 @@ public static int transferChunksAfterWar(City winner, City loser, int claimAmoun bfsCapture.accept(queue, visited); } else { // Try from border - List borderChunks = new ArrayList<>(); - for (BlockVector2 lChunk : loser.getChunks()) { + List borderChunks = new ArrayList<>(); + for (ChunkPos lChunk : loser.getChunks()) { if (lChunk.equals(mascotVec)) continue; - int lx = lChunk.getX(), lz = lChunk.getZ(); - BlockVector2[] neighs = { - BlockVector2.at(lx + 1, lz), - BlockVector2.at(lx - 1, lz), - BlockVector2.at(lx, lz + 1), - BlockVector2.at(lx, lz - 1) + int lx = lChunk.x(), lz = lChunk.z(); + ChunkPos[] neighs = { + new ChunkPos(lx + 1, lz), + new ChunkPos(lx - 1, lz), + new ChunkPos(lx, lz + 1), + new ChunkPos(lx, lz - 1) }; - for (BlockVector2 nb : neighs) { + for (ChunkPos nb : neighs) { if (!loser.getChunks().contains(nb)) { borderChunks.add(lChunk); break; @@ -407,12 +407,12 @@ public static int transferChunksAfterWar(City winner, City loser, int claimAmoun } if (!borderChunks.isEmpty()) { Collections.shuffle(borderChunks); - BlockVector2 seed = borderChunks.get(0); + ChunkPos seed = borderChunks.get(0); - loser.removeChunk(seed.getX(), seed.getZ()); - winner.addChunk(seed.getX(), seed.getZ()); - Queue queue = new LinkedList<>(); - Set visited = new HashSet<>(); + loser.removeChunk(seed.x(), seed.z()); + winner.addChunk(seed.x(), seed.z()); + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); queue.add(seed); visited.add(seed); transferred[0]++; diff --git a/src/main/java/fr/openmc/core/features/contest/menu/TradeMenu.java b/src/main/java/fr/openmc/core/features/contest/menu/TradeMenu.java index cf3b04352..143777232 100644 --- a/src/main/java/fr/openmc/core/features/contest/menu/TradeMenu.java +++ b/src/main/java/fr/openmc/core/features/contest/menu/TradeMenu.java @@ -7,10 +7,10 @@ import fr.openmc.core.features.contest.managers.ContestManager; import fr.openmc.core.features.contest.managers.ContestPlayerManager; import fr.openmc.core.features.mailboxes.MailboxManager; +import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.api.ItemsAdderApi; import fr.openmc.core.utils.api.PapiApi; -import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -28,7 +28,6 @@ import java.util.*; - public class TradeMenu extends Menu { public TradeMenu(Player owner) { diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/shop/ShopSearchMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/shop/ShopSearchMenu.java index 162214511..d1d45c2c8 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/shop/ShopSearchMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/shop/ShopSearchMenu.java @@ -1,7 +1,6 @@ package fr.openmc.core.features.corporation.menu.shop; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -10,10 +9,10 @@ import fr.openmc.core.features.corporation.manager.CompanyManager; import fr.openmc.core.features.corporation.manager.ShopBlocksManager; import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.api.ItemsAdderApi; import fr.openmc.core.utils.api.PapiApi; -import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -28,7 +27,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; public class ShopSearchMenu extends PaginatedMenu { @@ -93,67 +97,47 @@ public Map getButtons() { .setPreviousPageButton()); buttons.put(50, nextPageButton.setNextPageButton()); buttons.put(45, searchButton.setOnClick(inventoryClick -> { - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez le nom"; - lines[3] = "du shop/joueur"; - - SignGUI gui = null; - try { - gui = SignGUI.builder() - .setLines(null, lines[1] , lines[2], lines[3]) - .setType(ItemUtils.getSignType(getOwner())) - .setHandler((p, result) -> { - String input = result.getLine(0); - - boolean shopFind = false; - - for (Shop shop : CompanyManager.shops){ - double x = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockX(); - double y = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockY(); - double z = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockZ(); - - if (shop.getName().contains(input)){ - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a"+ shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - Player player = Bukkit.getPlayer(input); - if (player==null) continue; - if (shop.getOwner().isCompany()){ - Company company = shop.getOwner().getCompany(); - if (company.getAllMembers().contains(player.getUniqueId())){ - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a"+ shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - } - if (shop.getOwner().isPlayer()){ - Player shopPlayer = Bukkit.getPlayer(shop.getOwner().getPlayer()); - if (shopPlayer==null){ - continue; - } - if (shopPlayer.equals(player)){ - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a"+ shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - } - } - - if (!shopFind){ - MessagesManager.sendMessage(getOwner(), Component.text("§cAucun shop trouvé !"), Prefix.SHOP, MessageType.INFO, false); - } - - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(getOwner()); + DialogInput.send(getOwner(), Component.text("Entrez le nom du shop ou bien du joueur pour le rechercher"), MAX_LENGTH, input -> { + boolean shopFind = false; + + for (Shop shop : CompanyManager.shops) { + double x = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockX(); + double y = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockY(); + double z = ShopBlocksManager.getMultiblock(shop.getUuid()).getStockBlock().getBlockZ(); + + if (shop.getName().contains(input)) { + MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); + shopFind = true; + break; + } + Player player = Bukkit.getPlayer(input); + if (player == null) continue; + if (shop.getOwner().isCompany()) { + Company company = shop.getOwner().getCompany(); + if (company.getAllMembers().contains(player.getUniqueId())) { + MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); + shopFind = true; + break; + } + } + if (shop.getOwner().isPlayer()) { + Player shopPlayer = Bukkit.getPlayer(shop.getOwner().getPlayer()); + if (shopPlayer == null) { + continue; + } + if (shopPlayer.equals(player)) { + MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); + shopFind = true; + break; + } + } + } + + if (!shopFind) { + MessagesManager.sendMessage(getOwner(), Component.text("§cAucun shop trouvé !"), Prefix.SHOP, MessageType.INFO, false); + } + + }); })); } return buttons; diff --git a/src/main/java/fr/openmc/core/features/displays/holograms/HologramLoader.java b/src/main/java/fr/openmc/core/features/displays/holograms/HologramLoader.java index 44d1046b1..9f8b506d5 100644 --- a/src/main/java/fr/openmc/core/features/displays/holograms/HologramLoader.java +++ b/src/main/java/fr/openmc/core/features/displays/holograms/HologramLoader.java @@ -77,8 +77,6 @@ public static void registerHolograms(Hologram... holograms) { for (int i = 0; i < hologram.getLines().length; i++) { String rawLine = hologram.getLines()[i]; - System.out.println(rawLine); - if (component == null) { component = Component.text(rawLine); } else { diff --git a/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankDepositMenu.java b/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankDepositMenu.java index 5366daf40..db3deb8a9 100644 --- a/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankDepositMenu.java +++ b/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankDepositMenu.java @@ -1,13 +1,11 @@ package fr.openmc.core.features.economy.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.economy.BankManager; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -20,11 +18,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class PersonalBankDepositMenu extends Menu { public PersonalBankDepositMenu(Player owner) { @@ -108,30 +107,9 @@ public void onInventoryClick(InventoryClickEvent click) { itemMeta.itemName(Component.text("§7Déposer un §6montant précis")); itemMeta.lore(loreBankDepositInput); }).setOnClick(inventoryClickEvent -> { - - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre"; - lines[3] = "montant ci dessus"; - - SignGUI gui = null; - try { - gui = SignGUI.builder() - .setLines(null, lines[1] , lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - BankManager.addBankBalance(player, input); - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); - + DialogInput.send(player, Component.text("Entrez le montant que vous voulez déposer"), MAX_LENGTH, input -> + BankManager.addBankBalance(player, input) + ); })); inventory.put(18, new ItemBuilder(this, Material.ARROW, itemMeta -> { diff --git a/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankWithdrawMenu.java b/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankWithdrawMenu.java index 0fbfa834c..ba4017d5b 100644 --- a/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankWithdrawMenu.java +++ b/src/main/java/fr/openmc/core/features/economy/menu/PersonalBankWithdrawMenu.java @@ -1,13 +1,11 @@ package fr.openmc.core.features.economy.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.economy.BankManager; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -20,11 +18,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class PersonalBankWithdrawMenu extends Menu { public PersonalBankWithdrawMenu(Player owner) { @@ -110,30 +109,9 @@ public void onInventoryClick(InventoryClickEvent click) { itemMeta.itemName(Component.text("§7Prendre un §6montant précis")); itemMeta.lore(loreBankWithdrawInput); }).setOnClick(inventoryClickEvent -> { - - String[] lines = new String[4]; - lines[0] = ""; - lines[1] = " ᐱᐱᐱᐱᐱᐱᐱ "; - lines[2] = "Entrez votre"; - lines[3] = "montant ci dessus"; - - SignGUI gui = null; - try { - gui = SignGUI.builder() - .setLines(null, lines[1] , lines[2], lines[3]) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - BankManager.withdrawBankBalance(player, input); - return Collections.emptyList(); - }) - .build(); - } catch (SignGUIVersionException e) { - throw new RuntimeException(e); - } - - gui.open(player); - + DialogInput.send(player, Component.text("Entrez le montant que vous voulez retirer"), MAX_LENGTH, input -> + BankManager.withdrawBankBalance(player, input) + ); })); inventory.put(18, new ItemBuilder(this, Material.ARROW, itemMeta -> { diff --git a/src/main/java/fr/openmc/core/features/homes/menu/HomeChangeIconMenu.java b/src/main/java/fr/openmc/core/features/homes/menu/HomeChangeIconMenu.java index 72bcdba30..91ee1388e 100644 --- a/src/main/java/fr/openmc/core/features/homes/menu/HomeChangeIconMenu.java +++ b/src/main/java/fr/openmc/core/features/homes/menu/HomeChangeIconMenu.java @@ -1,7 +1,6 @@ package fr.openmc.core.features.homes.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; @@ -10,7 +9,6 @@ import fr.openmc.core.features.homes.icons.IconCategory; import fr.openmc.core.features.homes.models.Home; import fr.openmc.core.features.mailboxes.utils.MailboxMenuManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; @@ -31,6 +29,8 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; + public class HomeChangeIconMenu extends PaginatedMenu { private final Home home; @@ -111,34 +111,13 @@ public Map getButtons() { }).setOnClick(event -> { if (event.getClick().isLeftClick()) { getOwner().closeInventory(); - String[] lines = { - "", - " ᐱᐱᐱᐱᐱᐱᐱ ", - "Entrez votre", - "nom ci dessus" - }; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(lines) - .setType(ItemUtils.getSignType(getOwner())) - .setHandler((p, result) -> { - searchQuery = result.getLine(0); - currentCategory = IconCategory.ALL; - setPage(0); - refresh(); - - return Collections.emptyList(); - }) - .build(); - - gui.open(getOwner()); - } catch (SignGUIVersionException e) { - MessagesManager.sendMessage(getOwner(), - Component.text("§cUne erreur est survenue, veuillez contacter le Staff"), - Prefix.OPENMC, MessageType.ERROR, false); - } + + DialogInput.send(getOwner(), Component.text("Entrez votre recherche pour un item"), MAX_LENGTH, input -> { + searchQuery = input; + currentCategory = IconCategory.ALL; + setPage(0); + refresh(); + }); } else if (event.getClick().isRightClick()) { searchQuery = ""; refresh(); diff --git a/src/main/java/fr/openmc/core/features/homes/menu/HomeConfigMenu.java b/src/main/java/fr/openmc/core/features/homes/menu/HomeConfigMenu.java index a3088d5a1..50ffe3fc9 100644 --- a/src/main/java/fr/openmc/core/features/homes/menu/HomeConfigMenu.java +++ b/src/main/java/fr/openmc/core/features/homes/menu/HomeConfigMenu.java @@ -1,18 +1,16 @@ package fr.openmc.core.features.homes.menu; -import fr.openmc.api.input.signgui.SignGUI; -import fr.openmc.api.input.signgui.exception.SignGUIVersionException; +import fr.openmc.api.input.DialogInput; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.homes.HomesManager; -import fr.openmc.core.features.homes.models.Home; import fr.openmc.core.features.homes.icons.HomeIconRegistry; +import fr.openmc.core.features.homes.models.Home; import fr.openmc.core.features.homes.utils.HomeUtil; import fr.openmc.core.features.mailboxes.utils.MailboxMenuManager; -import fr.openmc.core.utils.ItemUtils; -import fr.openmc.core.utils.customfonts.CustomFonts; import fr.openmc.core.items.CustomItemRegistry; +import fr.openmc.core.utils.customfonts.CustomFonts; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -31,6 +29,8 @@ import java.util.*; +import static fr.openmc.core.features.homes.utils.HomeUtil.MAX_LENGTH_HOME_NAME; + public class HomeConfigMenu extends Menu { private final Home home; @@ -74,49 +74,26 @@ public HomeConfigMenu(Player owner, Home home) { .build(); itemMeta.lore(Collections.singletonList(lore)); }).setOnClick(e -> { - String[] lines = { - "", - " ᐱᐱᐱᐱᐱᐱᐱ ", - "Entrez votre", - "nom ci dessus" - }; - - SignGUI gui; - try { - gui = SignGUI.builder() - .setLines(lines) - .setType(ItemUtils.getSignType(player)) - .setHandler((p, result) -> { - String input = result.getLine(0); - - if (!HomeUtil.isValidHomeName(input)) - return Collections.emptyList(); - - if (HomesManager.getHomesNames(p.getUniqueId()).contains(input)) { - TextComponent message = Component.text("Tu as déjà un home avec ce nom.", NamedTextColor.RED); - MessagesManager.sendMessage(player, message, Prefix.HOME, MessageType.ERROR, true); - return Collections.emptyList(); - } - - TextComponent message = Component.text() - .append(Component.text("Ton home ", NamedTextColor.GREEN)) - .append(Component.text(home.getName(), NamedTextColor.YELLOW)) - .append(Component.text(" a été renommé en ", NamedTextColor.GREEN)) - .append(Component.text(input, NamedTextColor.YELLOW)) - .append(Component.text(".", NamedTextColor.GREEN)) - .build(); - - MessagesManager.sendMessage(player, message, Prefix.HOME, MessageType.SUCCESS, true); - HomesManager.renameHome(home, input); - - return Collections.emptyList(); - }) + DialogInput.send(getOwner(), Component.text("Entrez votre nouveau nom de home"), MAX_LENGTH_HOME_NAME, input -> { + if (!HomeUtil.isValidHomeName(input)) return; + + if (HomesManager.getHomesNames(getOwner().getUniqueId()).contains(input)) { + TextComponent message = Component.text("Tu as déjà un home avec ce nom.", NamedTextColor.RED); + MessagesManager.sendMessage(player, message, Prefix.HOME, MessageType.ERROR, true); + return; + } + + TextComponent message = Component.text() + .append(Component.text("Ton home ", NamedTextColor.GREEN)) + .append(Component.text(home.getName(), NamedTextColor.YELLOW)) + .append(Component.text(" a été renommé en ", NamedTextColor.GREEN)) + .append(Component.text(input, NamedTextColor.YELLOW)) + .append(Component.text(".", NamedTextColor.GREEN)) .build(); - } catch (SignGUIVersionException ex) { - throw new RuntimeException(ex); - } - gui.open(player); + MessagesManager.sendMessage(player, message, Prefix.HOME, MessageType.SUCCESS, true); + HomesManager.renameHome(home, input); + }); })); content.put(24, new ItemBuilder(this, Objects.requireNonNull(CustomItemRegistry.getByName("omc_homes:omc_homes_icon_bin_red")).getBest(), itemMeta -> { diff --git a/src/main/java/fr/openmc/core/features/homes/utils/HomeUtil.java b/src/main/java/fr/openmc/core/features/homes/utils/HomeUtil.java index f89a1e619..38888336a 100644 --- a/src/main/java/fr/openmc/core/features/homes/utils/HomeUtil.java +++ b/src/main/java/fr/openmc/core/features/homes/utils/HomeUtil.java @@ -1,14 +1,15 @@ package fr.openmc.core.features.homes.utils; -import fr.openmc.core.features.homes.models.Home; -import fr.openmc.core.features.homes.icons.OldHomeIcon; import fr.openmc.core.features.homes.icons.HomeIcon; import fr.openmc.core.features.homes.icons.HomeIconRegistry; +import fr.openmc.core.features.homes.icons.OldHomeIcon; +import fr.openmc.core.features.homes.models.Home; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; public class HomeUtil { + public static final int MAX_LENGTH_HOME_NAME = 32; @Deprecated public static HomeIcon getHomeIcon(String iconId) { if (iconId == null || iconId.isEmpty()) @@ -64,7 +65,7 @@ public static boolean isValidHomeName(String name) { name == null || name.trim().isEmpty() || name.length() < 3 || - name.length() > 32 + name.length() > MAX_LENGTH_HOME_NAME ) return false; long alphanumericCount = name.chars().filter(Character::isLetterOrDigit).count(); diff --git a/src/main/java/fr/openmc/core/listeners/HappyGhastListener.java b/src/main/java/fr/openmc/core/listeners/HappyGhastListener.java new file mode 100644 index 000000000..f1019c4a6 --- /dev/null +++ b/src/main/java/fr/openmc/core/listeners/HappyGhastListener.java @@ -0,0 +1,36 @@ +package fr.openmc.core.listeners; + +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntitySpawnEvent; + +public class HappyGhastListener implements Listener { + private final double DEFAULT_FLYING_SPEED = 0.05; + + @EventHandler(ignoreCancelled = true) + public void onHappyGhastSpawn(EntitySpawnEvent event) { + if (event.getEntityType() != EntityType.HAPPY_GHAST) return; + + LivingEntity entity = (LivingEntity) event.getEntity(); + + AttributeInstance attr = entity.getAttribute(Attribute.FLYING_SPEED); + if (attr == null) return; + + double multiplier = getMultiplier(); + attr.setBaseValue(DEFAULT_FLYING_SPEED * multiplier); + } + + // Effet de rareté, plus c'est proche de 1.6, plus c'est rare + private double getMultiplier() { + double min = 1.0; + double max = 1.6; + double random = Math.random(); + double biased = 1 - Math.pow(random, 3); + return min + (max - min) * biased; + } + +} diff --git a/src/main/java/fr/openmc/core/utils/ChunkPos.java b/src/main/java/fr/openmc/core/utils/ChunkPos.java index 88b5f232e..8cc259b50 100644 --- a/src/main/java/fr/openmc/core/utils/ChunkPos.java +++ b/src/main/java/fr/openmc/core/utils/ChunkPos.java @@ -1,24 +1,39 @@ package fr.openmc.core.utils; -public class ChunkPos { - final int x, z; - public ChunkPos(int x, int z) { this.x = x; this.z = z; } +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ChunkPos chunkPos = (ChunkPos) o; - return x == chunkPos.x && z == chunkPos.z; +public record ChunkPos(int x, int z) { + + public Chunk getChunkInWorld() { + World world = Bukkit.getWorld("world"); + if (world == null) { + throw new IllegalStateException("World 'world' does not exist."); + } + + return world.getChunkAt(x, z); } - @Override - public int hashCode() { - return 31 * x + z; + /** + * Get the distance between this vector and another vector. + * + * @param other the other vector + * @return distance + */ + public double distance(ChunkPos other) { + return Math.sqrt(distanceSq(other)); } - @Override - public String toString() { - return x + "," + z; + /** + * Get the distance between this vector and another vector, squared. + * + * @param other the other vector + * @return distance + */ + public int distanceSq(ChunkPos other) { + int dx = other.x - x; + int dz = other.z - z; + return dx * dx + dz * dz; } } diff --git a/src/main/java/fr/openmc/core/utils/InputUtils.java b/src/main/java/fr/openmc/core/utils/InputUtils.java index 916441cf6..5892bbcff 100644 --- a/src/main/java/fr/openmc/core/utils/InputUtils.java +++ b/src/main/java/fr/openmc/core/utils/InputUtils.java @@ -6,6 +6,10 @@ public class InputUtils { + public static final int MAX_LENGTH = 100; + public static final int MAX_LENGTH_CITY = 24; + public static final int MAX_LENGTH_PLAYERNAME = 16; + private InputUtils() { // for Sonar } @@ -83,7 +87,7 @@ public static boolean isInputCityName(String input) { return false; } - if (input.length() > 24) { + if (input.length() > MAX_LENGTH_CITY) { return false; } @@ -108,6 +112,10 @@ public static boolean isInputPlayer(String input) { return false; } + if (input.length() > MAX_LENGTH_PLAYERNAME) { + return false; + } + return Bukkit.getPlayer(input) != null; } } diff --git a/src/main/java/fr/openmc/core/utils/ParticleUtils.java b/src/main/java/fr/openmc/core/utils/ParticleUtils.java index 3b5d0acd9..0c466d660 100644 --- a/src/main/java/fr/openmc/core/utils/ParticleUtils.java +++ b/src/main/java/fr/openmc/core/utils/ParticleUtils.java @@ -20,10 +20,10 @@ import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import java.util.Random; - public class ParticleUtils { + private static final double MAX_PARTICLE_DISTANCE_SQR = 100 * 100; + public static Color color1; public static Color color2; @@ -40,7 +40,7 @@ public enum ParticleNms { } - public static void spawnParticlesInRegion(String regionId, World world, Particle particle, Integer amountPer2Tick, Integer maxHeight) { + public static void spawnParticlesInRegion(String regionId, World world, Particle particle, int amountPer2Tick, int minHeight, int maxHeight) { RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(world)); if (regionManager == null) return; @@ -50,19 +50,18 @@ public static void spawnParticlesInRegion(String regionId, World world, Particle BlockVector3 min = region.getMinimumPoint(); BlockVector3 max = region.getMaximumPoint(); - Location minLocation = new Location(world, min.getX(), min.getY(), min.getZ()); - Location maxLocation = new Location(world, max.getX(), max.getY(), max.getZ()); + Location minLocation = new Location(world, min.x(), minHeight, min.z()); + Location maxLocation = new Location(world, max.x(), maxHeight, max.z()); new BukkitRunnable() { @Override public void run() { if (ContestManager.data.getPhase() == 3) return; - Random random = new Random(); for (int i = 0; i < amountPer2Tick; i++) { - double x = minLocation.getX() + random.nextDouble() * (maxLocation.getX() - minLocation.getX()); - double y = minLocation.getY() + random.nextDouble() * (maxHeight - minLocation.getY()); - double z = minLocation.getZ() + random.nextDouble() * (maxLocation.getZ() - minLocation.getZ()); + double x = RandomUtils.randomBetween(minLocation.getX(), maxLocation.getX()); + double y = RandomUtils.randomBetween(minLocation.getY(), maxLocation.getY()); + double z = RandomUtils.randomBetween(minLocation.getZ(), maxLocation.getZ()); Location particleLocation = new Location(world, x, y, z); @@ -106,12 +105,10 @@ public static void spawnContestParticlesInRegion(String regionId, World world, i BlockVector3 min = region.getMinimumPoint(); BlockVector3 max = region.getMaximumPoint(); - Location minLocation = new Location(world, min.getX(), min.getY(), min.getZ()); - Location maxLocation = new Location(world, max.getX(), max.getY(), max.getZ()); + Location minLocation = new Location(world, min.x(), minHeight, min.z()); + Location maxLocation = new Location(world, max.x(), maxHeight, max.z()); new BukkitRunnable() { - final Random random = new Random(); - @Override public void run() { if (ContestManager.data.getPhase() != 3) return; @@ -139,18 +136,18 @@ public void run() { } for (int i = 0; i < amountPer2Tick; i++) { - double x = minLocation.getX() + random.nextDouble() * (maxLocation.getX() - minLocation.getX()); - double y = minHeight + random.nextDouble() * (maxHeight - minHeight); - double z = minLocation.getZ() + random.nextDouble() * (maxLocation.getZ() - minLocation.getZ()); + double x = RandomUtils.randomBetween(minLocation.getX(), maxLocation.getX()); + double y = RandomUtils.randomBetween(minLocation.getY(), maxLocation.getY()); + double z = RandomUtils.randomBetween(minLocation.getZ(), maxLocation.getZ()); Location base = new Location(world, x, y, z); spawnRisingDustParticle(regionId, world, base, color1, 1.0f, 15, 1); } for (int i = 0; i < amountPer2Tick; i++) { - double x = minLocation.getX() + random.nextDouble() * (maxLocation.getX() - minLocation.getX()); - double y = minHeight + random.nextDouble() * (maxHeight - minHeight); - double z = minLocation.getZ() + random.nextDouble() * (maxLocation.getZ() - minLocation.getZ()); + double x = RandomUtils.randomBetween(minLocation.getX(), maxLocation.getX()); + double y = RandomUtils.randomBetween(minLocation.getY(), maxLocation.getY()); + double z = RandomUtils.randomBetween(minLocation.getZ(), maxLocation.getZ()); Location base = new Location(world, x, y, z); spawnRisingDustParticle(regionId, world, base, color2, 1.0f, 15, 1); @@ -189,7 +186,7 @@ public void run() { if (!region.contains(BukkitAdapter.asBlockVector(player.getLocation()))) continue; - if (player.getLocation().distanceSquared(origin) > 100 * 100) continue; + if (player.getLocation().distanceSquared(origin) > MAX_PARTICLE_DISTANCE_SQR) continue; ServerPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); ClientboundLevelParticlesPacket packet = new ClientboundLevelParticlesPacket( diff --git a/src/main/java/fr/openmc/core/utils/RandomUtils.java b/src/main/java/fr/openmc/core/utils/RandomUtils.java new file mode 100644 index 000000000..81c533abc --- /dev/null +++ b/src/main/java/fr/openmc/core/utils/RandomUtils.java @@ -0,0 +1,28 @@ +package fr.openmc.core.utils; + +import java.util.Random; + +public class RandomUtils { + private static final Random random = new Random(); + + /** + * Retourne un double aléatoire entre min et max. + */ + public static double randomBetween(double min, double max) { + return min + random.nextDouble() * (max - min); + } + + /** + * Retourne un float aléatoire entre min et max. + */ + public static float randomBetween(float min, float max) { + return min + random.nextFloat() * (max - min); + } + + /** + * Retourne un int aléatoire entre min et max. + */ + public static int randomBetween(int min, int max) { + return min + random.nextInt((max - min) + 1); + } +} \ No newline at end of file diff --git a/src/main/java/fr/openmc/core/utils/dialog/ButtonType.java b/src/main/java/fr/openmc/core/utils/dialog/ButtonType.java new file mode 100644 index 000000000..c9900b030 --- /dev/null +++ b/src/main/java/fr/openmc/core/utils/dialog/ButtonType.java @@ -0,0 +1,18 @@ +package fr.openmc.core.utils.dialog; + +import lombok.Getter; + +public enum ButtonType { + CONFIRM("Confirmer"), + CANCEL("Annuler"), + BACK("Retour"), + NEXT("Suivant"), + PREVIOUS("Précédent"); + + @Getter + private final String label; + + ButtonType(String label) { + this.label = label; + } +} diff --git a/src/main/resources/data/motd.yml b/src/main/resources/data/motd.yml index 3ebb8699b..ebed7d7d1 100644 --- a/src/main/resources/data/motd.yml +++ b/src/main/resources/data/motd.yml @@ -3,8 +3,8 @@ ##### motds: - motd1: - line1: "§d§lOPENMC V2 §r§8- §7Le serveur Open Source §8- §d1.21.5" + line1: "§d§lOPENMC V2 §r§8- §7Le serveur Open Source §8- §d1.21.8" line2: " §6§lCONTEST UPDATE §3§lCITY UPDATE §d§lV2 UPDATE " - motd2: - line1: "§d§lOPENMC V2 §r§8- §7Le serveur Open Source §8- §d1.21.5" + line1: "§d§lOPENMC V2 §r§8- §7Le serveur Open Source §8- §d1.21.8" line2: " §3§lV2 UPDATE " \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5f9436f2d..964701e72 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,10 +1,7 @@ name: OpenMC version: ${version} main: fr.openmc.core.OMCPlugin -api-version: '1.21.5' - -depend: - - WorldEdit +api-version: '1.21.8' softdepend: - FancyNpcs diff --git a/src/test/resources/plugin.yml b/src/test/resources/plugin.yml index 9ca306fe3..cd1ffab7a 100644 --- a/src/test/resources/plugin.yml +++ b/src/test/resources/plugin.yml @@ -1,5 +1,5 @@ name: OpenMC version: ${version} main: fr.openmc.core.TestPlugin -api-version: '1.21.5' +api-version: '1.21.8' prefix: OMC diff --git a/third_party_licenses/SignGUI_LICENSE b/third_party_licenses/SignGUI_LICENSE deleted file mode 100644 index 1abfd6941..000000000 --- a/third_party_licenses/SignGUI_LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 Rapha149 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file