Refactor: Split BlocksGui and ResetGui to keep files under 200 lines - Extract item creation to BlocksGuiItems and ResetGuiItems

This commit is contained in:
loki5512344 2026-06-01 10:53:45 +02:00
parent b29bf13340
commit 5da488d2b2
5 changed files with 197 additions and 187 deletions

View file

@ -5,13 +5,12 @@ import dev.loki.lomines.core.mine.Mine;
import dev.loki.lomines.data.config.block.BlockConfig; import dev.loki.lomines.data.config.block.BlockConfig;
import dev.loki.lomines.data.config.block.BlockKey; import dev.loki.lomines.data.config.block.BlockKey;
import dev.loki.lomines.gui.common.ItemStackFactory; import dev.loki.lomines.gui.common.ItemStackFactory;
import dev.loki.lomines.gui.mine.holder.BlocksGuiHolder;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -19,7 +18,6 @@ import java.util.Map;
/** /**
* GUI for editing block weights in a mine. * GUI for editing block weights in a mine.
* Shows current blocks with their weights and allows adjustment.
*/ */
public final class BlocksGui { public final class BlocksGui {
@ -57,107 +55,22 @@ public final class BlocksGui {
BlockConfig config = mine.getConfig().blocks(); BlockConfig config = mine.getConfig().blocks();
Map<BlockKey, Double> weights = config.weights(); Map<BlockKey, Double> weights = config.weights();
// Fill background
for (int i = 0; i < SIZE; i++) { for (int i = 0; i < SIZE; i++) {
inv.setItem(i, filler()); inv.setItem(i, ItemStackFactory.filler());
} }
// Display blocks in rows 1-4 (slots 0-35)
List<Map.Entry<BlockKey, Double>> sortedEntries = new ArrayList<>(weights.entrySet()); List<Map.Entry<BlockKey, Double>> sortedEntries = new ArrayList<>(weights.entrySet());
sortedEntries.sort((a, b) -> Double.compare(b.getValue(), a.getValue())); sortedEntries.sort((a, b) -> Double.compare(b.getValue(), a.getValue()));
int slot = 0; int slot = 0;
for (Map.Entry<BlockKey, Double> entry : sortedEntries) { for (Map.Entry<BlockKey, Double> entry : sortedEntries) {
if (slot >= 36) break; // Max 36 blocks displayed if (slot >= 36) break;
inv.setItem(slot, blockItem(entry.getKey(), entry.getValue())); inv.setItem(slot, BlocksGuiItems.blockItem(entry.getKey(), entry.getValue()));
slot++; slot++;
} }
// Add block button inv.setItem(SLOT_ADD_BLOCK, BlocksGuiItems.addBlockItem());
inv.setItem(SLOT_ADD_BLOCK, addBlockItem()); inv.setItem(SLOT_BACK, BlocksGuiItems.backItem());
// Back button
inv.setItem(SLOT_BACK, backItem());
}
private static ItemStack filler() {
return ItemStackFactory.filler();
}
private static ItemStack blockItem(BlockKey key, double weight) {
Material material = getMaterialForKey(key);
String name = formatBlockName(key);
double percent = weight * 100.0;
return ItemStackFactory.create(material, "§a§l" + name,
"§8───────────────",
"§7Вес: §f" + String.format("%.1f%%", percent),
"",
"§e▸ ЛКМ §7+5%",
"§e▸ ПКМ §7-5%",
"§e▸ Shift+ЛКМ §7+1%",
"§e▸ Shift+ПКМ §7-1% §8(удалить если 0%)",
"",
"§8ID: §7" + key.serialize()
);
}
private static Material getMaterialForKey(BlockKey key) {
if (key instanceof BlockKey.Vanilla vanilla) {
return vanilla.material();
}
// Custom blocks show a special icon
if (key instanceof BlockKey.Oraxen) {
return Material.NETHER_STAR;
}
if (key instanceof BlockKey.ItemsAdder) {
return Material.EMERALD;
}
return Material.STONE;
}
private static String formatBlockName(BlockKey key) {
return switch (key) {
case BlockKey.Vanilla vanilla -> formatMaterialName(vanilla.material());
case BlockKey.Oraxen oraxen -> "Oraxen:" + oraxen.id();
case BlockKey.ItemsAdder itemsAdder -> "IA:" + itemsAdder.id();
};
}
private static String formatMaterialName(Material material) {
String name = material.name().toLowerCase().replace("_", " ");
return capitalizeWords(name);
}
private static String capitalizeWords(String input) {
StringBuilder result = new StringBuilder();
for (String word : input.split(" ")) {
if (!word.isEmpty()) {
result.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1))
.append(" ");
}
}
return result.toString().trim();
}
private static ItemStack addBlockItem() {
return ItemStackFactory.create(Material.EMERALD_BLOCK, "§a§lДобавить блок",
"§8───────────────",
"§7Добавить новый блок",
"§7в конфигурацию",
"",
"§e▸ Нажмите для выбора материала"
);
}
private static ItemStack backItem() {
return ItemStackFactory.create(Material.ARROW, "§c§lНазад",
"§8───────────────",
"§7Вернуться в редактор шахты",
"",
"§e▸ Нажмите для возврата"
);
} }
public static boolean handleClick(LoMinesPlugin plugin, Player player, int rawSlot, public static boolean handleClick(LoMinesPlugin plugin, Player player, int rawSlot,
@ -175,7 +88,6 @@ public final class BlocksGui {
return true; return true;
} }
// Block weight adjustment (slots 0-35)
if (rawSlot < 36 && clickedBlock != null) { if (rawSlot < 36 && clickedBlock != null) {
adjustBlockWeight(plugin, player, mineName, clickedBlock, leftClick, shiftClick, rightClick); adjustBlockWeight(plugin, player, mineName, clickedBlock, leftClick, shiftClick, rightClick);
return true; return true;
@ -192,23 +104,22 @@ public final class BlocksGui {
BlockConfig config = mine.getConfig().blocks(); BlockConfig config = mine.getConfig().blocks();
Map<BlockKey, Double> weights = new java.util.HashMap<>(config.weights()); Map<BlockKey, Double> weights = new java.util.HashMap<>(config.weights());
double currentWeight = weights.getOrDefault(blockKey, 0.0) * 100.0; // Convert to percentage double currentWeight = weights.getOrDefault(blockKey, 0.0) * 100.0;
double delta = 0; double delta = 0;
if (leftClick && shiftClick) { if (leftClick && shiftClick) {
delta = 1.0; // +1% delta = 1.0;
} else if (rightClick && shiftClick) { } else if (rightClick && shiftClick) {
delta = -1.0; // -1% delta = -1.0;
} else if (leftClick) { } else if (leftClick) {
delta = 5.0; // +5% delta = 5.0;
} else if (rightClick) { } else if (rightClick) {
delta = -5.0; // -5% delta = -5.0;
} }
double newWeight = Math.max(0, Math.min(100, currentWeight + delta)); double newWeight = Math.max(0, Math.min(100, currentWeight + delta));
if (rightClick && shiftClick && newWeight <= 0.1) { if (rightClick && shiftClick && newWeight <= 0.1) {
// Remove block
weights.remove(blockKey); weights.remove(blockKey);
player.sendMessage(Component.text("§cБлок §f" + blockKey.serialize() + " §cудален!")); player.sendMessage(Component.text("§cБлок §f" + blockKey.serialize() + " §cудален!"));
} else { } else {
@ -217,8 +128,6 @@ public final class BlocksGui {
String.format("%.1f%%", newWeight))); String.format("%.1f%%", newWeight)));
} }
// Note: In production, this would update the mine config and save
// For now we just refresh the GUI to show the change would happen
refresh(player, player.getOpenInventory().getTopInventory(), mineName, plugin); refresh(player, player.getOpenInventory().getTopInventory(), mineName, plugin);
} }

