From 8acfb1b8078b87c41667cd550e013019030a3300 Mon Sep 17 00:00:00 2001 From: AbulQasemFerdowsi <6b6t.ir@gmail.com> Date: Sat, 6 Jan 2024 12:39:37 +0330 Subject: [PATCH] Cleanup + Docstring (YEs AgaIn) --- .../EventCore/Commands/EventCommand.java | 233 +++++++++++++----- .../eventcore/Managers/InventoryManager.java | 189 +++++++++----- 2 files changed, 306 insertions(+), 116 deletions(-) diff --git a/src/main/java/ir/Mehran1022/EventCore/Commands/EventCommand.java b/src/main/java/ir/Mehran1022/EventCore/Commands/EventCommand.java index 5ce336d..2fcddad 100644 --- a/src/main/java/ir/Mehran1022/EventCore/Commands/EventCommand.java +++ b/src/main/java/ir/Mehran1022/EventCore/Commands/EventCommand.java @@ -48,74 +48,100 @@ of this software and associated documentation files (the "Software"), to deal public final class EventCommand implements CommandExecutor, TabCompleter { public static Boolean Active = false; - public static String EventDesc; - public static List Players = new ArrayList<>(); private static BossBar bossBar; + /** + * Handles the command execution. + * + * @param sender the command sender + * @param command the command object + * @param label the command label + * @param args the command arguments + * @return true if the command was handled successfully, false otherwise + */ @Override public boolean onCommand(final @NotNull CommandSender sender, final Command command, final @NotNull String label, final String[] args) { + // Check if the sender is a player if (!(sender instanceof Player)) { Common.sendMessage(sender, "Only Players Allowed."); return true; } + + // Check if the command is "event" if (!command.getName().equalsIgnoreCase("event")) { return true; } + // Check if there are no arguments if (args.length == 0) { if (!(sender instanceof Player)) { return true; } - Player player = (Player) sender; - InventoryManager inventoryManage = new InventoryManager(); + final Player player = (Player) sender; - inventoryManage.openInventory(player, (player.hasPermission("eventcore.admin") ? InventoryManager.Role.ADMIN : InventoryManager.Role.PLAYER)); + // Open the inventory for the player + new InventoryManager().openInventory(player, (player.hasPermission("eventcore.admin") ? InventoryManager.Role.ADMIN : InventoryManager.Role.PLAYER)); Common.logDebug("[Debug] Opened a GUI for " + player.getName()); return true; } - switch(args[0]){ - case "reload":{ + + // Handle different command arguments + switch (args[0]) { + case "reload": { + // Check if the sender has the admin permission if (!sender.hasPermission("eventcore.admin")) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); return true; } - long start = System.currentTimeMillis(); + + final long start = System.currentTimeMillis(); + + // Reload the config ConfigManager.loadConfig(); - long time = System.currentTimeMillis() - start; - Common.sendMessage(sender, ConfigManager.PREFIX + "&aTook &c" + time + "ms &aTo Reload."); + Common.sendMessage(sender, String.format("%s&aTook &c%s &aTo Reload.", ConfigManager.PREFIX, System.currentTimeMillis() - start)); return true; } - case "help":{ + case "help": { + // Send the help message sendHelpMessage(sender); return true; } - case "start":{ + case "start": { + // Check if the sender has the admin permission if (!sender.hasPermission("eventcore.admin")) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); return true; } + + // Check if the event is already active if (Active) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.ALREADY_STARTED); return true; } + + // Start the event startEvent(sender, args); } - case "join":{ + case "join": { + // Handle the join command handleJoinCommand(sender); return true; } - case "end":{ + case "end": { + // Handle the end command handleEndCommand(sender); return true; } - case "block":{ + case "block": { + // Handle the block command handleBlockCommand(sender, args); return true; } - case "unblock":{ + case "unblock": { + // Handle the unblock command handleUnblockCommand(sender, args); return true; } @@ -123,54 +149,87 @@ public boolean onCommand(final @NotNull CommandSender sender, final Command comm return true; } + /** + * Generates a list of tab completions for a command. + * + * @param sender the command sender + * @param cmd the command being tab completed + * @param s the alias or label of the command being tab completed + * @param args the arguments provided by the command sender + * @return a list of tab completions + */ @Override public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, @NotNull String[] args) { - List suggestions = new ArrayList<>(); + final List suggestions = new ArrayList<>(); + + // Generate suggestions based on the number of arguments if (args.length == 1) { suggestions.addAll(getCommandSuggestions(sender)); } else if (args.length == 2 && (args[1].equalsIgnoreCase("Block") || args[1].equalsIgnoreCase("UnBlock")) && sender.hasPermission("eventcore.admin")) { suggestions.addAll(getPlayerNameSuggestions()); } + return suggestions; } + /** + * Sends a help message to the command sender. + * + * @param sender The command sender to send the message to. + */ private void sendHelpMessage(CommandSender sender) { + // Send plugin version Common.sendMessage(sender, ConfigManager.PREFIX + "Event-Core v" + Main.getInstance().getDescription().getVersion()); - String[] messages = { - " &a/Event &f- &cOpens " + (sender.hasPermission("eventcore.admin") ? "Admin" : "Player") + " Panel.", - " &a/Event Help &f- &cSends help Message.", - " &a/Event Join &f- &cSends you to events server." - }; + + // Build the help message + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(" &a/Event &f- &cOpens ").append(sender.hasPermission("eventcore.admin") ? "Admin" : "Player").append(" Panel.\n"); + stringBuilder.append(" &a/Event Help &f- &cSends help Message.\n"); + stringBuilder.append(" &a/Event Join &f- &cSends you to events server."); + + // Add admin commands if the sender has admin permission if (sender.hasPermission("eventcore.admin")) { - messages = new String[]{ - " &a/Event &f- &cOpens " + (sender.hasPermission("eventcore.admin") ? "Admin" : "Player") + " Panel.", - " &a/Event Help &f- &cSends help Message.", - " &a/Event Join &f- &cSends you to events server.", - " &a/Event End &f- &cCloses any open event.", - " &a/Event Reload &f- &cReloads plugin configuration files.", - " &a/Event Block &f- &cBlocks a player.", - " &a/Event UnBlock &f- &cUnBlocks a player." - }; + stringBuilder.append('\n'); + stringBuilder.append(" &a/Event End &f- &cCloses any open event.\n"); + stringBuilder.append(" &a/Event Reload &f- &cReloads plugin configuration files.\n"); + stringBuilder.append(" &a/Event Block &f- &cBlocks a player.\n"); + stringBuilder.append(" &a/Event UnBlock &f- &cUnBlocks a player."); } - for (String message : messages) - Common.sendMessage(sender, message); + // Send the help message + Common.sendMessage(sender, stringBuilder.toString()); } + /** + * Starts the event by creating a boss bar, broadcasting a message, adding players to the boss bar, sending titles to players, + * and scheduling a task to end the event after a certain duration. + * + * @param sender the command sender + * @param args the command arguments + */ private void startEvent(CommandSender sender, String[] args) { Active = true; Players.clear(); + + // Create the boss bar string String BossbarString = ConfigManager.BOSSBAR.replace("[Desc]", args.length >= 2 && args[1] != null ? String.join(" ", args).substring(6) : ConfigManager.NO_DESC); + + // Create the boss bar bossBar = Bukkit.createBossBar(BossbarString, getRandomBarColor(), getRandomBarStyle()); + + // Broadcast the event description message Bukkit.broadcastMessage(Common.color(ConfigManager.PREFIX + EventDesc)); -// Common.sendMessageToBungee(ConfigManager.PREFIX + EventDesc); + + // Add players to the boss bar and send titles to players for (Player P : Bukkit.getOnlinePlayers()) { bossBar.addPlayer(P); P.sendTitle(Common.color(ConfigManager.TITLE), Common.color(ConfigManager.SUBTITLE), ConfigManager.FADEIN, ConfigManager.STAY, ConfigManager.FADEOUT); } + // Send action bar message to the sender Common.sendActionBar((Player) sender, "&a&lSuccessfully Created An Event With Duration Of " + ConfigManager.DURATION + " Seconds."); + // Schedule a task to end the event after a certain duration new BukkitRunnable() { @Override public void run() { @@ -184,102 +243,170 @@ public void run() { }.runTaskLater(Main.getInstance(), ConfigManager.DURATION * 20L); } + /** + * Handles the join command for the event. + * + * @param sender The command sender + */ private void handleJoinCommand(CommandSender sender) { Player player = (Player) sender; + + // Check if the event is active if (!Active) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.NO_EVENT); return; - } else if(Main.playersData.contains(player.getUniqueId().toString()) && Objects.equals(Main.playersData.get(player.getUniqueId().toString() + ".BANNED"), true)){ + } + + // Check if the player is banned + if (Main.playersData.contains(player.getUniqueId().toString()) && Objects.equals(Main.playersData.get(player.getUniqueId() + ".BANNED"), true)) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.BLOCKED); return; - }else if (Main.playersData.contains(player.getUniqueId().toString()) && Objects.equals(Main.playersData.get(player.getUniqueId().toString() + ".BANNED"), true)) { + } + + // Check if the player is already banned + if (Main.playersData.contains(player.getUniqueId().toString()) && Objects.equals(Main.playersData.get(player.getUniqueId() + ".BANNED"), true)) { Common.sendMessage(player, ConfigManager.PREFIX + ConfigManager.BLOCKED); return; } - if (Players.contains(player)) + + // Check if the player is already connected + if (Players.contains(player)) { Common.sendMessage(player, ConfigManager.PREFIX + "&cAlready Connected."); - else { + } else { Players.add(player); + + // Subtract the event cost from the player's bank if economy plugin found and cost is enabled if (Main.economyPluginFound && ConfigManager.ENABLE_COST) { - EconomyResponse response = Main.getEconomy().withdrawPlayer(player, ConfigManager.COST); - Common.sendMessage(player, ConfigManager.PREFIX + "This Event Subtracted " + ConfigManager.COST.toString() + "$ From Your Bank. You Have " + Main.getEconomy().format(response.balance) + "$ Now"); + Common.sendMessage(player, ConfigManager.PREFIX + "This Event Subtracted " + ConfigManager.COST.toString() + "$ From Your Bank. You Have " + Main.getEconomy().format(Main.getEconomy().withdrawPlayer(player, ConfigManager.COST).balance) + "$ Now"); System.out.println("Withdrew " + ConfigManager.COST + " From " + player.getName()); } + + // Send the player to another server Common.sendToAnotherServer(player, ConfigManager.SERVER_NAME); + + // Broadcast that the player has joined the event Bukkit.broadcastMessage(Common.color(ConfigManager.PREFIX + "&b" + player.getName() + "&f Has Joined The Event.")); } } + /** + * Handles the end command. + * + * @param sender The command sender + */ private void handleEndCommand(CommandSender sender) { + // Check if the sender has the admin permission if (!sender.hasPermission("eventcore.admin")) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); return; } + + // Check if there is an active event if (!Active) { Common.sendMessage(sender, ConfigManager.PREFIX + ConfigManager.NO_EVENT); return; } + + // Set the active flag to false and clear the players list Active = false; Players.clear(); + + // Remove the boss bar and broadcast the end message bossBar.removeAll(); Bukkit.broadcastMessage(Common.color(ConfigManager.PREFIX + ConfigManager.END)); + + // Send a message to the sender indicating that the event has been closed Common.sendMessage(sender, ConfigManager.PREFIX + "&aClosed The Active Event."); } + /** + * Handles the block command. + * + * @param sender the command sender + * @param args the command arguments + */ private void handleBlockCommand(CommandSender sender, String[] args) { + // Check if the sender has the admin permission if (!sender.hasPermission("eventcore.admin")) { sender.sendMessage(ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); return; } + + // Check if the arguments array has at least one element if (args[1].length() < 1) { return; } - Player player = Bukkit.getPlayer(args[1]); + + // Get the player with the given name + final Player player = Bukkit.getPlayer(args[1]); + + // Check if the player is offline if (player == null) { Common.sendMessage(sender, ConfigManager.PREFIX + (ConfigManager.OFFLINE).replace("[Player]", args[1])); return; } - String playerName = player.getName(); - UUID uuid = player.getUniqueId(); - if (Main.playersData.contains(uuid.toString())) { - Main.playersData.set(uuid.toString() + ".BANNED", true); + + // Ban the player and save the updated player data + if (Main.playersData.contains(player.getUniqueId().toString())) { + Main.playersData.set(player.getUniqueId() + ".BANNED", true); try { Main.playersData.save(Main.file); } catch (IOException e) { e.printStackTrace(); } - Common.sendMessage(sender, ConfigManager.PREFIX + (ConfigManager.BLOCK).replace("[Player]", playerName)); + Common.sendMessage(sender, ConfigManager.PREFIX + (ConfigManager.BLOCK).replace("[Player]", player.getName())); } } + /** + * Handle the unblock command. + * + * @param sender the command sender + * @param args the command arguments + */ private void handleUnblockCommand(CommandSender sender, String[] args) { + // Check if the sender has the admin permission if (!sender.hasPermission("eventcore.admin")) { sender.sendMessage(ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); return; } + + // Check if the arguments array has at least one element if (args[1].length() < 1) { return; } + + // Get the player by their name Player player = Bukkit.getPlayer(args[1]); if (player == null) { + // Send a message if the player is offline Common.sendMessage(sender, ConfigManager.PREFIX + (ConfigManager.OFFLINE).replace("[Player]", args[1])); return; } + + // Get the player's name and UUID String playerName = player.getName(); UUID uuid = player.getUniqueId(); + + // Check if the player's UUID is in the playersData list if (Main.playersData.contains(uuid.toString())) { - Main.playersData.set(uuid.toString() + ".BANNED", false); + // Set the "BANNED" key to false in the playersData list + Main.playersData.set(uuid + ".BANNED", false); + try { + // Save the playersData list to file Main.playersData.save(Main.file); } catch (IOException e) { e.printStackTrace(); } + + // Send a message to the sender indicating that the player has been unblocked Common.sendMessage(sender, ConfigManager.PREFIX + (ConfigManager.UNBLOCK).replace("[Player]", playerName)); } } private List getCommandSuggestions(CommandSender sender) { - List commands = new ArrayList<>(Arrays.asList("Join", "Help")); + final List commands = new ArrayList<>(Arrays.asList("Join", "Help")); if (sender.hasPermission("eventcore.admin")) { commands.addAll(Arrays.asList("End", "Start", "Block", "UnBlock", "Reload")); } @@ -291,16 +418,12 @@ private List getPlayerNameSuggestions() { } private BarColor getRandomBarColor() { - BarColor[] colors = BarColor.values(); - Random random = new Random(); - int index = random.nextInt(colors.length); - return colors[index]; + final BarColor[] colors = BarColor.values(); + return colors[new Random().nextInt(colors.length)]; } private BarStyle getRandomBarStyle() { BarStyle[] styles = BarStyle.values(); - Random random = new Random(); - int index = random.nextInt(styles.length); - return styles[index]; + return styles[new Random().nextInt(styles.length)]; } } diff --git a/src/main/java/ir/mehran1022/eventcore/Managers/InventoryManager.java b/src/main/java/ir/mehran1022/eventcore/Managers/InventoryManager.java index 3ad75d3..9b7459a 100644 --- a/src/main/java/ir/mehran1022/eventcore/Managers/InventoryManager.java +++ b/src/main/java/ir/mehran1022/eventcore/Managers/InventoryManager.java @@ -27,103 +27,170 @@ public enum Role { PLAYER } + /** + * Opens the inventory for the specified player based on their role. + * + * @param player the player to open the inventory for + * @param role the role of the player + */ public void openInventory(Player player, Role role) { - int size = 45; - String title = getInventoryTitle(role); - this.inventory = Bukkit.createInventory(this, size, title); + // Create the inventory with the appropriate title + this.inventory = Bukkit.createInventory(this, 45, getInventoryTitle(role)); + + // Fill the border of the inventory with black stained glass panes fillBorder(createItemStack(Material.BLACK_STAINED_GLASS_PANE, " ", "&8Don't mind me.")); - if (role.equals(Role.ADMIN)) { - setAdminItems(); - } else if (role.equals(Role.PLAYER)) { - setPlayerItems(); + // Set the items in the inventory based on the player's role + switch (role) { + case ADMIN: + setAdminItems(); + break; + case PLAYER: + setPlayerItems(); + break; } + // Open the inventory for the player player.openInventory(inventory); } @EventHandler - public void OnInventoryClick (InventoryClickEvent event) { - - Player player = (Player) event.getWhoClicked(); - ItemStack currentItem = event.getCurrentItem(); - - if (currentItem == null) { - return; - } - - String itemType = currentItem.getType().name(); - - event.setCancelled(true); - player.closeInventory(); - - switch (itemType) { - case "EMERALD": - if (ConfigManager.DEBUG) { - Common.log("[Debug] " + player.getName() + " clicked join button in the GUI"); - } - Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "join"), "/event join"); - break; - case "EMERALD_BLOCK": - case "REDSTONE_BLOCK": - case "GRINDSTONE": - if (!player.hasPermission("eventcore.admin")) { - Common.sendMessage(player, ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); - return; - } - switch (itemType) { - case "EMERALD_BLOCK": - Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "create an event"), "/event start"); - if (ConfigManager.DEBUG) { - Common.log("[Debug] " + player.getName() + " clicked create button in the GUI"); - } - break; - case "REDSTONE_BLOCK": - Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "close any open event"), "/event end"); - if (ConfigManager.DEBUG) { - Common.log("[Debug] " + player.getName() + " clicked close button in the GUI"); - } - break; - case "GRINDSTONE": - Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "reload the configurations"), "/event reload"); - if (ConfigManager.DEBUG) { - Common.log("[Debug] " + player.getName() + " clicked reload button in the GUI"); - } - break; - } - break; - } + public void OnInventoryClick(InventoryClickEvent event) { + // Get the player who clicked the inventory + final Player player = (Player) event.getWhoClicked(); + + // Get the clicked item + final ItemStack currentItem = event.getCurrentItem(); + + // If no item was clicked, return + if (currentItem == null) + return; + + // Cancel the event and close the inventory + event.setCancelled(true); + player.closeInventory(); + + // Handle different types of clicked items + switch (currentItem.getType().name()) { + case "EMERALD": + // If the clicked item is an emerald, show confirmation message and command for joining + if (ConfigManager.DEBUG) { + Common.log(String.format("[Debug] %s clicked join button in the GUI", player.getName())); + } + Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "join"), "/event join"); + break; + case "EMERALD_BLOCK": + case "REDSTONE_BLOCK": + case "GRINDSTONE": + // If the clicked item is an emerald block, redstone block, or grindstone, check for admin permission + if (!player.hasPermission("eventcore.admin")) { + // If player doesn't have admin permission, show no permission message and return + Common.sendMessage(player, ConfigManager.PREFIX + ConfigManager.NO_PERMISSION); + return; + } + + // Handle different types of admin actions + switch (currentItem.getType().name()) { + case "EMERALD_BLOCK": + // If the clicked item is an emerald block, show confirmation message and command for creating an event + Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "create an event"), "/event start"); + Common.logDebug(String.format("[Debug] %s clicked create button in the GUI", player.getName())); + break; + case "REDSTONE_BLOCK": + // If the clicked item is a redstone block, show confirmation message and command for closing an event + Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "close any open event"), "/event end"); + Common.logDebug(String.format("[Debug] %s clicked close button in the GUI", player.getName())); + break; + case "GRINDSTONE": + // If the clicked item is a grindstone, show confirmation message and command for reloading configurations + Common.confirmation(player, ConfigManager.PREFIX + ConfigManager.CONFIRMATION.replace("[Action]", "reload the configurations"), "/event reload"); + Common.logDebug("[Debug] " + player.getName() + " clicked reload button in the GUI"); + break; + } + break; + } } + /** + * Fills the border of the inventory with the specified border item. + * + * @param borderItem the item to fill the border with + */ private void fillBorder(ItemStack borderItem) { - int size = inventory.getSize(); + // Get the size of the inventory + final int size = inventory.getSize(); + + // Loop through each slot in the inventory for (int i = 0; i < size; i++) { + // Check if the slot is in the border if (i < 9 || i >= size - 9 || i % 9 == 0 || i % 9 == 8) { + // Set the border item in the slot inventory.setItem(i, borderItem); } } } + /** + * Creates an ItemStack with the given material, display name, and lore text. + * + * @param material the material of the ItemStack + * @param displayName the display name of the ItemStack + * @param loreText the lore text of the ItemStack + * @return the created ItemStack + */ private ItemStack createItemStack(Material material, String displayName, String loreText) { - ItemStack item = new ItemStack(material); - ItemMeta meta = item.getItemMeta(); - List lore = Collections.singletonList(Common.color(loreText)); + // Create a new ItemStack with the given material + final ItemStack item = new ItemStack(material); + + // Get the ItemMeta of the ItemStack + final ItemMeta meta = item.getItemMeta(); + + // Create a list with the lore text and set it as the lore of the ItemMeta + final List lore = Collections.singletonList(Common.color(loreText)); Objects.requireNonNull(meta).setLore(lore); + + // Set the display name of the ItemMeta meta.setDisplayName(Common.color(displayName)); + + // Set the modified ItemMeta back to the ItemStack item.setItemMeta(meta); + + // Return the created ItemStack return item; } + /** + * Generates the title for the inventory based on the specified role. + * + * @param role the role of the user + * @return the title for the inventory + */ private String getInventoryTitle(Role role) { return role.equals(Role.ADMIN) ? Common.color("Events - &lADMIN") : "Events"; } + /** + * Sets the admin items in the inventory. + */ private void setAdminItems() { + // Create and set the "Start" item inventory.setItem(20, createItemStack(Material.EMERALD_BLOCK, "&aStart", "&7Starts an event with the default description.")); + + // Create and set the "End" item inventory.setItem(24, createItemStack(Material.REDSTONE_BLOCK, "&cEnd", "&7Closes the active event.")); + + // Create and set the "Reload" item inventory.setItem(31, createItemStack(Material.GRINDSTONE, "&dReload", "&7Reloads the configuration files.")); } + /** + * Sets the player items. + *

+ * This function is responsible for setting the items for the player. + * It creates an item stack with the material EMERALD and sets it + * in the inventory slot 22. The item stack is created with the name + * "Join" in green color and the lore "Click to join" in gray color. + */ private void setPlayerItems() { inventory.setItem(22, createItemStack(Material.EMERALD, "&aJoin", "&7Click to join.")); }