Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
22 kB
1
Indexable
Never
package org.lifestealsmp.lifestealcore;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;

import github.scarsz.discordsrv.DiscordSRV;
import github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;
import github.scarsz.discordsrv.dependencies.jda.api.JDA;
import github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed;
import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel;

public class main extends JavaPlugin implements Listener {

	private FileConfiguration data;
	private File dfile;

	ArrayList<String> deathReason = new ArrayList<String>();

	public void onEnable() {
		Bukkit.getServer().getPluginManager().registerEvents(this, (Plugin) this);
		saveDefaultConfig();
		setupFiles();
	}

	public void setupFile(File file) {
		if (!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e) {
				Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create " + file.getName() + "!");
			}
	}

	public void saveFile(FileConfiguration config, File file) {
		try {
			config.save(file);
		} catch (IOException e) {
			Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save " + file.getName() + "!");
		}
	}

	public void setupFiles() {
		this.dfile = new File(getDataFolder(), "data.yml");
		setupFile(this.dfile);
		this.data = (FileConfiguration) YamlConfiguration.loadConfiguration(this.dfile);
	}

	public FileConfiguration getData() {
		return this.data;
	}

	public void saveData() {
		saveFile(this.data, this.dfile);
	}

	public void reloadData() {
		this.data = (FileConfiguration) YamlConfiguration.loadConfiguration(this.dfile);
	}

	@EventHandler
	public void onPlayerDeath(PlayerDeathEvent event) {
		Player player = event.getEntity();
		deathReason.clear();
		deathReason.add(event.getDeathMessage());
		removeHeart(player);
		if (event.getEntity().getKiller() instanceof Player) {
			Player killer = event.getEntity().getKiller();
			double currentHealth = killer.getMaxHealth();
			if (currentHealth == 40.0D) {
				ItemStack item = new ItemStack(Material.PAPER);
				ItemMeta meta = item.getItemMeta();
				meta.setDisplayName("§4Claimable Heart");
				meta.setCustomModelData(10012);
				item.setItemMeta(meta);

				Location location = player.getLocation();
				World world = player.getWorld();
				world.dropItemNaturally(location, item);
			} else {
				killer.setMaxHealth(currentHealth + 2.0D);
			}
		}
	}

	public void addHeart(Player player) {
		double currentHealth = player.getMaxHealth();
		if (currentHealth == 40.0D) {
			int num = getData().getInt(player.getUniqueId() + ".Hearts-Deposited");
			getData().set(player.getUniqueId() + ".Hearts-Deposited", Integer.valueOf(num + 1));
			saveData();
		} else {
			player.setMaxHealth(currentHealth + 2.0D);
		}
	}

	public void removeHeart(Player player) {
		double currentHealth = player.getMaxHealth();
		if (currentHealth <= 2.0D) {
			deathBan(player);
		} else {
			player.setMaxHealth(currentHealth - 2.0D);
		}
	}