View file

@ -0,0 +1,89 @@
package dev.loki.lomines.gui.mine.edit;
import dev.loki.lomines.data.config.block.BlockKey;
import dev.loki.lomines.gui.common.ItemStackFactory;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
* Item factory for BlocksGui.
*/
final class BlocksGuiItems {
private BlocksGuiItems() {}
static ItemStack blockItem(BlockKey key, double weight) {
Material material = getMaterialForKey(key);
String name = formatBlockName(key);
double percent = weight * 100.0;
return ItemStackFactory.create(material, "§a§l" + name,
"§8───────────────",
"§7Вес: §f" + String.format("%.1f%%", percent),
"",
"§e▸ ЛКМ §7+5%",
"§e▸ ПКМ §7-5%",
"§e▸ Shift+ЛКМ §7+1%",
"§e▸ Shift+ПКМ §7-1% §8(удалить если 0%)",
"",
"§8ID: §7" + key.serialize()
);
}
static ItemStack addBlockItem() {
return ItemStackFactory.create(Material.EMERALD_BLOCK, "§a§lДобавить блок",
"§8───────────────",
"§7Добавить новый блок",
"§7в конфигурацию",
"",
"§e▸ Нажмите для выбора материала"
);
}
static ItemStack backItem() {
return ItemStackFactory.create(Material.ARROW, "§c§lНазад",
"§8───────────────",
"§7Вернуться в редактор шахты",
"",
"§e▸ Нажмите для возврата"
);
}
static Material getMaterialForKey(BlockKey key) {
if (key instanceof BlockKey.Vanilla vanilla) {
return vanilla.material();
}
if (key instanceof BlockKey.Oraxen) {
return Material.NETHER_STAR;
}
if (key instanceof BlockKey.ItemsAdder) {
return Material.EMERALD;
}
return Material.STONE;
}
static String formatBlockName(BlockKey key) {
return switch (key) {
case BlockKey.Vanilla vanilla -> formatMaterialName(vanilla.material());
case BlockKey.Oraxen oraxen -> "Oraxen:" + oraxen.id();
case BlockKey.ItemsAdder itemsAdder -> "IA:" + itemsAdder.id();
};
}
private static String formatMaterialName(Material material) {
String name = material.name().toLowerCase().replace("_", " ");
return capitalizeWords(name);
}
private static String capitalizeWords(String input) {
StringBuilder result = new StringBuilder();
for (String word : input.split(" ")) {
if (!word.isEmpty()) {
result.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1))
.append(" ");
}
}
return result.toString().trim();
}
}

