@Override
public void onEnable() {
loadConfig();
initPlayerData();
loadPumpkinLocations();
loadPlayerData();
getServer().getPluginManager().registerEvents(this, this);
getCommand("givepumpkin").setExecutor(new GivePumpkinCommand(this));
}
private void loadConfig() {
File configFile = new File(getDataFolder(), "config.yml");
if (!configFile.exists()) {
saveDefaultConfig();
}
config = YamlConfiguration.loadConfiguration(configFile);
}
@Override
public void onDisable() {
for (Player player : getServer().getOnlinePlayers()) {
updatePlayerPlaytime(player);
}
savePumpkinLocations();
savePlayerData();
}
private void updatePlayerPlaytime(Player player) {
if (playerJoinTimes.containsKey(player.getName())) {
long joinedAt = playerJoinTimes.remove(player.getName());
long sessionPlaytime = System.currentTimeMillis() - joinedAt;
playerTotalPlaytime.put(player.getName(), playerTotalPlaytime.getOrDefault(player.getName(), 0L) + sessionPlaytime);
}
}
private void initPlayerData() {
dataFile = new File(getDataFolder(), "data.yml");
if (!dataFile.exists()) {
try {
dataFile.createNewFile(); // создадим пустой файл
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Не удалось создать data.yml", e);
}
}
dataConfig = YamlConfiguration.loadConfiguration(dataFile);
}
private void loadPlayerData() {
if (dataConfig.contains("players")) {
for (String playerName : dataConfig.getConfigurationSection("players").getKeys(false)) {
List<Integer> collected = dataConfig.getIntegerList("players." + playerName);
collectedPumpkins.put(playerName, new HashSet<>(collected));
}
}
if (dataConfig.contains("playtime")) {
for (String playerName : dataConfig.getConfigurationSection("playtime").getKeys(false)) {
playerTotalPlaytime.put(playerName, dataConfig.getLong("playtime." + playerName, 0L));
}
}
}
private void savePlayerData() {
collectedPumpkins.forEach((playerName, collected) ->
dataConfig.set("players." + playerName, new ArrayList<>(collected))
);
playerTotalPlaytime.forEach((playerName, playtime) ->
dataConfig.set("playtime." + playerName, playtime)
);
try {
dataConfig.save(dataFile);
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Не удалось сохранить данные игроков", e);
}
}
public ItemStack createPumpkinHead() {
ItemStack head = new ItemStack(Material.PLAYER_HEAD);
SkullMeta meta = (SkullMeta) head.getItemMeta();
applySkullTexture(meta);
meta.setDisplayName(colorize("&6Тыква"));
head.setItemMeta(meta);
return head;
}
private void applySkullTexture(SkullMeta meta) {
try {
GameProfile profile = new GameProfile(UUID.randomUUID(), "");
profile.getProperties().put("textures", new Property("textures", config.getString("halloween.pumpkinTexture")));
Field profileField = meta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(meta, profile);
} catch (NoSuchFieldException | IllegalAccessException e) {
getLogger().log(Level.SEVERE, "Ошибка при установке текстуры тыквы", e);
}
}
private void savePumpkinLocations() {
List<String> locations = new ArrayList<>();
pumpkinLocations.forEach((loc, index) ->
locations.add(String.format("%s,%f,%f,%f,%d",
loc.getWorld().getName(),
loc.getX(),
loc.getY(),
loc.getZ(),
index))
);
config.set("halloween.pumpkinsLocations", locations);
try {
config.save(new File(getDataFolder(), "config.yml"));
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Не удалось сохранить конфигурацию", e);
}
}
private void loadPumpkinLocations() {
for (String loc : config.getStringList("halloween.pumpkinsLocations")) {
String[] parts = loc.split(",");
Location location = new Location(Bukkit.getWorld(parts[0]), Double.parseDouble(parts[1]), Double.parseDouble(parts[2]), Double.parseDouble(parts[3]));
int index = Integer.parseInt(parts[4]);
pumpkinLocations.put(location, index);
}
}
private void setSkullTexture(Skull skull) {
try {
GameProfile profile = new GameProfile(UUID.randomUUID(), "");
profile.getProperties().put("textures", new Property("textures", config.getString("halloween.pumpkinTexture")));
Field profileField = skull.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(skull, profile);
} catch (NoSuchFieldException | IllegalAccessException e) {
getLogger().log(Level.SEVERE, "Ошибка при установке текстуры для блока тыквы", e);
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
playerJoinTimes.put(player.getName(), System.currentTimeMillis());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
updatePlayerPlaytime(event.getPlayer());
}
private boolean hasSufficientPlaytime(Player player) {
long requiredMinutes = config.getLong("halloween.requiredPlaytimeMinutes");
long totalPlaytime = playerTotalPlaytime.getOrDefault(player.getName(), 0L);
long currentSession = System.currentTimeMillis() - playerJoinTimes.getOrDefault(player.getName(), 0L);
long playedMinutes = (totalPlaytime + currentSession) / (1000 * 60);
return playedMinutes >= requiredMinutes;
}
private long getRemainingMinutes(Player player) {
long requiredMinutes = config.getLong("halloween.requiredPlaytimeMinutes");
long totalPlaytime = playerTotalPlaytime.getOrDefault(player.getName(), 0L);
long currentSession = System.currentTimeMillis() - playerJoinTimes.getOrDefault(player.getName(), 0L);
long playedMinutes = (totalPlaytime + currentSession) / (1000 * 60);
return Math.max(0, requiredMinutes - playedMinutes);
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
if (!isPumpkin(block)) return;
Location loc = block.getLocation();
if (!pumpkinLocations.containsKey(loc)) {
player.sendMessage(colorize("&cЭта локация не содержит тыквы."));
return;
}
event.setCancelled(true);
if (!hasSufficientPlaytime(player)) {
long remainingMinutes = getRemainingMinutes(player);
sendMessageList(player, "halloween.messages.needMorePlaytime", "%minutes%", remainingMinutes);
return;
}
String playerName = player.getName();
int pumpkinIndex = pumpkinLocations.get(loc);
Set<Integer> playerCollectedPumpkins = collectedPumpkins.computeIfAbsent(playerName, k -> new HashSet<>());
if (!playerCollectedPumpkins.contains(pumpkinIndex)) {
playerCollectedPumpkins.add(pumpkinIndex);
processPumpkinCollection(player, pumpkinIndex);
} else {
sendMessageList(player, "halloween.messages.alreadyCollected");
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
if (!event.getPlayer().hasPermission("dragonspresents.admin")) {
sendMessageList(event.getPlayer(), "halloween.messages.adminPermissionError");
return;
}
Block block = event.getBlock();
ItemStack item = event.getItemInHand();
Player player = event.getPlayer();
if (isPumpkinItem(item)) {
new BukkitRunnable() {
@Override
public void run() {
pumpkinLocations.putIfAbsent(block.getLocation(), pumpkinLocations.size());
if (block.getState() instanceof Skull skull) {
setSkullTexture(skull);
skull.update();
sendMessageList(player, "halloween.messages.pumpkinAdded");
}
savePumpkinLocations();
}
}.runTaskLater(this, 1L);
}
}
private boolean isPumpkin(Block block) {
Material type = block.getType();
return type == Material.PLAYER_HEAD || type == Material.PLAYER_WALL_HEAD;
}
private boolean isPumpkinItem(ItemStack item) {
return item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(colorize("&6Тыква"));
}
private void processPumpkinCollection(Player player, int pumpkinIndex) {
savePlayerData();
sendMessageList(player, "halloween.messages.foundPumpkin");
showTitle(player, collectedPumpkins.get(player.getName()).size());
dispatchRewardCommand(player, "halloween.rewardCommand");
if (collectedPumpkins.get(player.getName()).size() == config.getInt("halloween.totalPumpkins")) {
dispatchRewardCommand(player, "halloween.finalRewardCommand");
}
}
private void sendMessageList(Player player, String path) {
List<String> messageList = config.getStringList(path);
for (String message : messageList) {
player.sendMessage(colorize(message));
}
}
private void sendMessageList(Player player, String path, String placeholder, Object replacement) {
List<String> messageList = config.getStringList(path);
for (String message : messageList) {
message = message.replace(placeholder, replacement.toString());
player.sendMessage(colorize(message));
}
}
private void showTitle(Player player, int collected) {
String title = colorize(config.getStringList("halloween.messages.title").get(0));
String subtitle = colorize(
config.getStringList("halloween.messages.subtitle").get(0)
.replace("%collected%", String.valueOf(collected))
.replace("%total%", String.valueOf(config.getInt("halloween.totalPumpkins")))
);
player.sendTitle(title, subtitle, 10, 70, 20);
}
private void dispatchRewardCommand(Player player, String commandKey) {
String command = config.getString(commandKey).replace("{player}", player.getName());
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
}
String colorize(String message) {
return message.replace("&", "§");
}