	public void deathBan(Player player) {
		getData().set(player.getUniqueId() + ".Death-Reason", deathReason);
		getData().set(player.getUniqueId() + ".Death-Banned", Boolean.valueOf(true));
		// Format the current date and set Time-Banned
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String currentDate = dateFormat.format(new Date());
		getData().set(player.getUniqueId() + ".Time-Banned", currentDate);

		saveData();
		String kickMessage = "You have been death banned!";
		player.kickPlayer(kickMessage);
		String playerName = player.getName();
		try {
			String imageUrl = "https://mc-heads.net/player/" + playerName;
			EmbedBuilder embedBuilder = new EmbedBuilder();
			embedBuilder.setTitle(String.valueOf(playerName) + " has been death banned!!");
			embedBuilder.setImage(imageUrl);
			embedBuilder.setColor(Color.RED);
			MessageEmbed embed = embedBuilder.build();
			JDA jda = DiscordSRV.getPlugin().getJda();
			TextChannel channel = jda.getTextChannelById("1119383259328040980");
			if (channel != null) {
				channel.sendMessageEmbeds(embed, new MessageEmbed[0]).queue(
						success -> System.out.println("Embed sent successfully!"), error -> error.printStackTrace());
			} else {
				System.out.println("Channel not found!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@EventHandler
	public void PlayerLoginEvent(PlayerLoginEvent event) {
		Player player = event.getPlayer();
		boolean deathBanned = getData().getBoolean(player.getUniqueId() + ".Death-Banned");
		if (deathBanned) {
			String kickMessage = "You have been death banned!";
			event.disallow(PlayerLoginEvent.Result.KICK_OTHER, kickMessage);
		}
	}

	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (command.getName().equalsIgnoreCase("LifeStealCore")) {
			if (!sender.hasPermission("LifeStealCore.Admin"))
				return true;
			if (args.length == 3 && args[0].equalsIgnoreCase("give")) {
				int amount;
				try {
					amount = Integer.parseInt(args[2]);
				} catch (NumberFormatException e) {
					sender.sendMessage("Invalid amount!");
					return true;
				}
				if (args[1].equalsIgnoreCase("all")) {
					for (Player player : Bukkit.getOnlinePlayers())
						adjustPlayerHealth(player, amount);
				} else {
					Player target = Bukkit.getPlayerExact(args[1]);
					if (target != null) {
						adjustPlayerHealth(target, amount);
					} else {
						sender.sendMessage("Player not found!");
					}
				}
				return true;
			}
		}
		if (command.getName().equalsIgnoreCase("ReviveStation") && sender instanceof Player) {
			Player player = (Player) sender;
			ReviveStationInventory(player);
		}
		return false;
	}

	private void adjustPlayerHealth(Player player, int amount) {
		double currentMaxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue();
		double potentialNewMaxHealth = currentMaxHealth + (amount * 2);
		if (potentialNewMaxHealth <= 40.0D) {
			player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(potentialNewMaxHealth);
		} else {
			player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(40.0D);
			double excessHearts = (potentialNewMaxHealth - 40.0D) / 2.0D;
			double num = 0.0D;
			if (getData().contains(player.getUniqueId() + ".Hearts-Deposited"))
				num = getData().getDouble(player.getUniqueId() + ".Hearts-Deposited");
			getData().set(player.getUniqueId() + ".Hearts-Deposited", Double.valueOf(num + excessHearts));
			saveData();
		}
	}

	public void ReviveStationInventory(Player player) {
		Inventory inv = Bukkit.createInventory(null, 27, "Revive Station");
		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName("§r");
		blankMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
		blank.setItemMeta(blankMeta);
		for (int i = 0; i < inv.getSize(); i++) {
			if (inv.getItem(i) == null)
				inv.setItem(i, blank);
		}
		ItemStack deathbans = new ItemStack(Material.PAPER);
		ItemMeta deathbansMeta = deathbans.getItemMeta();
		deathbansMeta.setDisplayName("Death Bans");
		deathbansMeta.setCustomModelData(Integer.valueOf(10013));
		deathbansMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		deathbans.setItemMeta(deathbansMeta);

		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName("Hearts Deposited");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		int hearts = getData().getInt(player.getUniqueId() + ".Hearts-Deposited");
		if (hearts == 0) {
			heartCount.setAmount(1);
		} else {
			heartCount.setAmount(getData().getInt(player.getUniqueId() + ".Hearts-Deposited"));
		}
		heartCount.setItemMeta(heartCountMeta);

		ItemStack withdrawHearts = new ItemStack(Material.PAPER);
		ItemMeta withdrawHeartsMeta = withdrawHearts.getItemMeta();
		withdrawHeartsMeta.setDisplayName("Withdraw Hearts");
		withdrawHeartsMeta.setCustomModelData(Integer.valueOf(10014));
		withdrawHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		withdrawHearts.setItemMeta(withdrawHeartsMeta);

		ItemStack depositHearts = new ItemStack(Material.PAPER);
		ItemMeta depositHeartsMeta = depositHearts.getItemMeta();
		depositHeartsMeta.setDisplayName("Deposit Hearts");
		depositHeartsMeta.setCustomModelData(Integer.valueOf(10015));
		depositHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		depositHearts.setItemMeta(depositHeartsMeta);

		inv.setItem(10, deathbans);
		inv.setItem(12, heartCount);
		inv.setItem(14, withdrawHearts);
		inv.setItem(16, depositHearts);
		player.openInventory(inv);
	}

	public void openDeathBansInventory(Player player, int page) {
		FileConfiguration data = getData();
		List<UUID> bannedPlayers = new ArrayList<>();

		for (String key : data.getKeys(false)) {
			if (data.getBoolean(key + ".Death-Banned")) {
				try {
					UUID uuid = UUID.fromString(key);
					bannedPlayers.add(uuid);
				} catch (IllegalArgumentException e) {
					// Handle invalid UUIDs
				}
			}
		}

		Inventory inv = Bukkit.createInventory(null, 27, "Death Bans Page " + page);

		// Filling inventory with placeholder items
		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName("§r");
		blankMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
		blank.setItemMeta(blankMeta);

		for (int i = 0; i < inv.getSize(); i++) {
			inv.setItem(i, blank);
		}

		// Calculate indices for pagination
		int startIndex = (page - 1) * 21;
		int endIndex = Math.min(startIndex + 21, bannedPlayers.size());

		// Set player heads in the inventory
		for (int i = startIndex; i < endIndex; i++) {
			UUID playerUUID = bannedPlayers.get(i);
			ItemStack head = new ItemStack(Material.PLAYER_HEAD, 1);
			SkullMeta headMeta = (SkullMeta) head.getItemMeta();

			String playerName = Bukkit.getOfflinePlayer(playerUUID).getName();
			if (playerName != null) {
				headMeta.setDisplayName("§a" + playerName); // You can change the color code as needed
			}

			// Set the owning player to display the correct head
			headMeta.setOwningPlayer(Bukkit.getOfflinePlayer(playerUUID));

			// Fetch the Time-Banned info
			String timeBanned = data.getString(playerUUID + ".Time-Banned");
			String banReason = data.getString(playerUUID + ".Death-Reason");
			if (timeBanned != null) {
				// Create lore and add it to the headMeta
				List<String> lore = new ArrayList<>();
				lore.add("§7Time Banned: §c" + timeBanned);
				lore.add("§7Ban Reason: §c" + banReason);
				lore.add("");
				lore.add("§aClick to open revive menu!");
				headMeta.setLore(lore);
			}

			// Apply the modified meta to the head
			head.setItemMeta(headMeta);

			// Place the head in the inventory
			inv.setItem((i - startIndex), head);
		}

		// Adding previous and next page buttons
		if (page > 1) {
			ItemStack prevPage = new ItemStack(Material.ARROW);
			ItemMeta prevPageMeta = prevPage.getItemMeta();
			prevPageMeta.setDisplayName("§cPrevious Page");
			prevPage.setItemMeta(prevPageMeta);
			inv.setItem(25, prevPage); // Bottom left slot for 'previous' button
		}

		if (endIndex < bannedPlayers.size()) {
			ItemStack nextPage = new ItemStack(Material.ARROW);
			ItemMeta nextPageMeta = nextPage.getItemMeta();
			nextPageMeta.setDisplayName("§aNext Page");
			nextPage.setItemMeta(nextPageMeta);
			inv.setItem(26, nextPage); // Bottom right slot for 'next' button
		}

		player.openInventory(inv);
	}

	@EventHandler
	public void onInventoryClickTwo(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().startsWith("Death Bans")) {

			event.setCancelled(true);

			ItemStack clickedItem = event.getCurrentItem();
			if (clickedItem == null || clickedItem.getType() == Material.AIR)
				return;

			if (clickedItem.getType() == Material.PLAYER_HEAD) {
				// Extract the player's name from the skull
				SkullMeta skullMeta = (SkullMeta) clickedItem.getItemMeta();
				if (skullMeta.hasOwner()) {
					String skullOwnerName = skullMeta.getOwningPlayer().getName();
					// Open a new inventory with the title "Name's Revive"
					openReviveInventory(player, skullOwnerName);
					return;
				}
			}

			// Existing pagination code
			String title = event.getView().getTitle();
			int currentPage = Integer.parseInt(title.split(" ")[3]);

			if (clickedItem.getType() == Material.ARROW) {
				if (clickedItem.getItemMeta().getDisplayName().contains("Previous Page")) {
					openDeathBansInventory(player, currentPage - 1);
				} else if (clickedItem.getItemMeta().getDisplayName().contains("Next Page")) {
					openDeathBansInventory(player, currentPage + 1);
				}
			}
		}
	}

	private HashMap<Player, Integer> playerScores = new HashMap<>();

	// Example method to add or update a player's score
	public void setPlayerScore(Player player, int score) {
		playerScores.put(player, score);
	}

	// Example method to get a player's score
	public Integer getPlayerScore(Player player) {
		if(playerScores.containsKey(player)) {
			return playerScores.get(player);
		} else {
			return 0;
		}
	}

	public void openReviveInventory(Player player, String playerName) {
		int totalHearts = getData().getInt(player.getUniqueId() + ".Hearts-Deposited") + countCustomPaperItems(player);
		int count = getPlayerScore(player);
		Inventory inv = Bukkit.createInventory(null, 27, "[" + playerName + "] Your Hearts: " + totalHearts);

		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName("§r");
		blankMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
		blank.setItemMeta(blankMeta);
		for (int i = 0; i < inv.getSize(); i++) {
			if (inv.getItem(i) == null)
				inv.setItem(i, blank);
		}

		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName("Use " + getPlayerScore(player) + " heart(s) to revive this player!");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		if (count == 0) {
			ItemStack zeroHearts = new ItemStack(Material.BEDROCK);
			ItemMeta zeroHeartsMeta = heartCount.getItemMeta();
			zeroHeartsMeta.setDisplayName("Add Hearts!");
			zeroHearts.setItemMeta(zeroHeartsMeta);
			inv.setItem(13, zeroHearts);
		} else {
			heartCount.setAmount(count);
			heartCount.setItemMeta(heartCountMeta);
			inv.setItem(13, heartCount);
		}

		ItemStack withdrawHearts = new ItemStack(Material.PAPER);
		ItemMeta withdrawHeartsMeta = withdrawHearts.getItemMeta();
		withdrawHeartsMeta.setDisplayName("Remove heart from revive");
		withdrawHeartsMeta.setCustomModelData(Integer.valueOf(10014));
		withdrawHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		withdrawHearts.setItemMeta(withdrawHeartsMeta);

		ItemStack depositHearts = new ItemStack(Material.PAPER);
		ItemMeta depositHeartsMeta = depositHearts.getItemMeta();
		depositHeartsMeta.setDisplayName("Add heart to revive");
		depositHeartsMeta.setCustomModelData(Integer.valueOf(10015));
		depositHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		depositHearts.setItemMeta(depositHeartsMeta);

		inv.setItem(21, withdrawHearts);
		inv.setItem(23, depositHearts);
		player.openInventory(inv);
	}

	@EventHandler
	public void onInventoryClickThree(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().contains("Your Hearts:")) {
			event.setCancelled(true);

			if (event.getSlot() == 21) {
				int num = getPlayerScore(player);
				if(num != 0) {
					setPlayerScore(player, num - 1);
				} else {
					return;
				}
			}

			if (event.getSlot() == 23) {
				int totalHearts = getData().getInt(player.getUniqueId() + ".Hearts-Deposited") + countCustomPaperItems(player);
				int num = getPlayerScore(player);
				if(num < totalHearts && num < 20) {
					setPlayerScore(player, num + 1);
				}
			}
			Inventory inv = player.getOpenInventory().getTopInventory();
		    updateInventoryItems(inv, player);
		    player.updateInventory();
		}
	}
	
	public void updateInventoryItems(Inventory inv, Player player) {
		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName("Use " + getPlayerScore(player) + " heart(s) to revive this player!");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		if (getPlayerScore(player) == 0) {
			ItemStack zeroHearts = new ItemStack(Material.BEDROCK);
			ItemMeta zeroHeartsMeta = heartCount.getItemMeta();
			zeroHeartsMeta.setDisplayName("Add Hearts!");
			zeroHearts.setItemMeta(zeroHeartsMeta);
			inv.setItem(13, zeroHearts);
		} else {
			heartCount.setAmount(getPlayerScore(player));
			heartCount.setItemMeta(heartCountMeta);
		    inv.setItem(13, heartCount); // Assuming 13 is the slot of the heart count item
		}
	}

	public int countCustomPaperItems(Player player) {
		int count = 0;
		for (ItemStack item : player.getInventory().getContents()) {
			if (item != null && item.getType() == Material.PAPER) {
				ItemMeta meta = item.getItemMeta();
				if (meta != null && meta.hasCustomModelData() && meta.getCustomModelData() == 10012) {
					count += item.getAmount();
				}
			}
		}
		return count;
	}
	
	@EventHandler
	public void onInventoryClose(InventoryCloseEvent event) {
		Player player = (Player) event.getPlayer();
		if(playerScores.containsKey(player)) {
			playerScores.remove(player);
		}
	}

	@EventHandler
	public void onInventoryClick(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().startsWith("Revive Station")) {
			event.setCancelled(true);

			if (event.getSlot() == 10) {
				openDeathBansInventory(player, 1);
			}

			if (event.getSlot() == 14) {
				double hearts = getData().getInt(player.getUniqueId() + ".Hearts-Deposited");
				if (hearts != 0) {
					getData().set(player.getUniqueId() + ".Hearts-Deposited", hearts - 1);
					saveData();
					double currentMaxHealth = player.getMaxHealth();
					if (currentMaxHealth == 40) {
						Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
								"iagive " + player.getName() + " custom_texture_items:heart 1 silent");
					} else {
						player.setMaxHealth(currentMaxHealth + 2);
					}
					ReviveStationInventory(player);
				}
			}

			if (event.getSlot() == 16) {
				ItemStack[] items = event.getWhoClicked().getInventory().getContents();
				int count = 0;

				for (ItemStack item : items) {
					if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
							&& item.getItemMeta().hasCustomModelData()
							&& item.getItemMeta().getCustomModelData() == 10012) {
						count++;
					}
				}

				if (count > 0) {
					double hearts = getData().getInt(event.getWhoClicked().getUniqueId() + ".Hearts-Deposited");

					if (event.isShiftClick()) {
						// Remove all items and update hearts for all items
						for (ItemStack item : items) {
							if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
									&& item.getItemMeta().hasCustomModelData()
									&& item.getItemMeta().getCustomModelData() == 10012) {
								int amount = item.getAmount();
								item.setAmount(0); // Remove the item
								hearts += 1.0D * amount;
							}
						}
					} else {
						// Remove only one item and update hearts for one item
						for (ItemStack item : items) {
							if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
									&& item.getItemMeta().hasCustomModelData()
									&& item.getItemMeta().getCustomModelData() == 10012) {
								if (item.getAmount() > 1) {
									item.setAmount(item.getAmount() - 1);
								} else {
									item.setAmount(0); // Remove the item
								}
								hearts += 1.0D;
								break;
							}
						}
					}
					getData().set(event.getWhoClicked().getUniqueId() + ".Hearts-Deposited", hearts);
					saveData();
					ReviveStationInventory(player);
				}
			}
		}
	}
}
Leave a Comment