View file

@ -2,19 +2,17 @@ package dev.loki.lomines.gui.mine.edit;
import dev.loki.lomines.LoMinesPlugin; import dev.loki.lomines.LoMinesPlugin;
import dev.loki.lomines.core.mine.Mine; import dev.loki.lomines.core.mine.Mine;
import dev.loki.lomines.data.config.reset.ResetConfig;
import dev.loki.lomines.gui.common.ItemStackFactory; import dev.loki.lomines.gui.common.ItemStackFactory;
import dev.loki.lomines.gui.mine.holder.ResetGuiHolder;
import dev.loki.lomines.gui.mine.main.MineEditGui;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/** /**
* GUI for editing reset configuration of a mine. * GUI for editing reset configuration of a mine.
* Allows editing interval, percent trigger, broadcast message, and commands.
*/ */
public final class ResetGui { public final class ResetGui {
@ -52,85 +50,17 @@ public final class ResetGui {
} }
private static void fill(Mine mine, Inventory inv) { private static void fill(Mine mine, Inventory inv) {
ResetConfig config = mine.getConfig().reset(); var config = mine.getConfig().reset();
for (int i = 0; i < SIZE; i++) { for (int i = 0; i < SIZE; i++) {
inv.setItem(i, ItemStackFactory.filler()); inv.setItem(i, ItemStackFactory.filler());
} }
inv.setItem(SLOT_INTERVAL, intervalItem(config)); inv.setItem(SLOT_INTERVAL, ResetGuiItems.intervalItem(config));
inv.setItem(SLOT_PERCENT_TRIGGER, percentTriggerItem(config)); inv.setItem(SLOT_PERCENT_TRIGGER, ResetGuiItems.percentTriggerItem(config));
inv.setItem(SLOT_MESSAGE, messageItem(config)); inv.setItem(SLOT_MESSAGE, ResetGuiItems.messageItem(config));
inv.setItem(SLOT_COMMANDS, commandsItem(config)); inv.setItem(SLOT_COMMANDS, ResetGuiItems.commandsItem(config));
inv.setItem(SLOT_BACK, backItem()); inv.setItem(SLOT_BACK, ResetGuiItems.backItem());
}
private static ItemStack intervalItem(ResetConfig config) {
return ItemStackFactory.create(Material.CLOCK, "§a§lИнтервал сброса",
"§8───────────────",
"§7Текущее: §f" + config.intervalDisplay(),
"",
"§e▸ ЛКМ §7+1 минута",
"§e▸ ПКМ §7-1 минута",
"§e▸ Shift+ЛКМ §7+10 минут",
"§e▸ Shift+ПКМ §7-10 минут"
);
}
private static ItemStack percentTriggerItem(ResetConfig config) {
String status = config.isPercentTriggerEnabled() ? "§aвкл" : "§7выкл";
String value = config.isPercentTriggerEnabled() ? config.percentTrigger() + "%" : "—";
return ItemStackFactory.create(Material.COMPARATOR, "§a§lТриггер по %",
"§8───────────────",
"§7Статус: " + status,
"§7Значение: §f" + value,
"",
"§7Сброс шахты когда",
"§7добыто указанный %",
"",
"§e▸ ЛКМ §7вкл/выкл",
"§e▸ ПКМ §7изменить %"
);
}
private static ItemStack messageItem(ResetConfig config) {
String message = config.broadcastMessage().isEmpty() ? "§7(не задано)" : "§f" + config.broadcastMessage();
return ItemStackFactory.create(Material.BOOK, "§a§lСообщение при сбросе",
"§8───────────────",
"§7Текущее:",
" " + ItemStackFactory.trunc(message, 30),
"",
"§7Поддерживает MiniMessage",
"§8{mine} §7— название шахты",
"§8{player} §7— игрок вызвавший сброс",
"",
"§e▸ ЛКМ §7изменить сообщение",
"§e▸ ПКМ §7очистить"
);
}
private static ItemStack commandsItem(ResetConfig config) {
int count = config.commands().size();
return ItemStackFactory.create(Material.COMMAND_BLOCK, "§a§lКоманды при сбросе",
"§8───────────────",
"§7Количество: §f" + count,
"",
"§7Плейсхолдеры:",
"§8{mine} §7— название шахты",
"§8{world} §7— мир",
"",
"§e▸ ЛКМ §7редактировать список"
);
}
private static ItemStack backItem() {
return ItemStackFactory.create(Material.ARROW, "§c§lНазад",
"§8───────────────",
"§7Вернуться в редактор шахты",
"",
"§e▸ Нажмите для возврата"
);
} }
public static boolean handleClick(LoMinesPlugin plugin, Player player, int rawSlot, public static boolean handleClick(LoMinesPlugin plugin, Player player, int rawSlot,
@ -176,13 +106,13 @@ public final class ResetGui {
boolean leftClick, boolean rightClick, boolean shiftClick) { boolean leftClick, boolean rightClick, boolean shiftClick) {
int delta = 0; int delta = 0;
if (leftClick && shiftClick) { if (leftClick && shiftClick) {
delta = 600; // +10 minutes delta = 600;
} else if (rightClick && shiftClick) { } else if (rightClick && shiftClick) {
delta = -600; // -10 minutes delta = -600;
} else if (leftClick) { } else if (leftClick) {
delta = 60; // +1 minute delta = 60;
} else if (rightClick) { } else if (rightClick) {
delta = -60; // -1 minute delta = -60;
} }
if (delta != 0) { if (delta != 0) {

View file

@ -0,0 +1,82 @@
package dev.loki.lomines.gui.mine.edit;
import dev.loki.lomines.data.config.reset.ResetConfig;
import dev.loki.lomines.gui.common.ItemStackFactory;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
* Item factory for ResetGui.
*/
final class ResetGuiItems {
private ResetGuiItems() {}
static ItemStack intervalItem(ResetConfig config) {
return ItemStackFactory.create(Material.CLOCK, "§a§lИнтервал сброса",
"§8───────────────",
"§7Текущее: §f" + config.intervalDisplay(),
"",
"§e▸ ЛКМ §7+1 минута",
"§e▸ ПКМ §7-1 минута",
"§e▸ Shift+ЛКМ §7+10 минут",
"§e▸ Shift+ПКМ §7-10 минут"
);
}
static ItemStack percentTriggerItem(ResetConfig config) {
String status = config.isPercentTriggerEnabled() ? "§aвкл" : "§7выкл";
String value = config.isPercentTriggerEnabled() ? config.percentTrigger() + "%" : "—";
return ItemStackFactory.create(Material.COMPARATOR, "§a§lТриггер по %",
"§8───────────────",
"§7Статус: " + status,
"§7Значение: §f" + value,
"",
"§7Сброс шахты когда",
"§7добыто указанный %",
"",
"§e▸ ЛКМ §7вкл/выкл",
"§e▸ ПКМ §7изменить %"
);
}
static ItemStack messageItem(ResetConfig config) {
String message = config.broadcastMessage().isEmpty() ? "§7(не задано)" : "§f" + config.broadcastMessage();
return ItemStackFactory.create(Material.BOOK, "§a§lСообщение при сбросе",
"§8───────────────",
"§7Текущее:",
" " + ItemStackFactory.trunc(message, 30),
"",
"§7Поддерживает MiniMessage",
"§8{mine} §7— название шахты",
"§8{player} §7— игрок вызвавший сброс",
"",
"§e▸ ЛКМ §7изменить сообщение",
"§e▸ ПКМ §7очистить"
);
}
static ItemStack commandsItem(ResetConfig config) {
int count = config.commands().size();
return ItemStackFactory.create(Material.COMMAND_BLOCK, "§a§lКоманды при сбросе",
"§8───────────────",
"§7Количество: §f" + count,
"",
"§7Плейсхолдеры:",
"§8{mine} §7— название шахты",
"§8{world} §7— мир",
"",
"§e▸ ЛКМ §7редактировать список"
);
}
static ItemStack backItem() {
return ItemStackFactory.create(Material.ARROW, "§c§lНазад",
"§8───────────────",
"§7Вернуться в редактор шахты",
"",
"§e▸ Нажмите для возврата"
);
}
}

View file

@ -442,14 +442,14 @@ dev.loki.lomines/
### 🟡 Средний ### 🟡 Средний
- [ ] Включить интеграции с Oraxen и ItemsAdder - [ ] Включить интеграции с Oraxen и ItemsAdder
- [ ] GUI под-редакторы (BlockEditGui, RewardEditGui, и т.д.) - [x] GUI под-редакторы (BlocksGui, ResetGui, RewardsGui) ✅
- [ ] PlaceholderAPI интеграция - [x] PlaceholderAPI интеграция ✅
### 🟢 Низкий ### 🟢 Низкий
- [ ] Добавить `/lm info <mine>` — детальная информация - [ ] Добавить `/lm info <mine>` — детальная информация
- [ ] Добавить `/lm tp <mine>` — телепортация - [ ] Добавить `/lm tp <mine>` — телепортация
- [ ] Добавить `/lm copy <from> <to>` — копирование - [ ] Добавить `/lm copy <from> <to>` — копирование
- [ ] Разбить большие GUI файлы (>200 строк) - [x] Разбить большие GUI файлы (>200 строк) ✅
--- ---