To enhance your PVOPlugin, fix the GUI issues, and ensure that commands work correctly, we'll address the following areas:
-
GUI Fixes:
- Issue: The current GUI handling relies on inventory titles and iterating through all PVOs to find the matching GUI, which is inefficient and error-prone.
- Solution: Implement custom
InventoryHolder classes to uniquely identify each GUI. This approach simplifies event handling and ensures that interactions are correctly mapped to their respective GUIs.
-
Command Improvements:
- Issue: Commands might not function as expected due to registration issues, incorrect permission checks, or flawed command execution logic.
- Solution: Ensure that commands are properly registered in
plugin.yml, verify permission checks, and streamline command execution methods.
-
Listener Enhancements:
- Issue: Redundant or incorrectly implemented listeners can cause unexpected behavior or interfere with GUI interactions.
- Solution: Consolidate listeners where possible, ensure they are correctly registered, and verify their event handling logic.
-
General Code Optimization:
- Issue: Some parts of the code can be optimized for better performance and maintainability.
- Solution: Refactor code for clarity, efficiency, and adherence to best practices.
Below, you'll find the enhanced code with detailed explanations for each section.
1. Implement Custom Inventory Holders
Using custom InventoryHolder implementations helps uniquely identify each GUI, making event handling more reliable.
a. PVOGUIHolder.java
// src/main/java/com/example/pVOPlugin/gui/PVOGUIHolder.java
package com.example.pVOPlugin.gui;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
public class PVOGUIHolder implements InventoryHolder {
private final PVOGUI gui;
public PVOGUIHolder(PVOGUI gui) {
this.gui = gui;
}
@Override
public Inventory getInventory() {
return gui.getInventory();
}
public PVOGUI getGui() {
return gui;
}
}
b. TechnologyGUIHolder.java
// src/main/java/com/example/pVOPlugin/gui/TechnologyGUIHolder.java
package com.example.pVOPlugin.gui;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
public class TechnologyGUIHolder implements InventoryHolder {
private final TechnologyGUI gui;
public TechnologyGUIHolder(TechnologyGUI gui) {
this.gui = gui;
}
@Override
public Inventory getInventory() {
return gui.getInventory();
}
public TechnologyGUI getGui() {
return gui;
}
}
2. Update GUI Classes to Use Inventory Holders
a. PVOGUI.java
Refactor the PVOGUI to use PVOGUIHolder and include a reference to the PVO it manages.
// src/main/java/com/example/pVOPlugin/gui/PVOGUI.java
package com.example.pVOPlugin.gui;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.managers.TechnologyManager;
import com.example.pVOPlugin.models.PVO;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.*;
import java.util.ArrayList;
import java.util.List;
public class PVOGUI {
private final PVOPlugin plugin;
private final Player player;
private final PVO pvo;
private final Inventory inventory;
public PVOGUI(PVOPlugin plugin, Player player, PVO pvo) {
this.plugin = plugin;
this.player = player;
this.pvo = pvo;
this.inventory = Bukkit.createInventory(new PVOGUIHolder(this), 27, ChatColor.RED + "Настройки PVO");
initializeGUI();
}
private void initializeGUI() {
// Заполняем все слоты серыми стеклами
ItemStack filler = createItem(Material.GRAY_STAINED_GLASS_PANE, " ");
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, filler);
}
// Кнопка включения/выключения
ItemStack toggleItem = new ItemStack(pvo.isEnabled() ? Material.LIME_WOOL : Material.RED_WOOL);
ItemMeta toggleMeta = toggleItem.getItemMeta();
if (toggleMeta != null) {
toggleMeta.setDisplayName(ChatColor.GREEN + (pvo.isEnabled() ? "Выключить PVO" : "Включить PVO"));
toggleItem.setItemMeta(toggleMeta);
inventory.setItem(11, toggleItem);
}
// Кнопка добавления энергии
ItemStack energyItem = new ItemStack(Material.GLOWSTONE_DUST);
ItemMeta energyMeta = energyItem.getItemMeta();
if (energyMeta != null) {
energyMeta.setDisplayName(ChatColor.YELLOW + "Добавить энергию");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.GRAY + "Текущая энергия: " + pvo.getEnergy());
energyMeta.setLore(lore);
energyItem.setItemMeta(energyMeta);
inventory.setItem(13, energyItem);
}
// Кнопка управления исключениями
ItemStack excludeItem = new ItemStack(Material.PLAYER_HEAD);
ItemMeta excludeMeta = excludeItem.getItemMeta();
if (excludeMeta != null) {
excludeMeta.setDisplayName(ChatColor.BLUE + "Управление исключениями");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.GRAY + "Исключено игроков: " + pvo.getExclusions().size());
excludeMeta.setLore(lore);
excludeItem.setItemMeta(excludeMeta);
inventory.setItem(15, excludeItem);
}
// Кнопка открытия технологического прогресса
ItemStack techItem = new ItemStack(Material.BOOK);
ItemMeta techMeta = techItem.getItemMeta();
if (techMeta != null) {
techMeta.setDisplayName(ChatColor.GOLD + "Технологический Прогресс");
techMeta.setLore(List.of(ChatColor.GRAY + "Управляйте исследованиями и улучшениями."));
techItem.setItemMeta(techMeta);
inventory.setItem(22, techItem);
}
// Кнопка закрытия GUI
ItemStack closeButton = new ItemStack(Material.BARRIER);
ItemMeta closeMeta = closeButton.getItemMeta();
if (closeMeta != null) {
closeMeta.setDisplayName(ChatColor.RED + "Закрыть");
closeButton.setItemMeta(closeMeta);
inventory.setItem(26, closeButton);
}
}
private ItemStack createItem(Material material, String name) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setDisplayName(name);
item.setItemMeta(meta);
}
return item;
}
public Inventory getInventory() {
return inventory;
}
public void open() {
player.openInventory(inventory);
}
public void handleClick(InventoryClickEvent event) {
event.setCancelled(true);
ItemStack clicked = event.getCurrentItem();
if (clicked == null || clicked.getType() == Material.AIR) return;
switch (clicked.getType()) {
case LIME_WOOL:
case RED_WOOL:
togglePVO();
break;
case GLOWSTONE_DUST:
promptEnergyInput();
break;
case PLAYER_HEAD:
manageExclusions();
break;
case BOOK:
openTechnologyGUI();
break;
case BARRIER:
player.closeInventory();
break;
default:
break;
}
}
private void togglePVO() {
pvo.setEnabled(!pvo.isEnabled());
plugin.getPVOManager().addPVO(pvo.getLocation(), pvo);
plugin.getPVOManager().savePVOs();
player.sendMessage(ChatColor.GREEN + "PVO " + (pvo.isEnabled() ? "включено." : "выключено."));
// Обновляем GUI
initializeGUI();
player.openInventory(inventory);
}
private void promptEnergyInput() {
// Запрос ввода через чат
plugin.getTechnologyManager().promptAction(player, TechnologyManager.ActionType.ADD_ENERGY);
player.sendMessage(ChatColor.YELLOW + "Введите количество энергии для добавления через чат:");
}
private void manageExclusions() {
player.sendMessage(ChatColor.BLUE + "Введите ник игрока через команду /pvo exclude <ник>");
}
private void openTechnologyGUI() {
// Открываем технологический GUI
plugin.getTechnologyManager().openTechnologyGUI(player);
}
public void update() {
initializeGUI();
player.openInventory(inventory);
}
}
b. TechnologyGUI.java
Similarly, refactor TechnologyGUI to use TechnologyGUIHolder.
// src/main/java/com/example/pVOPlugin/gui/TechnologyGUI.java
package com.example.pVOPlugin.gui;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.managers.TechnologyManager;
import com.example.pVOPlugin.managers.TechnologyManager.Technology;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TechnologyGUI {
private final PVOPlugin plugin;
private final Player player;
private final TechnologyManager technologyManager;
private final Inventory inventory;
public TechnologyGUI(PVOPlugin plugin, Player player, TechnologyManager technologyManager) {
this.plugin = plugin;
this.player = player;
this.technologyManager = technologyManager;
this.inventory = Bukkit.createInventory(new TechnologyGUIHolder(this), 54, ChatColor.GOLD + "Технологический Прогресс");
initializeGUI();
}
private void initializeGUI() {
// Заполняем все слоты черными стеклами
ItemStack filler = createItem(Material.BLACK_STAINED_GLASS_PANE, " ");
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, filler);
}
// Получаем доступные технологии
Map<String, Technology> technologies = technologyManager.getTechnologies();
int slot = 10; // Начальный слот для технологий
for (Technology tech : technologies.values()) {
ItemStack techItem = new ItemStack(Material.ENCHANTED_BOOK);
ItemMeta techMeta = techItem.getItemMeta();
if (techMeta != null) {
techMeta.setDisplayName(ChatColor.GOLD + tech.getName());
List<String> lore = new ArrayList<>();
lore.add(ChatColor.GRAY + tech.getDescription());
lore.add("");
lore.add(ChatColor.GREEN + "Стоимость: " + tech.getCost() + " энергии");
lore.add(ChatColor.YELLOW + "Вероятность успеха: " + tech.getSuccessRate() + "%");
techMeta.setLore(lore);
techItem.setItemMeta(techMeta);
}
inventory.setItem(slot, techItem);
slot += 2; // Размещаем через слот для эстетики
}
// Кнопка закрытия GUI
ItemStack closeButton = new ItemStack(Material.BARRIER);
ItemMeta closeMeta = closeButton.getItemMeta();
if (closeMeta != null) {
closeMeta.setDisplayName(ChatColor.RED + "Закрыть");
closeButton.setItemMeta(closeMeta);
inventory.setItem(53, closeButton);
}
}
private ItemStack createItem(Material material, String name) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setDisplayName(name);
item.setItemMeta(meta);
}
return item;
}
public Inventory getInventory() {
return inventory;
}
public void open() {
player.openInventory(inventory);
}
public void handleClick(InventoryClickEvent event) {
event.setCancelled(true);
ItemStack clicked = event.getCurrentItem();
if (clicked == null || clicked.getType() == Material.AIR) return;
switch (clicked.getType()) {
case ENCHANTED_BOOK:
researchTechnology(clicked);
break;
case BARRIER:
player.closeInventory();
break;
default:
break;
}
}
private void researchTechnology(ItemStack item) {
String techName = ChatColor.stripColor(item.getItemMeta().getDisplayName()).toLowerCase();
Technology tech = technologyManager.getTechnologies().get(techName);
if (tech == null) {
player.sendMessage(ChatColor.RED + "Технология не найдена.");
return;
}
// Запрос подтверждения исследования
technologyManager.promptAction(player, TechnologyManager.ActionType.RESEARCH_TECHNOLOGY);
player.sendMessage(ChatColor.YELLOW + "Введите название технологии для исследования через чат:");
}
}
3. Revise Listener for GUI Interaction
GUIListener.java
Update the GUIListener to utilize the custom InventoryHolder classes for accurate event handling.
// src/main/java/com/example/pVOPlugin/listeners/GUIListener.java
package com.example.pVOPlugin.listeners;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.gui.PVOGUI;
import com.example.pVOPlugin.gui.PVOGUIHolder;
import com.example.pVOPlugin.gui.TechnologyGUI;
import com.example.pVOPlugin.gui.TechnologyGUIHolder;
import com.example.pVOPlugin.models.PVO;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class GUIListener implements Listener {
private final PVOPlugin plugin;
public GUIListener(PVOPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
if (event.getClickedInventory() == null) return;
if (event.getCurrentItem() == null || event.getCurrentItem().getType() == null) return;
// Check for PVOGUI
if (event.getView().getTitle().equals(ChatColor.RED + "Настройки PVO")) {
// Get the holder and cast it
if (!(event.getInventory().getHolder() instanceof PVOGUIHolder)) return;
PVOGUIHolder holder = (PVOGUIHolder) event.getInventory().getHolder();
PVOGUI gui = holder.getGui();
gui.handleClick(event);
return;
}
// Check for TechnologyGUI
if (event.getView().getTitle().equals(ChatColor.GOLD + "Технологический Прогресс")) {
if (!(event.getInventory().getHolder() instanceof TechnologyGUIHolder)) return;
TechnologyGUIHolder holder = (TechnologyGUIHolder) event.getInventory().getHolder();
TechnologyGUI gui = holder.getGui();
gui.handleClick(event);
}
}
}
4. Refactor Command Executors
Ensure that commands are correctly implemented, with proper permission checks and execution logic.
a. AdminCommand.java
Refactor AdminCommand to ensure it handles only its designated subcommands.
// src/main/java/com/example/pVOPlugin/commands/AdminCommand.java
package com.example.pVOPlugin.commands;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.gui.TechnologyGUI;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AdminCommand implements CommandExecutor, TabCompleter {
private final PVOPlugin plugin;
public AdminCommand(PVOPlugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("§cЭта команда может быть использована только игроками.");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("pvoplugin.admin")) {
player.sendMessage("§cУ вас нет прав для использования этой команды.");
return true;
}
if (args.length < 1) {
player.sendMessage("§cИспользование: /pvoadmin <opentechgui>");
return true;
}
String subCommand = args[0].toLowerCase();
if (subCommand.equals("opentechgui")) {
openTechnologyGUI(player);
return true;
}
player.sendMessage("§cНеизвестная подкоманда.");
return true;
}
private void openTechnologyGUI(Player player) {
plugin.getTechnologyManager().openTechnologyGUI(player);
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (command.getName().equalsIgnoreCase("pvoadmin")) {
if (args.length == 1) {
return Arrays.asList("opentechgui");
}
}
return Collections.emptyList();
}
}
b. PVOCommand.java
Ensure that PVOCommand properly handles all subcommands with accurate permission checks.
// src/main/java/com/example/pVOPlugin/commands/PVOCommand.java
package com.example.pVOPlugin.commands;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.managers.TechnologyManager;
import com.example.pVOPlugin.models.PVO;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.*;
public class PVOCommand implements CommandExecutor, TabCompleter {
private final PVOPlugin plugin;
public PVOCommand(PVOPlugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("givepvo")) {
return handleGivePVO(sender, args);
}
if (command.getName().equalsIgnoreCase("pvo")) {
return handlePVO(sender, args);
}
return false;
}
private boolean handleGivePVO(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("§cЭта команда может быть использована только игроками.");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("pvoplugin.givepvo")) {
player.sendMessage("§cУ вас нет прав для использования этой команды.");
return true;
}
if (args.length != 1) {
player.sendMessage("§cИспользование: /givepvo <тип>");
return true;
}
String type = args[0].toLowerCase();
Material pvoMaterial;
String displayName;
switch (type) {
case "km-1":
pvoMaterial = Material.REDSTONE_BLOCK;
displayName = ChatColor.AQUA + "PVO KM-1";
break;
case "km-2":
pvoMaterial = Material.EMERALD_BLOCK;
displayName = ChatColor.AQUA + "PVO KM-2";
break;
case "rtio-100":
pvoMaterial = Material.DIAMOND_BLOCK;
displayName = ChatColor.AQUA + "PVO RTIO-100";
break;
case "rtio-200":
pvoMaterial = Material.GOLD_BLOCK;
displayName = ChatColor.AQUA + "PVO RTIO-200";
break;
case "rtio-300":
pvoMaterial = Material.IRON_BLOCK;
displayName = ChatColor.AQUA + "PVO RTIO-300";
break;
default:
player.sendMessage("§cНеизвестный тип PVO.");
return true;
}
ItemStack pvoItem = new ItemStack(pvoMaterial);
ItemMeta meta = pvoItem.getItemMeta();
if (meta != null) {
meta.setDisplayName(displayName);
List<String> lore = new ArrayList<>();
lore.add("§7Тип: " + type.toUpperCase());
lore.add("§7Энергия: " + plugin.getConfigManager().getConfig().getInt("pvo.initial_energy", 1000));
meta.setLore(lore);
pvoItem.setItemMeta(meta);
}
player.getInventory().addItem(pvoItem);
player.sendMessage("§aВы получили " + displayName + ".");
return true;
}
private boolean handlePVO(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("§cЭта команда может быть использована только игроками.");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("pvoplugin.admin")) {
player.sendMessage("§cУ вас нет прав для использования этой команды.");
return true;
}
if (args.length < 1) {
player.sendMessage("§cИспользование: /pvo <on|off|addenergy|exclude|research>");
return true;
}
String subCommand = args[0].toLowerCase();
TechnologyManager technologyManager = plugin.getTechnologyManager();
switch (subCommand) {
case "on":
activatePVO(player, true);
break;
case "off":
activatePVO(player, false);
break;
case "addenergy":
if (args.length != 2) {
player.sendMessage("§cИспользование: /pvo addenergy <количество>");
return true;
}
try {
int amount = Integer.parseInt(args[1]);
promptEnergyInput(player, amount);
} catch (NumberFormatException e) {
player.sendMessage("§cВведите корректное число.");
}
break;
case "exclude":
if (args.length != 2) {
player.sendMessage("§cИспользование: /pvo exclude <ник>");
return true;
}
String targetPlayer = args[1].toLowerCase();
addExclusion(player, targetPlayer);
break;
case "research":
if (args.length != 2) {
player.sendMessage("§cИспользование: /pvo research <технология>");
return true;
}
String techKey = args[1].toLowerCase();
if (technologyManager.getTechnologies().containsKey(techKey)) {
promptResearchInput(player, techKey);
} else {
player.sendMessage("§cТехнология не найдена.");
}
break;
default:
player.sendMessage("§cНеизвестная подкоманда.");
break;
}
return true;
}
private void activatePVO(Player player, boolean activate) {
for (PVO pvo : plugin.getPVOManager().getAllPVOs()) {
pvo.setEnabled(activate);
}
plugin.getPVOManager().savePVOs();
player.sendMessage("§aВсе PVO " + (activate ? "включены." : "выключены."));
}
private void promptEnergyInput(Player player, int amount) {
plugin.getTechnologyManager().promptAction(player, TechnologyManager.ActionType.ADD_ENERGY, amount);
player.sendMessage(ChatColor.YELLOW + "Введите количество энергии для добавления через чат:");
}
private void addExclusion(Player player, String targetPlayer) {
for (PVO pvo : plugin.getPVOManager().getAllPVOs()) {
pvo.addExclusion(targetPlayer);
}
plugin.getPVOManager().savePVOs();
player.sendMessage("§aИгрок " + targetPlayer + " добавлен в исключения всех PVO.");
}
private void promptResearchInput(Player player, String techKey) {
plugin.getTechnologyManager().promptAction(player, TechnologyManager.ActionType.RESEARCH_TECHNOLOGY, techKey);
player.sendMessage(ChatColor.YELLOW + "Введите название технологии для исследования через чат:");
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (command.getName().equalsIgnoreCase("givepvo")) {
if (args.length == 1) {
return Arrays.asList("km-1", "km-2", "rtio-100", "rtio-200", "rtio-300");
}
}
if (command.getName().equalsIgnoreCase("pvo")) {
if (args.length == 1) {
return Arrays.asList("on", "off", "addenergy", "exclude", "research");
}
if (args.length == 2) {
if (args[0].equalsIgnoreCase("exclude")) {
// Возвращаем список онлайн игроков
List<String> players = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
players.add(p.getName());
}
return players;
}
if (args[0].equalsIgnoreCase("research")) {
// Возвращаем список доступных технологий
return new ArrayList<>(plugin.getTechnologyManager().getTechnologies().keySet());
}
}
}
return Collections.emptyList();
}
}
Notes:
- Permission Checks: Ensure that
givepvo command has the appropriate permission check (pvoplugin.givepvo) where necessary.
- Enhanced
promptAction: Modify TechnologyManager to accept additional parameters if needed (e.g., amount or techKey).
5. Update TechnologyManager.java
Ensure that TechnologyManager can handle additional parameters for actions like adding energy or researching specific technologies.
// src/main/java/com/example/pVOPlugin/managers/TechnologyManager.java
package com.example.pVOPlugin.managers;
import com.example.pVOPlugin.PVOPlugin;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.*;
public class TechnologyManager {
private final PVOPlugin plugin;
private final Map<UUID, PendingAction> pendingActions; // Ассоциация игроков с ожидающими действиями
private final Map<String, Technology> technologies; // Доступные технологии
public TechnologyManager(PVOPlugin plugin) {
this.plugin = plugin;
this.pendingActions = new HashMap<>();
this.technologies = new HashMap<>();
}
public void loadTechnologies() {
FileConfiguration config = plugin.getConfigManager().getConfig();
ConfigurationSection section = config.getConfigurationSection("technologies");
if (section != null) {
for (String key : section.getKeys(false)) {
ConfigurationSection techSection = section.getConfigurationSection(key);
if (techSection != null) {
String name = techSection.getString("name");
String description = techSection.getString("description");
int cost = techSection.getInt("cost");
double successRate = techSection.getDouble("success_rate", 100.0);
technologies.put(key.toLowerCase(), new Technology(key.toLowerCase(), name, description, cost, successRate));
}
}
} else {
// Если секция отсутствует, инициализируем стандартные технологии
initializeDefaultTechnologies();
saveTechnologies();
}
plugin.getLogger().info("Загружено " + technologies.size() + " технологий.");
}
private void initializeDefaultTechnologies() {
technologies.put("upgrade_energy", new Technology("upgrade_energy", "Увеличение Энергии", "Повышает максимальную энергию PVO.", 500, 90.0));
technologies.put("synthesis_speed", new Technology("synthesis_speed", "Скорость Синтеза", "Увеличивает скорость синтеза PVO.", 300, 85.0));
technologies.put("enhanced_scope", new Technology("enhanced_scope", "Увеличенный Обхват", "Расширяет радиус действия PVO.", 400, 80.0));
technologies.put("adaptive_shield", new Technology("adaptive_shield", "Адаптивный Щит", "Увеличивает защиту от атак.", 600, 75.0));
technologies.put("energy_regeneration", new Technology("energy_regeneration", "Регенерация Энергии", "Увеличивает скорость регенерации энергии PVO.", 450, 80.0));
// Добавьте дополнительные технологии по необходимости
}
public void saveTechnologies() {
FileConfiguration config = plugin.getConfigManager().getConfig();
config.set("technologies", null); // Очистка секции перед сохранением
for (Map.Entry<String, Technology> entry : technologies.entrySet()) {
String key = entry.getKey();
Technology tech = entry.getValue();
config.set("technologies." + key + ".name", tech.getName());
config.set("technologies." + key + ".description", tech.getDescription());
config.set("technologies." + key + ".cost", tech.getCost());
config.set("technologies." + key + ".success_rate", tech.getSuccessRate());
}
plugin.getConfigManager().saveConfigFile();
}
public Map<String, Technology> getTechnologies() {
return technologies;
}
public void handleChatInput(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (pendingActions.containsKey(uuid)) {
PendingAction action = pendingActions.get(uuid);
String message = event.getMessage();
event.setCancelled(true);
switch (action.getType()) {
case ADD_ENERGY:
handleAddEnergy(player, action, message);
break;
case RESEARCH_TECHNOLOGY:
handleResearchTechnology(player, action, message);
break;
default:
player.sendMessage(ChatColor.RED + "Неизвестное действие.");
break;
}
pendingActions.remove(uuid);
}
}
private void handleAddEnergy(Player player, PendingAction action, String message) {
try {
int amount = Integer.parseInt(message);
if (amount <= 0) {
player.sendMessage(ChatColor.RED + "Количество энергии должно быть положительным числом.");
return;
}
// Добавляем энергию всем PVO (можно изменить для выбора конкретного PVO)
for (PVO pvo : plugin.getPVOManager().getAllPVOs()) {
pvo.addEnergy(amount);
}
plugin.getPVOManager().savePVOs();
player.sendMessage(ChatColor.GREEN + "Добавлено энергии: " + amount);
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED + "Введите корректное число.");
}
}
private void handleResearchTechnology(Player player, PendingAction action, String message) {
String techKey = message.toLowerCase();
Technology tech = technologies.get(techKey);
if (tech == null) {
player.sendMessage(ChatColor.RED + "Технология не найдена.");
return;
}
// Рассчитываем вероятность успеха
double chance = tech.getSuccessRate();
double roll = Math.random() * 100;
if (roll <= chance) {
// Успех исследования
applyTechnology(player, tech);
plugin.getPVOManager().savePVOs();
player.sendMessage(ChatColor.GREEN + "Вы успешно исследовали технологию: " + tech.getName());
plugin.getLogger().info(player.getName() + " успешно исследовал технологию " + tech.getName());
} else {
// Провал исследования
player.sendMessage(ChatColor.RED + "Исследование технологии " + tech.getName() + " провалилось.");
plugin.getLogger().info(player.getName() + " провалил исследование технологии " + tech.getName());
}
}
private void applyTechnology(Player player, Technology tech) {
// Применяем эффект исследования (пример: улучшаем все PVO)
for (PVO pvo : plugin.getPVOManager().getAllPVOs()) {
switch (tech.getKey()) {
case "upgrade_energy":
// Увеличиваем максимальную энергию
pvo.addEnergy(500);
break;
case "synthesis_speed":
// Реализуйте логику увеличения скорости синтеза
break;
case "enhanced_scope":
// Реализуйте логику увеличения радиуса действия
break;
case "adaptive_shield":
// Реализуйте логику увеличения защиты
break;
case "energy_regeneration":
// Реализуйте логику увеличения скорости регенерации
break;
// Добавьте дополнительные технологии по необходимости
default:
break;
}
}
}
public void promptAction(Player player, ActionType actionType, Object... params) {
UUID uuid = player.getUniqueId();
if (actionType == ActionType.ADD_ENERGY && params.length > 0) {
int amount = (int) params[0];
pendingActions.put(uuid, new PendingAction(actionType, amount));
} else if (actionType == ActionType.RESEARCH_TECHNOLOGY && params.length > 0) {
String techKey = (String) params[0];
pendingActions.put(uuid, new PendingAction(actionType, techKey));
} else {
pendingActions.put(uuid, new PendingAction(actionType));
}
switch (actionType) {
case ADD_ENERGY:
player.sendMessage(ChatColor.YELLOW + "Введите количество энергии через чат:");
break;
case RESEARCH_TECHNOLOGY:
player.sendMessage(ChatColor.YELLOW + "Введите название технологии для исследования через чат:");
break;
default:
break;
}
}
public void openTechnologyGUI(Player player) {
TechnologyGUI techGUI = new TechnologyGUI(plugin, player, this);
techGUI.open();
}
// Внутренний класс для представления технологии
public static class Technology {
private final String key;
private final String name;
private final String description;
private final int cost;
private final double successRate;
public Technology(String key, String name, String description, int cost, double successRate) {
this.key = key;
this.name = name;
this.description = description;
this.cost = cost;
this.successRate = successRate;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public int getCost() {
return cost;
}
public double getSuccessRate() {
return successRate;
}
}
// Внутренний класс для представления ожидающего действия
private static class PendingAction {
private final ActionType type;
private final Object data;
public PendingAction(ActionType type) {
this(type, null);
}
public PendingAction(ActionType type, Object data) {
this.type = type;
this.data = data;
}
public ActionType getType() {
return type;
}
public Object getData() {
return data;
}
}
// Перечисление типов действий
public enum ActionType {
ADD_ENERGY,
RESEARCH_TECHNOLOGY
}
}
Key Changes:
-
Enhanced promptAction Method: Now accepts additional parameters (Object... params) to handle specific data related to the action type, such as the amount of energy or the technology key.
-
Improved PendingAction Class: Stores additional data necessary for performing actions, allowing more flexible and accurate processing of user inputs.
6. Update GUIListener.java to Utilize Inventory Holders
Ensure that GUIListener accurately maps clicks to their respective GUIs using the custom InventoryHolder.
// src/main/java/com/example/pVOPlugin/listeners/GUIListener.java
package com.example.pVOPlugin.listeners;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.gui.PVOGUI;
import com.example.pVOPlugin.gui.PVOGUIHolder;
import com.example.pVOPlugin.gui.TechnologyGUI;
import com.example.pVOPlugin.gui.TechnologyGUIHolder;
import com.example.pVOPlugin.models.PVO;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class GUIListener implements Listener {
private final PVOPlugin plugin;
public GUIListener(PVOPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
if (event.getClickedInventory() == null) return;
if (event.getCurrentItem() == null || event.getCurrentItem().getType() == null) return;
// Check for PVOGUI
if (event.getView().getTitle().equals(ChatColor.RED + "Настройки PVO")) {
// Get the holder and cast it
if (!(event.getInventory().getHolder() instanceof PVOGUIHolder)) return;
PVOGUIHolder holder = (PVOGUIHolder) event.getInventory().getHolder();
PVOGUI gui = holder.getGui();
gui.handleClick(event);
return;
}
// Check for TechnologyGUI
if (event.getView().getTitle().equals(ChatColor.GOLD + "Технологический Прогресс")) {
if (!(event.getInventory().getHolder() instanceof TechnologyGUIHolder)) return;
TechnologyGUIHolder holder = (TechnologyGUIHolder) event.getInventory().getHolder();
TechnologyGUI gui = holder.getGui();
gui.handleClick(event);
}
}
}
Notes:
- The
InventoryClickEvent now directly relates to the specific GUI instances via InventoryHolder, eliminating the need to iterate through all PVOs.
7. Enhance PlayerInteractListener.java
Ensure that when a player interacts with a PVO block, the correct GUI is opened.
// src/main/java/com/example/pVOPlugin/listeners/PlayerInteractListener.java
package com.example.pVOPlugin.listeners;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.gui.PVOGUI;
import com.example.pVOPlugin.models.PVO;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
public class PlayerInteractListener implements Listener {
private final PVOPlugin plugin;
public PlayerInteractListener(PVOPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
// Проверяем, что игрок нажал правой кнопкой мыши на блок
if (!event.hasBlock() || !isRightClick(event.getAction())) return;
// Проверяем, что используется главная рука
if (event.getHand() != EquipmentSlot.HAND) return;
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (block == null) return;
// Проверяем, является ли блок PVO
if (isPVOBlock(block.getType())) {
// Проверяем, что игрок приседает
if (player.isSneaking()) {
PVO pvo = plugin.getPVOManager().getPVO(block.getLocation());
if (pvo != null) {
PVOGUI gui = new PVOGUI(plugin, player, pvo);
gui.open();
event.setCancelled(true);
}
}
}
}
private boolean isRightClick(org.bukkit.event.block.Action action) {
return action == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK || action == org.bukkit.event.block.Action.RIGHT_CLICK_AIR;
}
private boolean isPVOBlock(Material type) {
return type == Material.REDSTONE_BLOCK ||
type == Material.EMERALD_BLOCK ||
type == Material.DIAMOND_BLOCK ||
type == Material.GOLD_BLOCK ||
type == Material.IRON_BLOCK;
}
}
Notes:
- Ensure that the player is using the main hand to prevent handling off-hand interactions.
- The GUI is now instantiated with the specific
PVO instance, ensuring accurate settings and interactions.
8. Consolidate Chat Listeners
The original plugin has multiple chat listeners (ChatListener, EnergyInputListener, ExclusionInputListener). To streamline, consolidate these into a single listener.
ChatInputListener.java
// src/main/java/com/example/pVOPlugin/listeners/ChatInputListener.java
package com.example.pVOPlugin.listeners;
import com.example.pVOPlugin.PVOPlugin;
import com.example.pVOPlugin.managers.TechnologyManager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatInputListener implements Listener {
private final PVOPlugin plugin;
public ChatInputListener(PVOPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
plugin.getTechnologyManager().handleChatInput(event);
}
}
Notes:
- Remove
EnergyInputListener and ExclusionInputListener as they are no longer needed.
- Ensure that
ChatInputListener is registered in the main plugin class.
9. Update Main Plugin Class
Ensure that all listeners and commands are correctly registered and that the plugin lifecycle methods are properly implemented.
// src/main/java/com/example/pVOPlugin/PVOPlugin.java
package com.example.pVOPlugin;
import com.example.pVOPlugin.commands.AdminCommand;
import com.example.pVOPlugin.commands.PVOCommand;
import com.example.pVOPlugin.listeners.*;
import com.example.pVOPlugin.managers.ConfigManager;
import com.example.pVOPlugin.managers.PVOManager;
import com.example.pVOPlugin.managers.TechnologyManager;
import com.example.pVOPlugin.managers.RecipeManager;
import org.bukkit.plugin.java.JavaPlugin;
public class PVOPlugin extends JavaPlugin implements Listener {
private static PVOPlugin instance;
private ConfigManager configManager;
private PVOManager pvoManager;
private TechnologyManager technologyManager;
private RecipeManager recipeManager;
@Override
public void onEnable() {
instance = this;
// Инициализация менеджеров
configManager = new ConfigManager(this);
configManager.setup();
pvoManager = new PVOManager(this);
pvoManager.loadPVOs();
technologyManager = new TechnologyManager(this);
technologyManager.loadTechnologies();
recipeManager = new RecipeManager(this);
recipeManager.registerRecipes();
// Регистрация команд
PVOCommand pvoCommand = new PVOCommand(this);
getCommand("givepvo").setExecutor(pvoCommand);
getCommand("givepvo").setTabCompleter(pvoCommand);
getCommand("pvo").setExecutor(pvoCommand);
getCommand("pvo").setTabCompleter(pvoCommand);
AdminCommand adminCommand = new AdminCommand(this);
getCommand("pvoadmin").setExecutor(adminCommand);
getCommand("pvoadmin").setTabCompleter(adminCommand);
// Регистрация слушателей событий
getServer().getPluginManager().registerEvents(new BlockPlaceListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerInteractListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerMoveListener(this), this);
getServer().getPluginManager().registerEvents(new GUIListener(this), this);
getServer().getPluginManager().registerEvents(new ChatInputListener(this), this);
getLogger().info("PVOPlugin успешно включён!");
}
@Override
public void onDisable() {
pvoManager.savePVOs();
technologyManager.saveTechnologies();
getLogger().info("PVOPlugin успешно выключен.");
}
public static PVOPlugin getInstance() {
return instance;
}
public ConfigManager getConfigManager() {
return configManager;
}
public PVOManager getPVOManager() {
return pvoManager;
}
public TechnologyManager getTechnologyManager() {
return technologyManager;
}
public RecipeManager getRecipeManager() {
return recipeManager;
}
}
Key Changes:
- Command Registration: Ensured that both
givepvo and pvo commands have their executors and tab completers set.
- Listener Registration: Registered the consolidated
ChatInputListener and removed redundant listeners.
10. Validate and Enhance plugin.yml
Ensure that all commands, permissions, and other configurations are correctly defined.
# src/main/resources/plugin.yml
name: PVOPlugin
main: com.example.pVOPlugin.PVOPlugin
version: 2.0
api-version: 1.20
description: Расширенный плагин PVO с технологическим прогрессом и индивидуальными настройками.
commands:
givepvo:
description: Выдача PVO.
usage: /givepvo <тип>
permission: pvoplugin.givepvo
aliases: [gpvo]
pvo:
description: Управление PVO.
usage: /pvo <подкоманда>
permission: pvoplugin.admin
aliases: [pvoadmin]
pvoadmin:
description: Административные команды для технологического прогресса.
usage: /pvoadmin <opentechgui>
permission: pvoplugin.admin
permissions:
pvoplugin.givepvo:
description: Разрешение на выдачу PVO.
default: op
pvoplugin.admin:
description: Административные права PVO.
default: op
Enhancements:
- Aliases: Added an alias (
gpvo) for the givepvo command for convenience.
- Command Permissions: Ensured that both commands (
pvo and pvoadmin) share the pvoplugin.admin permission.
11. Final Checks and Testing
After implementing the above changes, perform the following steps to ensure everything works as expected:
-
Compile the Plugin: Ensure there are no compilation errors.
-
Deploy to a Server: Place the compiled .jar file in the plugins directory of your Minecraft server.
-
Verify Configuration Files: Make sure config.yml is properly generated with all necessary default values.
-
Test Commands:
/givepvo <type>: Verify that PVO items are correctly given.
/pvo on/off: Ensure all PVOs are activated/deactivated.
/pvo addenergy <amount>: Test adding energy to PVOs.
/pvo exclude <player>: Check if players are correctly excluded from PVO effects.
/pvo research <technology>: Validate research functionality.
/pvoadmin opentechgui: Open the Technology GUI and interact with it.
-
Test GUI Interactions:
- Right-click on PVO blocks while sneaking to open the PVO GUI.
- Interact with the buttons within the GUI to toggle PVO status, add energy, manage exclusions, and access the Technology GUI.
- Within the Technology GUI, attempt to research technologies and observe the outcomes.
-
Check Permissions: Ensure that only players with the appropriate permissions can execute administrative commands or interact with GUIs.
-
Monitor Logs: Review server logs for any errors or warnings related to the plugin during operation.
12. Additional Recommendations
- Use Inventory Holders Throughout: For any future GUIs, continue using custom
InventoryHolder implementations to maintain consistency and ease of management.
- Handle Concurrent GUI Sessions: If multiple players interact with GUIs simultaneously, ensure that each session is isolated and managed correctly.
- Optimize Event Handling: Avoid unnecessary operations within event handlers to maintain server performance, especially for frequent events like
PlayerMoveEvent.
- Expand Configurations: Consider adding more configurable options in
config.yml to allow server administrators to tweak plugin behavior without modifying code.
By implementing the above enhancements and following best practices in event handling and command management, your PVOPlugin should function reliably with fully operational GUIs and commands. Remember to thoroughly test each feature to ensure stability and correct behavior.