file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
ChatColorEscaper.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/chat/ChatColorEscaper.java
package me.patothebest.gamecore.chat; import me.patothebest.gamecore.command.ChatColor; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ChatColorEscaper { private static final char COLOR_CHAR = '\u00A7'; private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)[" + COLOR_CHAR + "&]([0-9A-FK-OR])"); private static final Pattern COLOR_PATTERN = Pattern.compile("%%([a-z_]+?)%%"); private ChatColorEscaper() {} public static String escapeColors(String originalString) { StringBuffer sb = new StringBuffer(); Matcher matcher = STRIP_COLOR_PATTERN.matcher(originalString); while (matcher.find()) { String colorChar = matcher.group(1); ChatColor byChar = ChatColor.getByChar(colorChar); matcher.appendReplacement(sb, "%%" + byChar.name().toLowerCase() + "%%"); } matcher.appendTail(sb); return sb.toString(); } public static String toColor(String originalString) { StringBuffer sb = new StringBuffer(); Matcher matcher = COLOR_PATTERN.matcher(originalString); while (matcher.find()) { String colorName = matcher.group(1); ChatColor byName = ChatColor.getByName(colorName.toUpperCase()); if (byName != null) { matcher.appendReplacement(sb, COLOR_CHAR + String.valueOf(byName.getChar())); } } matcher.appendTail(sb); return ChatColor.translateAlternateColorCodes('&', sb.toString()); } public static String toColorCodes(String originalString) { StringBuffer sb = new StringBuffer(); Matcher matcher = COLOR_PATTERN.matcher(originalString); while (matcher.find()) { String colorName = matcher.group(1); ChatColor byName = ChatColor.getByName(colorName.toUpperCase()); if (byName != null) { matcher.appendReplacement(sb, '&' + String.valueOf(byName.getChar())); } } matcher.appendTail(sb); return sb.toString(); } }
2,108
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DefaultWorldHandler.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/DefaultWorldHandler.java
package me.patothebest.gamecore.world; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.util.Utils; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; import java.io.File; import java.util.concurrent.CompletableFuture; public class DefaultWorldHandler implements WorldHandler { @Override public CompletableFuture<World> loadWorld(AbstractArena arena, String worldName, World.Environment environment) { CompletableFuture<World> completableFuture = new CompletableFuture<>(); WorldCreator worldCreator = new WorldCreator(worldName); worldCreator.environment(environment); worldCreator.generateStructures(false); worldCreator.generator(ArenaWorld.chunkGenerator); completableFuture.complete(Bukkit.createWorld(worldCreator)); return completableFuture; } @Override public boolean hasAsyncSupport() { return false; } @Override public boolean decompressWorld(AbstractArena arena, File worldZipFile, File tempWorld) { // unzip the world if (!Utils.unZip(worldZipFile.getPath(), tempWorld.getPath())) { return false; } new File(tempWorld, "uid.dat").delete(); return true; } @Override public void deleteWorld(File tempWorld) { // delete the world directory Utils.deleteFolder(tempWorld); } @Override public boolean unloadWorld(World world) { return Bukkit.unloadWorld(world, false); } }
1,553
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ArenaWorld.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/ArenaWorld.java
package me.patothebest.gamecore.world; import io.papermc.lib.PaperLib; import me.patothebest.gamecore.PluginConfig; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.option.options.EnvironmentOption; import me.patothebest.gamecore.arena.option.options.TimeOfDayOption; import me.patothebest.gamecore.util.Utils; import org.bukkit.Bukkit; import org.bukkit.Difficulty; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.concurrent.ExecutionException; public class ArenaWorld { // -------------------------------------------- // // CONSTANTS // -------------------------------------------- // // the blank chunk generator // this generator will create a world with only one // block there is no need to create one per class, // so that is why it is static final static BlankChunkGenerator chunkGenerator = new BlankChunkGenerator(); // the directory where all the world zip files // will be stored public final static File WORLD_DIRECTORY = new File(Utils.PLUGIN_DIR, "worlds" + File.separatorChar); // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final File worldZipFile; private final File tempWorld; private final String worldName; protected final AbstractArena arena; private World world; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public ArenaWorld(AbstractArena arena) { this(arena, arena.getWorldName()); } public ArenaWorld(AbstractArena arena, String arenaWorldName) { this.arena = arena; // If the world directory doesn't exist... if(!WORLD_DIRECTORY.exists()) { // ...create the directory WORLD_DIRECTORY.mkdirs(); } // the world zip file this.worldZipFile = new File(WORLD_DIRECTORY, arena.getName() + ".zip"); // the world directory this.worldName = PluginConfig.WORLD_PREFIX + arenaWorldName; this.tempWorld = new File(worldName + File.separatorChar); } // -------------------------------------------- // // PUBLIC METHODS // -------------------------------------------- // public boolean decompressWorld() { // unzip the world return arena.getWorldHandler().get().decompressWorld(arena, worldZipFile, tempWorld); } public void loadWorld(boolean permanentWorld) { loadWorld(permanentWorld, arena.getWorldHandler().get()); } public void loadWorld(boolean permanentWorld, WorldHandler worldHandler) { // WorldCreator World.Environment environment = arena.getOption(EnvironmentOption.class).getEnvironment(); if (tempWorld.exists()) { if (environment != World.Environment.NORMAL) { String dimFolderName = "DIM" + environment.getId(); String otherDim = "DIM" + (environment.getId() == -1 ? "1" : "-1"); File dimFolder = new File(tempWorld, dimFolderName); File otherDimFolder = new File(tempWorld, otherDim); if (!dimFolder.exists()) { dimFolder.mkdir(); if (otherDimFolder.exists()) { try { System.out.println(arena.getName() + ": Detected old dimension " + otherDim + ". Moving " + otherDim + " to " + dimFolderName); Files.move(new File(otherDimFolder, "poi").toPath(), new File(dimFolder, "poi").toPath(), StandardCopyOption.REPLACE_EXISTING); Files.move(new File(otherDimFolder, "region").toPath(), new File(dimFolder, "region").toPath(), StandardCopyOption.REPLACE_EXISTING); Utils.deleteFolder(otherDimFolder); } catch (IOException e) { e.printStackTrace(); } } else { if (new File(tempWorld, "region").exists()) { try { System.out.println(arena.getName() + ": Detected old dimension NORMAL. Moving NORMAL to " + dimFolderName); Files.move(new File(tempWorld, "poi").toPath(), new File(dimFolder, "poi").toPath(), StandardCopyOption.REPLACE_EXISTING); Files.move(new File(tempWorld, "region").toPath(), new File(dimFolder, "region").toPath(), StandardCopyOption.REPLACE_EXISTING); Utils.deleteFolder(new File(tempWorld, "poi")); Utils.deleteFolder(new File(tempWorld, "region")); } catch (IOException e) { e.printStackTrace(); } } } } } else { if (!new File(tempWorld, "region").exists()) { for (int dim : new int[]{-1, 1}) { File dimFolder = new File(tempWorld, "DIM" + dim); if (dimFolder.exists()) { try { System.out.println(arena.getName() + ": Detected old dimension DIM" + dim + ". Moving DIM" + dim + " to NORMAL"); Files.move(new File(tempWorld, "poi").toPath(), new File(dimFolder, "poi").toPath(), StandardCopyOption.REPLACE_EXISTING); Files.move(new File(tempWorld, "region").toPath(), new File(dimFolder, "region").toPath(), StandardCopyOption.REPLACE_EXISTING); Utils.deleteFolder(dimFolder); } catch (IOException e) { e.printStackTrace(); } } } } } } // create the world if (!permanentWorld) { try { world = worldHandler.loadWorld(arena, worldName, environment).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Could not load world " + worldName + "!", e); } } else { WorldCreator worldCreator = new WorldCreator(worldName); worldCreator.environment(environment); worldCreator.generateStructures(false); worldCreator.generator(chunkGenerator); world = Bukkit.createWorld(worldCreator); } if (environment == World.Environment.THE_END) { if (!Bukkit.getVersion().contains("1.8")) { // In 1.9 a dragon fight system was implemented, this allowed portals to be automatically created // The problem is that the portal spawns with the dragon and we don't want that, so we must remove // the EnderDragonBattle object from the world provider Object worldServer = Utils.invokeMethod(world, "getHandle", new Class[]{}); if (Bukkit.getVersion().contains("1.16")) { try { Utils.setFinalField(Utils.getFieldOrNull(Utils.getNMSClass("WorldServer"), "dragonBattle"), worldServer, null); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } else { Object worldProvider = Utils.invokeMethod(worldServer, Utils.getMethodNotDeclaredValue(worldServer.getClass(), "getWorldProvider"), new Class[]{}); try { Utils.setFinalField(Utils.getFieldOrNull(Utils.getNMSClass("WorldProviderTheEnd"), "g"), worldProvider, null); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } } } arena.getPluginScheduler().ensureSync(() -> { // set the time to day world.setTime(arena.getOption(TimeOfDayOption.class).getTime().getTick()); // no rain on the world world.setThundering(false); world.setStorm(false); world.setKeepSpawnInMemory(false); world.setAutoSave(permanentWorld); world.setWeatherDuration(Integer.MAX_VALUE); // default game rules world.setGameRuleValue("doMobSpawning", "false"); world.setGameRuleValue("mobGriefing", "true"); world.setGameRuleValue("doDaylightCycle", "false"); // difficulty hard world.setDifficulty(Difficulty.HARD); // set the world spawn location world.setSpawnLocation(0, 101, 0); }); if (arena.getArea() != null && !permanentWorld) { arena.getPluginScheduler().runTaskAsynchronously(() -> { if (PaperLib.isPaper()) { for (Location location : arena.getArea().getChunkLocations()) { try { PaperLib.getChunkAtAsync(location).get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); } } public void unloadWorld(boolean save) { if(world == null) { return; } world.getPlayers().forEach(player -> { // if the player is dead... if(player.isDead()) { try { // ...try to respawn the player player.spigot().respawn(); } catch(Throwable t) { // can't respawn the player (bukkit) so we kick him player.kickPlayer("Regenerating arena"); } } // teleport the player out of the world so we can unload it player.teleport(Bukkit.getWorlds().get(0).getSpawnLocation()); }); // attempt to unload the world boolean unloaded = save ? Bukkit.unloadWorld(world, save) : arena.getWorldHandler().get().unloadWorld(world); world = null; // If the world could not be unloaded... if(!unloaded) { // ...throw an exception throw new RuntimeException("Could not unload world " + world.getName()); } } public void deleteWorld() { arena.getWorldHandler().get().deleteWorld(tempWorld); } // -------------------------------------------- // // GETTERS // -------------------------------------------- // public World getWorld() { return world; } public File getTempWorld() { return tempWorld; } public File getWorldZipFile() { return worldZipFile; } @Override public String toString() { return "ArenaWorld{" + "worldZipFile=" + worldZipFile + ", tempWorld=" + tempWorld + ", worldName='" + worldName + '\'' + ", world=" + world + '}'; } }
11,467
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WorldManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/WorldManager.java
package me.patothebest.gamecore.world; import com.google.inject.Inject; import me.patothebest.gamecore.arena.ArenaManager; import me.patothebest.gamecore.modules.ListenerModule; public class WorldManager implements ListenerModule { private final ArenaManager arenaManager; @Inject private WorldManager(ArenaManager arenaManager) { this.arenaManager = arenaManager; } // TODO: Arena regen with only loading/unloading chunks /*@EventHandler public void onUnload(ChunkUnloadEvent event) { for (AbstractArena value : arenaManager.getArenas().values()) { if (value.getWorld() == event.getWorld()) { if (!value.isEnabled()) { return; } event.setSaveChunk(false); return; } } }*/ }
841
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BlankChunkGenerator.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/BlankChunkGenerator.java
package me.patothebest.gamecore.world; import me.patothebest.gamecore.itemstack.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import java.util.ArrayList; import java.util.List; import java.util.Random; class BlankChunkGenerator extends ChunkGenerator { // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // //This is where you stick your populators - these will be covered in another tutorial @Override public List<BlockPopulator> getDefaultPopulators(World world) { return new ArrayList<>(); } //This needs to be set to return true to override minecraft's default behaviour @Override public boolean canSpawn(World world, int x, int z) { return true; } @Override public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid biome) { ChunkData chunkData = createChunkData(world); for (int x = 0; x <= 15; x++) { for (int z = 0; z <= 15; z++) { biome.setBiome(x, z, Biome.PLAINS); } } if(cx == 0 && cz == 0) { chunkData.setBlock(0, 100, 0, Material.BEDROCK.parseMaterial()); } return chunkData; } }
1,373
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WorldHandler.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/WorldHandler.java
package me.patothebest.gamecore.world; import me.patothebest.gamecore.arena.AbstractArena; import org.bukkit.World; import java.io.File; import java.util.concurrent.CompletableFuture; public interface WorldHandler { CompletableFuture<World> loadWorld(AbstractArena arena, String worldName, World.Environment environment); boolean decompressWorld(AbstractArena arena, File worldZipFile, File tempWorld); void deleteWorld(File tempWorld); boolean unloadWorld(World world); boolean hasAsyncSupport(); }
528
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
InfinityWorld.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/infinity/InfinityWorld.java
package me.patothebest.gamecore.world.infinity; import com.grinderwolf.swm.api.exceptions.CorruptedWorldException; import com.grinderwolf.swm.api.exceptions.NewerFormatException; import com.grinderwolf.swm.api.exceptions.UnknownWorldException; import com.grinderwolf.swm.api.exceptions.WorldInUseException; import com.grinderwolf.swm.api.loaders.SlimeLoader; import com.grinderwolf.swm.api.world.SlimeChunk; import com.grinderwolf.swm.api.world.SlimeWorld; import com.grinderwolf.swm.nms.CraftSlimeWorld; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.world.ArenaWorld; import org.bukkit.World; import org.bukkit.util.Vector; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Set; public class InfinityWorld extends ArenaWorld { private final SlimeLoader loader; private final SlimeWorld slimeWorld; private final World world; private Set<Long> chunkCoordinates; public InfinityWorld(AbstractArena arena, SlimeLoader loader, SlimeWorld slimeWorld, World world) { super(arena); this.loader = loader; this.slimeWorld = slimeWorld; this.world = world; } @Override public boolean decompressWorld() { return super.decompressWorld(); } @Override public void loadWorld(boolean permanentWorld) { if (permanentWorld) { throw new UnsupportedOperationException("Permanent worlds are not supported!"); } try { byte[] serializedWorld = loader.loadWorld(arena.getName(), true); Vector offset = arena.getOffset(); Map<Long, SlimeChunk> slimeChunkMap = SlimeWorldUtils.deserializeWorld(offset.getBlockX(), offset.getBlockZ(), arena.getWorldName(), serializedWorld); chunkCoordinates = slimeChunkMap.keySet(); arena.getPluginScheduler().ensureSync(() -> ((CraftSlimeWorld)slimeWorld).getChunks().putAll(slimeChunkMap)); } catch (UnknownWorldException | WorldInUseException | IOException | NewerFormatException | CorruptedWorldException e) { e.printStackTrace(); } } @Override public void unloadWorld(boolean save) { if (save) { throw new UnsupportedOperationException("Saving the world is not supported"); } Map<Long, SlimeChunk> chunks = ((CraftSlimeWorld) slimeWorld).getChunks(); for (Long chunkCoordinate : chunkCoordinates) { SlimeChunk slimeChunk = chunks.get(chunkCoordinate); if (slimeChunk != null) { world.unloadChunk(slimeChunk.getX(), slimeChunk.getZ(), false); chunks.remove(chunkCoordinate); } } chunkCoordinates.clear(); } @Override public void deleteWorld() { } @Override public World getWorld() { return world; } @Override public File getTempWorld() { return null; } @Override public File getWorldZipFile() { return null; } }
3,035
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SlimeWorldUtils.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/world/infinity/SlimeWorldUtils.java
package me.patothebest.gamecore.world.infinity; import com.github.luben.zstd.Zstd; import com.grinderwolf.swm.api.exceptions.CorruptedWorldException; import com.grinderwolf.swm.api.exceptions.NewerFormatException; import com.grinderwolf.swm.api.utils.NibbleArray; import com.grinderwolf.swm.api.utils.SlimeFormat; import com.grinderwolf.swm.api.world.SlimeChunk; import com.grinderwolf.swm.api.world.SlimeChunkSection; import com.grinderwolf.swm.internal.com.flowpowered.nbt.CompoundMap; import com.grinderwolf.swm.internal.com.flowpowered.nbt.CompoundTag; import com.grinderwolf.swm.internal.com.flowpowered.nbt.DoubleTag; import com.grinderwolf.swm.internal.com.flowpowered.nbt.IntArrayTag; import com.grinderwolf.swm.internal.com.flowpowered.nbt.IntTag; import com.grinderwolf.swm.internal.com.flowpowered.nbt.ListTag; import com.grinderwolf.swm.internal.com.flowpowered.nbt.TagType; import com.grinderwolf.swm.internal.com.flowpowered.nbt.stream.NBTInputStream; import com.grinderwolf.swm.nms.CraftSlimeChunk; import com.grinderwolf.swm.nms.CraftSlimeChunkSection; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; public class SlimeWorldUtils { public static Map<Long, SlimeChunk> deserializeWorld(int xOffset, int zOffset, String worldName, byte[] serializedWorld) throws IOException, CorruptedWorldException, NewerFormatException { DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(serializedWorld)); try { byte[] fileHeader = new byte[SlimeFormat.SLIME_HEADER.length]; dataStream.read(fileHeader); if (!Arrays.equals(SlimeFormat.SLIME_HEADER, fileHeader)) { throw new CorruptedWorldException(worldName); } // File version byte version = dataStream.readByte(); if (version > SlimeFormat.SLIME_VERSION) { throw new NewerFormatException(version); } // World version byte worldVersion; if (version >= 6) { worldVersion = dataStream.readByte(); } else if (version >= 4) { // In v4 there's just a boolean indicating whether the world is pre-1.13 or post-1.13 worldVersion = (byte) (dataStream.readBoolean() ? 0x04 : 0x01); } else { worldVersion = 0; // We'll try to automatically detect it later } // Chunk int chunkOffsetX = xOffset >> 4; int chunkOffsetZ = zOffset >> 4; short minX = dataStream.readShort(); short minZ = dataStream.readShort(); int width = dataStream.readShort(); int depth = dataStream.readShort(); if (width <= 0 || depth <= 0) { throw new CorruptedWorldException(worldName); } int bitmaskSize = (int) Math.ceil((width * depth) / 8.0D); byte[] chunkBitmask = new byte[bitmaskSize]; dataStream.read(chunkBitmask); BitSet chunkBitset = BitSet.valueOf(chunkBitmask); int compressedChunkDataLength = dataStream.readInt(); int chunkDataLength = dataStream.readInt(); byte[] compressedChunkData = new byte[compressedChunkDataLength]; byte[] chunkData = new byte[chunkDataLength]; dataStream.read(compressedChunkData); // Tile Entities int compressedTileEntitiesLength = dataStream.readInt(); int tileEntitiesLength = dataStream.readInt(); byte[] compressedTileEntities = new byte[compressedTileEntitiesLength]; byte[] tileEntities = new byte[tileEntitiesLength]; dataStream.read(compressedTileEntities); // Entities byte[] compressedEntities = new byte[0]; byte[] entities = new byte[0]; if (version >= 3) { boolean hasEntities = dataStream.readBoolean(); if (hasEntities) { int compressedEntitiesLength = dataStream.readInt(); int entitiesLength = dataStream.readInt(); compressedEntities = new byte[compressedEntitiesLength]; entities = new byte[entitiesLength]; dataStream.read(compressedEntities); } } // Extra NBT tag byte[] compressedExtraTag = new byte[0]; byte[] extraTag = new byte[0]; if (version >= 2) { int compressedExtraTagLength = dataStream.readInt(); int extraTagLength = dataStream.readInt(); compressedExtraTag = new byte[compressedExtraTagLength]; extraTag = new byte[extraTagLength]; dataStream.read(compressedExtraTag); } // World Map NBT tag byte[] compressedMapsTag = new byte[0]; byte[] mapsTag = new byte[0]; if (version >= 7) { int compressedMapsTagLength = dataStream.readInt(); int mapsTagLength = dataStream.readInt(); compressedMapsTag = new byte[compressedMapsTagLength]; mapsTag = new byte[mapsTagLength]; dataStream.read(compressedMapsTag); } if (dataStream.read() != -1) { throw new CorruptedWorldException(worldName); } // Data decompression Zstd.decompress(chunkData, compressedChunkData); Zstd.decompress(tileEntities, compressedTileEntities); Zstd.decompress(entities, compressedEntities); Zstd.decompress(extraTag, compressedExtraTag); Zstd.decompress(mapsTag, compressedMapsTag); // Chunk deserialization Map<Long, SlimeChunk> chunks = readChunks(worldVersion, version, worldName, chunkOffsetX, chunkOffsetZ, minX, minZ, width, depth, chunkBitset, chunkData); // Entity deserialization CompoundTag entitiesCompound = readCompoundTag(entities); if (entitiesCompound != null) { ListTag<CompoundTag> entitiesList = (ListTag<CompoundTag>) entitiesCompound.getValue().get("entities"); for (CompoundTag entityCompound : entitiesList.getValue()) { ListTag<DoubleTag> listTag = (ListTag<DoubleTag>) entityCompound.getAsListTag("Pos").get(); DoubleTag xTag = listTag.getValue().get(0); xTag.setValue(xTag.getValue() + xOffset); DoubleTag zTag = listTag.getValue().get(2); zTag.setValue(zTag.getValue() + zOffset); if (entityCompound.getValue().containsKey("TileX")) { IntTag xTileTag = (IntTag) entityCompound.getValue().get("TileX"); IntTag zTileTag = (IntTag) entityCompound.getValue().get("TileZ"); xTileTag.setValue(xTileTag.getValue() + xOffset); zTileTag.setValue(zTileTag.getValue() + zOffset); } int chunkX = floor(xTag.getValue()) >> 4; int chunkZ = floor(zTag.getValue()) >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getEntities().add(entityCompound); } } // Tile Entity deserialization CompoundTag tileEntitiesCompound = readCompoundTag(tileEntities); if (tileEntitiesCompound != null) { ListTag<CompoundTag> tileEntitiesList = (ListTag<CompoundTag>) tileEntitiesCompound.getValue().get("tiles"); for (CompoundTag tileEntityCompound : tileEntitiesList.getValue()) { IntTag xTag = (IntTag) tileEntityCompound.getValue().get("x"); IntTag zTag = (IntTag) tileEntityCompound.getValue().get("z"); xTag.setValue(xTag.getValue() + xOffset); zTag.setValue(zTag.getValue() + zOffset); int chunkX = xTag.getValue() >> 4; int chunkZ = zTag.getValue() >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getTileEntities().add(tileEntityCompound); } } // No support for world Maps return chunks; } catch (EOFException ex) { throw new CorruptedWorldException(worldName, ex); } } private static int floor(double num) { final int floor = (int) num; return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); } private static Map<Long, SlimeChunk> readChunks(byte worldVersion, int version, String worldName, int chunkOffsetX, int chunkOffsetZ, int minX, int minZ, int width, int depth, BitSet chunkBitset, byte[] chunkData) throws IOException { DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(chunkData)); Map<Long, SlimeChunk> chunkMap = new HashMap<>(); for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { int bitsetIndex = z * width + x; if (chunkBitset.get(bitsetIndex)) { // Height Maps CompoundTag heightMaps; if (worldVersion >= 0x04) { int heightMapsLength = dataStream.readInt(); byte[] heightMapsArray = new byte[heightMapsLength]; dataStream.read(heightMapsArray); heightMaps = readCompoundTag(heightMapsArray); // Height Maps might be null if empty if (heightMaps == null) { heightMaps = new CompoundTag("", new CompoundMap()); } } else { int[] heightMap = new int[256]; for (int i = 0; i < 256; i++) { heightMap[i] = dataStream.readInt(); } CompoundMap map = new CompoundMap(); map.put("heightMap", new IntArrayTag("heightMap", heightMap)); heightMaps = new CompoundTag("", map); } // Biome array int[] biomes; if (worldVersion >= 0x04) { int biomesArrayLength = version >= 8 ? dataStream.readInt() : 256; biomes = new int[biomesArrayLength]; for (int i = 0; i < biomes.length; i++) { biomes[i] = dataStream.readInt(); } } else { byte[] byteBiomes = new byte[256]; dataStream.read(byteBiomes); biomes = toIntArray(byteBiomes); } // Chunk Sections SlimeChunkSection[] sections = readChunkSections(dataStream, worldVersion, version); chunkMap.put(((long) minZ + z + chunkOffsetZ) * Integer.MAX_VALUE + ((long) minX + x + chunkOffsetX), new CraftSlimeChunk(worldName,minX + x + chunkOffsetX, minZ + z + chunkOffsetZ, sections, heightMaps, biomes, new ArrayList<>(), new ArrayList<>())); } } } return chunkMap; } private static int[] toIntArray(byte[] buf) { ByteBuffer buffer = ByteBuffer.wrap(buf).order(ByteOrder.BIG_ENDIAN); int[] ret = new int[buf.length / 4]; buffer.asIntBuffer().get(ret); return ret; } private static SlimeChunkSection[] readChunkSections(DataInputStream dataStream, byte worldVersion, int version) throws IOException { SlimeChunkSection[] chunkSectionArray = new SlimeChunkSection[16]; byte[] sectionBitmask = new byte[2]; dataStream.read(sectionBitmask); BitSet sectionBitset = BitSet.valueOf(sectionBitmask); for (int i = 0; i < 16; i++) { if (sectionBitset.get(i)) { // Block Light Nibble Array NibbleArray blockLightArray; if (version < 5 || dataStream.readBoolean()) { byte[] blockLightByteArray = new byte[2048]; dataStream.read(blockLightByteArray); blockLightArray = new NibbleArray((blockLightByteArray)); } else { blockLightArray = null; } // Block data byte[] blockArray; NibbleArray dataArray; ListTag<CompoundTag> paletteTag; long[] blockStatesArray; // Post 1.13 block format if (worldVersion >= 0x04) { // Palette int paletteLength = dataStream.readInt(); List<CompoundTag> paletteList = new ArrayList<>(paletteLength); for (int index = 0; index < paletteLength; index++) { int tagLength = dataStream.readInt(); byte[] serializedTag = new byte[tagLength]; dataStream.read(serializedTag); paletteList.add(readCompoundTag(serializedTag)); } paletteTag = new ListTag<>("", TagType.TAG_COMPOUND, paletteList); // Block states int blockStatesArrayLength = dataStream.readInt(); blockStatesArray = new long[blockStatesArrayLength]; for (int index = 0; index < blockStatesArrayLength; index++) { blockStatesArray[index] = dataStream.readLong(); } blockArray = null; dataArray = null; } else { blockArray = new byte[4096]; dataStream.read(blockArray); // Block Data Nibble Array byte[] dataByteArray = new byte[2048]; dataStream.read(dataByteArray); dataArray = new NibbleArray((dataByteArray)); paletteTag = null; blockStatesArray = null; } // Sky Light Nibble Array NibbleArray skyLightArray; if (version < 5 || dataStream.readBoolean()) { byte[] skyLightByteArray = new byte[2048]; dataStream.read(skyLightByteArray); skyLightArray = new NibbleArray((skyLightByteArray)); } else { skyLightArray = null; } // HypixelBlocks 3 if (version < 4) { short hypixelBlocksLength = dataStream.readShort(); dataStream.skip(hypixelBlocksLength); } chunkSectionArray[i] = new CraftSlimeChunkSection(blockArray, dataArray, paletteTag, blockStatesArray, blockLightArray, skyLightArray); } } return chunkSectionArray; } private static CompoundTag readCompoundTag(byte[] serializedCompound) throws IOException { if (serializedCompound.length == 0) { return null; } NBTInputStream stream = new NBTInputStream(new ByteArrayInputStream(serializedCompound), NBTInputStream.NO_COMPRESSION, ByteOrder.BIG_ENDIAN); return (CompoundTag) stream.readTag(); } }
16,457
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
VersionFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/VersionFile.java
package me.patothebest.gamecore.file; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; import java.util.Map; public class VersionFile extends FlatFile { // -------------------------------------------- // // FIELDS // -------------------------------------------- // protected final JavaPlugin plugin; protected String versionFileName; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public VersionFile(JavaPlugin plugin, String fileName) { super(fileName); this.plugin = plugin; this.versionFileName = this.fileName; } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public void load() { super.load(); try { // read jar config YamlConfiguration yamlConfiguration = new YamlConfiguration(); yamlConfiguration.loadFromString(fileToYAML(plugin.getResource(versionFileName))); // compare config versions if(!isSet("file-version") || get("file-version") != yamlConfiguration.get("file-version")) { Map<String, Object> toOverride = new HashMap<>(); // get this config's values getValues(true).forEach((key, object) -> { // filter out all the comments as we only want values if(key.contains("GAMECORE_COMMENT") || key.contains("GAMECORE_BLANKLINE") || key.contains("file-version")) { return; } // store in cache map toOverride.put(key, object); }); // delete the config delete(); // clear the map from MemorySection, this is // to avoid clashes map.clear(); // generate new file and load it super.load(); // set all the values from the cache to the new config toOverride.forEach(this::set); // save the updated config save(); } } catch (Exception e) { System.err.println("Could not load file from jar"); e.printStackTrace(); } } }
2,441
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
FlatFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/FlatFile.java
package me.patothebest.gamecore.file; import com.google.common.io.Files; import me.patothebest.gamecore.util.Utils; import org.apache.commons.lang.StringUtils; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; import org.yaml.snakeyaml.DumperOptions; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; public class FlatFile extends YamlConfiguration { // -------------------------------------------- // // FIELDS // -------------------------------------------- // protected final File file; protected final String fileName; protected String header; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public FlatFile(String fileName) { this.fileName = fileName + ".yml"; this.file = new File(Utils.PLUGIN_DIR, this.fileName); this.header = fileName; DumperOptions dumperOptions = Utils.getFieldValue(YamlConfiguration.class, "yamlOptions", this); assert dumperOptions != null; dumperOptions.setWidth(Integer.MAX_VALUE); } public FlatFile(File file) { this.file = file; this.fileName = file.getName(); this.header = file.getName(); } // -------------------------------------------- // // PUBLIC METHODS // -------------------------------------------- // public void save() { try { save(file); } catch (IOException e) { e.printStackTrace(); } } @Override public void save(File file) throws IOException { try { // create parent directory Files.createParentDirs(file); // We convert the default YAML file comments // into YAML paths so that they aren't deleted by // the poorly coded loading and saving YAML methods String data = escapeYamlCharacters(saveToString()); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { // write the data into the file writer.write(data); } } catch (IOException ex) { Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save " + file.getName() + " to " + file.getPath(), ex); } } public void delete() { file.delete(); } public File getFile() { return file; } // -------------------------------------------- // // CLASS METHODS // -------------------------------------------- // protected void generateFile() { try { // create parent directory and the file Files.createParentDirs(file); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } // create a bufferedwriter to write into the file try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));){ // write and close the writer writeFile(writer); } catch (IOException e) { e.printStackTrace(); } } protected void writeFile(BufferedWriter writer) throws IOException { // each file contains a header only writer.write(getHeader(header)); } public void load() { // first we clear to avoid any issues map.clear(); // if the file doesn't exist... if(!file.exists()) { // ...generate the file generateFile(); } try { // load the file loadFromString(fileToYAML(file)); } catch (InvalidConfigurationException e1) { System.out.println("Error while loading file " + file.getName()); e1.printStackTrace(); // rename the file to broken file.renameTo(new File(Utils.PLUGIN_DIR, file.getName().substring(0, file.getName().length()-4) + ".broken-" + System.currentTimeMillis() + ".yml")); // generate a new file load(); } catch (IOException e) { e.printStackTrace(); } } protected String fileToYAML(File fileToRead) throws IOException { // create a FileInputStream FileInputStream stream = new FileInputStream(fileToRead); // load the file return fileToYAML(stream); } protected String fileToYAML(InputStream stream) throws IOException { // create the InputStreamReader with Charset UTF-8, // this allows loading files with special characters // such as accents InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); BufferedReader input = new BufferedReader(reader); int commentNum = 0; int spaces = 0; boolean stringList = false; String addLine; String currentLine; StringBuilder whole = new StringBuilder(); // read all the lines from the file while ((currentLine = input.readLine()) != null) { if (currentLine.equalsIgnoreCase("---")) { // crowdin line ignore continue; } // if the line starts with the #... if (currentLine.replace(" ", "").startsWith("#")) { // ...it is a comment so we need to convert it // into a YAML path addLine = currentLine.replace(":", "REPLACED_COLON").replace("'", "SINGLE_QUOTE").replace("{", "RIGHT_BRACKET").replace("}", "LEFT_BRACKET").replace("(", "RIGHT_PARENTHESIS").replace(")", "LEFT_PARENTHESIS").replaceFirst("#", "GAMECORE_COMMENT_" + commentNum + ":").replace(": ", ": '").replace(":#", ": '#"); whole.append(addLine).append("'\n"); commentNum++; spaces = countSpaces(addLine); } else if(currentLine.isEmpty()) { // the line is blank so we just use GAMECORE_BLANKLINE // as an identifier for the blank line whole.append(StringUtils.repeat(" ", (stringList ? spaces-2 : spaces))).append("GAMECORE_BLANKLINE").append(commentNum).append(": ''\n"); commentNum++; } else { // the line is a normal line so just append stringList = currentLine.trim().startsWith("-"); whole.append(currentLine).append("\n"); spaces = countSpaces(currentLine); } } input.close(); return whole.toString(); } protected int countSpaces(String str) { int count = 0; for(int i = 0; i < str.length(); i++) { if(Character.isWhitespace(str.charAt(i))) { count++; } else { return count; } } return count; } private String escapeYamlCharacters(String configString) { String[] lines = configString.split("\n"); StringBuilder config = new StringBuilder(); for (String line : lines) { if (line.contains("GAMECORE_COMMENT")) { String comment = line.replace(line.substring(line.indexOf("GAMECORE_COMMENT"), line.indexOf(":") + 2), "# "); if (comment.startsWith("# '")) { comment = comment.substring(0, comment.length() - 1).replaceFirst("# '#", "##").replaceFirst("# '", "# ").replace("REPLACED_COLON", ":"); } else { comment = comment.replace("REPLACED_COLON", ":").replace("SINGLE_QUOTE", "'").replace("RIGHT_BRACKET", "{").replace("LEFT_BRACKET", "}").replace("RIGHT_PARENTHESIS", "(").replace("LEFT_PARENTHESIS", ")"); } config.append(comment).append("\n"); } else if(line.contains("GAMECORE_BLANKLINE")) { config.append("\n"); } else { config.append(line).append("\n"); } } return config.toString(); } protected String getHeader(String title) { return "############################################################\n" + "# +------------------------------------------------------+ #\n" + "# |" + StringUtils.center(title, 54) + "| #\n" + "# +------------------------------------------------------+ #\n" + "############################################################\n"; } }
8,925
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ParserException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/ParserException.java
package me.patothebest.gamecore.file; public class ParserException extends RuntimeException { public ParserException() { } public ParserException(String message) { super(message); } public ParserException(String message, Throwable cause) { super(message, cause); } }
311
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ParserValidations.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/ParserValidations.java
package me.patothebest.gamecore.file; public class ParserValidations { public static void isTrue(boolean expression) { isTrue(expression, "The validated expression is false"); } public static void isTrue(boolean expression, String message) { if (!expression) { throw new ParserException(message); } } public static void notNull(Object object) { notNull(object, "The validated object is null"); } public static void notNull(Object object, String message) { if (object == null) { throw new ParserException(message); } } }
630
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PluginHookFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/PluginHookFile.java
package me.patothebest.gamecore.file; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.modules.Module; import me.patothebest.gamecore.util.Utils; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.IOException; public class PluginHookFile extends VersionFile implements Module { // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // @Inject public PluginHookFile(CorePlugin plugin) { super(plugin, "plugin-hooks"); this.header = "Plugin Hooks"; load(); } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override protected void writeFile(BufferedWriter writer) throws IOException { super.writeFile(writer); Utils.writeFileToWriter(writer, plugin.getResource("plugin-hooks.yml")); } }
951
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DeathMessagesFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/DeathMessagesFile.java
package me.patothebest.gamecore.file; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.modules.Module; import me.patothebest.gamecore.util.Utils; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.IOException; public class DeathMessagesFile extends VersionFile implements Module { // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // @Inject public DeathMessagesFile(CorePlugin plugin) { super(plugin, "death-messages"); this.header = "Death Messages"; load(); } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override protected void writeFile(BufferedWriter writer) throws IOException { super.writeFile(writer); Utils.writeFileToWriter(writer, plugin.getResource("death-messages.yml")); } }
963
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
InventoryItem.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/InventoryItem.java
package me.patothebest.gamecore.file; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.util.Utils; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; import java.util.Map; public class InventoryItem implements ConfigurationSerializable { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final String configName; private final String name; private final int slot; private final List<String> lore; private final ItemStackBuilder itemStack; private String command; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // @SuppressWarnings("unchecked") public InventoryItem(String configName, Map<String, Object> map) { this.configName = configName; this.name = (String) map.get("name"); this.slot = (int) map.get("slot"); this.lore = (List<String>) map.get("lore"); this.itemStack = new ItemStackBuilder(Utils.itemStackFromString((String) map.get("item"))); if (map.containsKey("command")) { command = (String) map.get("command"); } itemStack.name(name); itemStack.lore(lore); } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<>(); map.put("name", name); map.put("lore", lore.toArray()); map.put("slot", slot); map.put("item", Utils.itemStackToString(itemStack)); return map; } // -------------------------------------------- // // GETTERS // -------------------------------------------- // public ItemStack getItemStack() { return itemStack; } public int getSlot() { return slot; } public String getName() { return configName; } public String getCommand() { return command; } }
2,222
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ReadOnlyFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/ReadOnlyFile.java
package me.patothebest.gamecore.file; import org.apache.commons.lang.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class ReadOnlyFile extends FlatFile { // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public ReadOnlyFile(String fileName) { super(fileName); } public ReadOnlyFile(File file) { super(file); } // -------------------------------------------- // // PUBLIC METHODS // -------------------------------------------- // @Override public void save() { throw new UnsupportedOperationException("File is read-only!"); } @Override public void save(File file) throws IOException { throw new UnsupportedOperationException("File is read-only!"); } @Override public void delete() { throw new UnsupportedOperationException("File is read-only!"); } // -------------------------------------------- // // CLASS METHODS // -------------------------------------------- // @Override protected String fileToYAML(InputStream stream) throws IOException { // create the InputStreamReader with Charset UTF-8, // this allows loading files with special characters // such as accents InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); BufferedReader input = new BufferedReader(reader); String currentLine; StringBuilder whole = new StringBuilder(); // read all the lines from the file while ((currentLine = input.readLine()) != null) { whole.append(currentLine).append("\n"); } input.close(); return whole.toString(); } protected String getHeader(String title) { return "############################################################\n" + "# +------------------------------------------------------+ #\n" + "# |" + StringUtils.center(title, 54) + "| #\n" + "# +------------------------------------------------------+ #\n" + "############################################################\n"; } }
2,377
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CoreConfig.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/file/CoreConfig.java
package me.patothebest.gamecore.file; import me.patothebest.gamecore.lang.CoreLocaleManager; import me.patothebest.gamecore.lang.Locale; import me.patothebest.gamecore.modules.ReloadPriority; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.Priority; import org.bukkit.Location; import org.bukkit.plugin.java.JavaPlugin; import java.io.BufferedWriter; import java.io.IOException; @ReloadPriority(priority = Priority.LOW) public abstract class CoreConfig extends VersionFile implements ReloadableModule { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private Locale defaultLocale; private int countdownTime; private Location mainLobby; private int levelsToGive; private boolean useMainLobby; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public CoreConfig(JavaPlugin plugin, String fileName) { super(plugin, fileName); this.versionFileName = "core-config.yml"; } // -------------------------------------------- // // METHODS // -------------------------------------------- // public void readConfig() { // Countdown time until arena starts countdownTime = getInt("countdown"); // Default locale String defaultLocaleName = getString("default-locale","en"); if (defaultLocaleName.equalsIgnoreCase("es")) { defaultLocaleName = "es_ES"; } defaultLocale = CoreLocaleManager.getLocale(defaultLocaleName); // Levels to give to each player after they kill someone levelsToGive = getInt("levels-on-kill"); // MainLobby // If there is no main lobby, the default world // spawn will be used if(isSet("MainLobby")) { mainLobby = Location.deserialize(getConfigurationSection("MainLobby").getValues(true)); } if(isSet("teleport.location")) { useMainLobby = getString("teleport.location").equalsIgnoreCase("MainLobby"); } } @Override public void writeFile(BufferedWriter writer) throws IOException { super.writeFile(writer); Utils.writeFileToWriter(writer, plugin.getResource("core-config.yml")); Utils.writeFileToWriter(writer, plugin.getResource("config.yml")); } @Override public void onReload() { load(); readConfig(); } @Override public String getReloadName() { return "config"; } // -------------------------------------------- // // GETTERS AND SETTERS // -------------------------------------------- // public int getCountdownTime() { return countdownTime; } public Location getMainLobby() { return mainLobby; } public Locale getDefaultLocale() { return defaultLocale; } public void setMainLobby(Location mainLobby) { this.mainLobby = mainLobby; } public int getLevelsToGive() { return levelsToGive; } public boolean isUseMainLobby() { return useMainLobby; } public void setUseMainLobby(boolean useMainLobby) { this.useMainLobby = useMainLobby; } }
3,349
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BungeeStateUpdate.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/api/BungeeStateUpdate.java
package me.patothebest.gamecore.api; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class BungeeStateUpdate extends Event { private static final HandlerList handlers = new HandlerList(); private final String newMOTD; public BungeeStateUpdate(String newMOTD) { this.newMOTD = newMOTD; } /** * Gets the new MOTD * * @return the new MOTD */ public String getNewMOTD() { return newMOTD; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
636
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ReloadPriority.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ReloadPriority.java
package me.patothebest.gamecore.modules; import me.patothebest.gamecore.util.Priority; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Defines the priority in which the module will be reloaded * This annotation is optional and must be used exclusively * on the class which implements {@link ReloadableModule} * <p> * First priority to the last priority executed: * <ol> * <li>LOWEST * <li>LOW * <li>NORMAL * <li>HIGH * <li>HIGHEST * </ol> */ @Retention(value = RetentionPolicy.RUNTIME) public @interface ReloadPriority { /** * Gets the priority the module will be reloaded in * * @return the priority the module should be reloaded in */ Priority priority(); }
754
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ActivableModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ActivableModule.java
package me.patothebest.gamecore.modules; import me.patothebest.gamecore.injector.Activatable; public interface ActivableModule extends Module, Activatable { default void onPreEnable() {} default void onPostEnable() {} }
233
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ModulePriority.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ModulePriority.java
package me.patothebest.gamecore.modules; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.util.Priority; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Defines the priority in which the module will be loaded * in on the {@link CorePlugin#onEnable()}. This annotation * is optional and must be used exclusively on the class * which implements {@link Module} * <p> * First priority to the last priority executed: * <ol> * <li>LOWEST * <li>LOW * <li>NORMAL * <li>HIGH * <li>HIGHEST * </ol> */ @Retention(value = RetentionPolicy.RUNTIME) public @interface ModulePriority { /** * Gets the priority the module will be loaded in * * @return the priority the module should be loaded in */ Priority priority(); }
823
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ReloadableModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ReloadableModule.java
package me.patothebest.gamecore.modules; public interface ReloadableModule extends Module { void onReload(); String getReloadName(); }
147
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ModuleName.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ModuleName.java
package me.patothebest.gamecore.modules; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(value = RetentionPolicy.RUNTIME) @Target(value = ElementType.TYPE) public @interface ModuleName { String value(); }
337
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ListenerModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/modules/ListenerModule.java
package me.patothebest.gamecore.modules; import org.bukkit.event.Listener; public interface ListenerModule extends Module, Listener { }
139
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/KitFile.java
package me.patothebest.gamecore.kit; import me.patothebest.gamecore.file.FlatFile; import java.io.File; import java.io.IOException; public class KitFile extends FlatFile { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final Kit kit; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public KitFile(Kit kit) { super("kits" + File.separatorChar + kit.getKitName()); this.header = "Kit" + kit.getKitName() + " data"; this.kit = kit; load(); } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public void save() { set("data", kit.serialize()); try { save(file); } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { return "KitFile{" + "kit=" + kit.getKitName() + '}'; } }
1,130
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
NullKit.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/NullKit.java
package me.patothebest.gamecore.kit; import com.google.inject.Inject; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.permission.PermissionGroupManager; import org.bukkit.inventory.ItemStack; public class NullKit extends Kit { @Inject private NullKit(CorePlugin plugin, PermissionGroupManager permissionGroupManager) { super(plugin, permissionGroupManager, "Default", new ItemStack[1], new ItemStack[1]); } }
454
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/KitModule.java
package me.patothebest.gamecore.kit; import com.google.inject.TypeLiteral; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.multibindings.MapBinder; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.commands.kit.KitCommand; import me.patothebest.gamecore.commands.user.UserKitCommand; import me.patothebest.gamecore.injector.InstanceProvider; import me.patothebest.gamecore.kit.entities.KitFlatFileEntity; import me.patothebest.gamecore.kit.entities.KitMySQLEntity; import me.patothebest.gamecore.storage.StorageModule; import me.patothebest.gamecore.storage.flatfile.FlatFileEntity; import me.patothebest.gamecore.storage.mysql.MySQLEntity; import me.patothebest.gamecore.treasure.reward.Reward; import me.patothebest.gamecore.treasure.reward.RewardProvider; import me.patothebest.gamecore.treasure.reward.rewards.KitReward; public class KitModule extends StorageModule { public KitModule(CorePlugin plugin) { super(plugin); } @Override protected void configure() { super.configure(); install(new FactoryModuleBuilder().build(KitFactory.class)); registerModule(UserKitCommand.class); registerModule(KitCommand.class); registerModule(KitCommand.Parent.class); MapBinder<String, InstanceProvider<Reward>> mapBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {}, new TypeLiteral<InstanceProvider<Reward>>() {}); mapBinder.addBinding("kit").toInstance(new RewardProvider(KitReward.class)); } @Override protected Class<? extends FlatFileEntity> getFlatFileEntity() { return KitFlatFileEntity.class; } @Override protected Class<? extends MySQLEntity> getSQLEntity() { return KitMySQLEntity.class; } }
1,808
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WrappedPotionEffect.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/WrappedPotionEffect.java
package me.patothebest.gamecore.kit; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.LivingEntity; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.Map; import java.util.NoSuchElementException; @SerializableAs("WrappedPotionEffect") public class WrappedPotionEffect extends PotionEffect { private static final String AMPLIFIER = "amplifier"; private static final String DURATION = "duration"; private static final String TYPE = "effect"; private static final String AMBIENT = "ambient"; private static final String PARTICLES = "has-particles"; private int amplifier; private int duration; private PotionEffectType type; private boolean ambient; private boolean particles; private Color color; public WrappedPotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles, Color color) { super(type, duration, amplifier, ambient, particles); Validate.notNull(type, "effect type cannot be null"); this.type = type; this.duration = duration; this.amplifier = amplifier; this.ambient = ambient; this.particles = particles; this.color = color; } public WrappedPotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles) { this(type, duration, amplifier, ambient, particles, null); } public WrappedPotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient) { this(type, duration, amplifier, ambient, true); } public WrappedPotionEffect(PotionEffectType type, int duration, int amplifier) { this(type, duration, amplifier, true); } public WrappedPotionEffect(Map<String, Object> map) { this(getEffectType(map), getInt(map, "duration"), getInt(map, "amplifier"), getBool(map, "ambient", false), getBool(map, "has-particles", true)); } private static PotionEffectType getEffectType(Map<?, ?> map) { int type = getInt(map, "effect"); @SuppressWarnings("deprecation") PotionEffectType effect = PotionEffectType.getById(type); if(effect != null) { return effect; } else { throw new NoSuchElementException(map + " does not contain " + "effect"); } } private static int getInt(Map<?, ?> map, Object key) { Object num = map.get(key); if(num instanceof Integer) { return (Integer) num; } else { throw new NoSuchElementException(map + " does not contain " + key); } } private static boolean getBool(Map<?, ?> map, Object key, boolean def) { Object bool = map.get(key); return bool instanceof Boolean? (Boolean) bool :def; } @Override public Map<String, Object> serialize() { //noinspection deprecation return ImmutableMap.of("effect", this.type.getId(), "duration", this.duration, "amplifier", this.amplifier, "ambient", this.ambient, "has-particles", this.particles); } @Override public boolean apply(LivingEntity entity) { return entity.addPotionEffect(this); } @Override public boolean equals(Object obj) { if(this == obj) { return true; } else if(!(obj instanceof org.bukkit.potion.PotionEffect)) { return false; } else { org.bukkit.potion.PotionEffect that = (org.bukkit.potion.PotionEffect)obj; return this.type.equals(that.getType()) && this.ambient == that.isAmbient() && this.amplifier == that.getAmplifier() && this.duration == that.getDuration() && this.particles == that.hasParticles(); } } @Override public int getAmplifier() { return this.amplifier; } @Override public int getDuration() { return this.duration; } @Override public PotionEffectType getType() { return this.type; } @Override public boolean isAmbient() { return this.ambient; } @Override public boolean hasParticles() { return this.particles; } // Do not @Override // 1.8 doesn't have this method! public Color getColor() { return this.color; } public void setAmplifier(int amplifier) { this.amplifier = amplifier; } public void setDuration(int duration) { this.duration = duration; } public void setType(PotionEffectType type) { this.type = type; } public void setAmbient(boolean ambient) { this.ambient = ambient; } public void setParticles(boolean particles) { this.particles = particles; } public void setColor(Color color) { this.color = color; } @Override public int hashCode() { byte hash = 1; int hash1 = hash * 31 + this.type.hashCode(); hash1 = hash1 * 31 + this.amplifier; hash1 = hash1 * 31 + this.duration; hash1 ^= 572662306 >> (this.ambient?1:-1); hash1 ^= 572662306 >> (this.particles?1:-1); return hash1; } @Override public String toString() { return this.type.getName() + (this.ambient?":(":":") + this.duration + "t-x" + this.amplifier + (this.ambient?")":""); } }
5,463
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitFactory.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/KitFactory.java
package me.patothebest.gamecore.kit; import org.bukkit.inventory.PlayerInventory; import java.sql.ResultSet; public interface KitFactory { Kit createKit(ResultSet resultSet); Kit createKit(String kitName, PlayerInventory playerInventory); }
254
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/KitManager.java
package me.patothebest.gamecore.kit; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.name.Named; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.modules.ReloadPriority; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.storage.Storage; import me.patothebest.gamecore.arena.AbstractGameTeam; import me.patothebest.gamecore.logger.InjectLogger; import me.patothebest.gamecore.player.IPlayer; import me.patothebest.gamecore.player.PlayerManager; import me.patothebest.gamecore.util.Priority; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.PlayerInventory; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.stream.Collectors; @Singleton @ReloadPriority(priority = Priority.HIGHEST) @ModuleName("Kit Manager") public class KitManager implements ActivableModule, ReloadableModule { private final CorePlugin plugin; private final PlayerManager playerManager; private final Map<String, Kit> kits; private final Provider<Storage> storageProvider; @InjectLogger private Logger logger; // TODO: multiple default kits with permission @Inject @Named("DefaultKit") private Kit defaultKit; @Inject private KitManager(CorePlugin plugin, PlayerManager playerManager, Provider<Storage> storageProvider) { this.plugin = plugin; this.playerManager = playerManager; this.storageProvider = storageProvider; this.kits = new HashMap<>(); } @Override public void onPostEnable() { logger.config(ChatColor.YELLOW + "Loading kits..."); storageProvider.get().loadKits(kits); logger.info("Loaded " + kits.size() + " kits!"); } public void applyKit(Player player, AbstractGameTeam team) { IPlayer corePlayer = playerManager.getPlayer(player); if(corePlayer.getKit() != null) { corePlayer.getKit().applyKit(corePlayer); } else { defaultKit.applyKit(corePlayer); } // Don't paint armor for solo arenas if(corePlayer.getCurrentArena().getTeams().size() > 1) { if (player.getInventory().getHelmet() != null && player.getInventory().getHelmet().getType() == Material.LEATHER_HELMET.parseMaterial()) { player.getInventory().setHelmet(new ItemStackBuilder(player.getInventory().getHelmet()).color(team.getColor().getColor())); } if (player.getInventory().getChestplate() != null && player.getInventory().getChestplate().getType() == Material.LEATHER_CHESTPLATE.parseMaterial()) { player.getInventory().setChestplate(new ItemStackBuilder(player.getInventory().getChestplate()).color(team.getColor().getColor())); } if (player.getInventory().getLeggings() != null && player.getInventory().getLeggings().getType() == Material.LEATHER_LEGGINGS.parseMaterial()) { player.getInventory().setLeggings(new ItemStackBuilder(player.getInventory().getLeggings()).color(team.getColor().getColor())); } if (player.getInventory().getBoots() != null && player.getInventory().getBoots().getType() == Material.LEATHER_BOOTS.parseMaterial()) { player.getInventory().setBoots(new ItemStackBuilder(player.getInventory().getBoots()).color(team.getColor().getColor())); } } } public void applyPotionEffects(Player player) { if(playerManager.getPlayer(player) == null) { return; } defaultKit.applyPotionEffects(player); if(playerManager.getPlayer(player).getKit() != null) { playerManager.getPlayer(player).getKit().applyPotionEffects(player); } } @Override public void onReload() { kits.clear(); onPostEnable(); } @Override public String getReloadName() { return "kits"; } public boolean kitExists(String name) { return kits.containsKey(name); } public Kit getDefaultKit() { return defaultKit; } public Map<String, Kit> getKits() { return kits; } public List<Kit> getEnabledKits() { return kits.values().stream().filter(Kit::isEnabled).collect(Collectors.toList()); } public Kit createKit(String name, PlayerInventory items) { Kit kit = storageProvider.get().createKit(name, items); kits.put(name, kit); return kit; } }
4,833
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Kit.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/Kit.java
package me.patothebest.gamecore.kit; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.permission.GroupPermissible; import me.patothebest.gamecore.permission.PermissionGroup; import me.patothebest.gamecore.permission.PermissionGroupManager; import me.patothebest.gamecore.player.IPlayer; import me.patothebest.gamecore.storage.Storage; import me.patothebest.gamecore.util.NameableObject; import me.patothebest.gamecore.util.ThrowableConsumer; import me.patothebest.gamecore.util.ThrowableRunnable; import me.patothebest.gamecore.util.Utils; import org.bukkit.ChatColor; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("unchecked") public class Kit implements ConfigurationSerializable, GroupPermissible, NameableObject { private final CorePlugin plugin; private final List<WrappedPotionEffect> potionEffects; private final List<String> description; private KitFile kitFile; private Provider<Storage> storageProvider; private String kitName; private PermissionGroup permissionGroup; private ItemStack[] armorItems; private ItemStack[] inventoryItems; private ItemStack displayItem; private boolean oneTimeKit; private boolean enabled; private double cost; private final static int[] DEFAULT_LAYOUT = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 }; public Kit(CorePlugin plugin, PermissionGroupManager permissionGroupManager, String kitName, ItemStack[] armorItems, ItemStack[] inventoryItems) { this.plugin = plugin; this.kitName = kitName; this.armorItems = armorItems; this.inventoryItems = inventoryItems; this.description = new ArrayList<>(); this.potionEffects = new ArrayList<>(); this.displayItem = inventoryItems[0] == null ? new ItemStackBuilder().material(Material.DIRT) : inventoryItems[0]; this.enabled = false; this.permissionGroup = permissionGroupManager.getDefaultPermissionGroup(); this.oneTimeKit = false; this.cost = 0; this.kitFile = new KitFile(this); kitFile.save(); } public Kit(CorePlugin plugin, PermissionGroupManager permissionGroupManager, String kitName) { this.plugin = plugin; this.kitName = kitName; this.kitFile = new KitFile(this); Map<String, Object> data = kitFile.getConfigurationSection("data").getValues(true); this.description = (List<String>) data.get("description"); this.displayItem = Utils.itemStackFromString((String) data.get("display-item")); this.inventoryItems = (((ArrayList<ItemStack>) data.get("items")).toArray(new ItemStack[((ArrayList<ItemStack>) data.get("items")).size()])); this.armorItems = (((ArrayList<ItemStack>) data.get("armor")).toArray(new ItemStack[((ArrayList<ItemStack>) data.get("armor")).size()])); this.potionEffects = (List<WrappedPotionEffect>) data.get("potion-effects"); this.oneTimeKit = (boolean) data.get("one-time-kit"); this.cost = (double) data.get("cost"); this.enabled = (boolean) data.get("enabled"); if(data.get("permission-group") != null) { permissionGroup = permissionGroupManager.getOrCreatePermissionGroup((String) data.get("permission-group")); } else { permissionGroup = permissionGroupManager.getDefaultPermissionGroup(); } } @AssistedInject private Kit(CorePlugin plugin, PermissionGroupManager permissionGroupManager, Provider<Storage> storageProvider, @Assisted ResultSet resultSet) { this.plugin = plugin; this.storageProvider = storageProvider; this.description = new ArrayList<>(); this.potionEffects = new ArrayList<>(); tryLoad(() -> { this.kitName = resultSet.getString("name"); this.permissionGroup = permissionGroupManager.getOrCreatePermissionGroup(resultSet.getString("permission_group")); this.oneTimeKit = resultSet.getInt("one_time_kit") == 1; this.cost = resultSet.getDouble("price"); this.enabled = resultSet.getInt("enabled") == 1; }, e -> { System.out.println("Error loading kit " + kitName); e.printStackTrace(); }); tryLoad(() -> { this.description.addAll(Arrays.asList(resultSet.getString("description").split("%delimiter%"))); }, (e) -> { System.err.println("Could not load kit " + kitName + " description"); e.printStackTrace(); }); tryLoad(() -> { this.displayItem = Utils.itemStackFromString(resultSet.getString("display_item")); }, (e) -> { String display_item = resultSet.getString("display_item"); System.err.println("Could not load kit " + kitName + " display_item." + display_item + " not found."); e.printStackTrace(); }); tryLoad(() -> { this.inventoryItems = Utils.itemStackArrayFromBase64(resultSet.getString("items")); }, (e) -> { System.err.println("Could not load kit " + kitName + " inventory items."); e.printStackTrace(); }); tryLoad(() -> { this.armorItems = Utils.itemStackArrayFromBase64(resultSet.getString("armor")); }, (e) -> { System.err.println("Could not load kit " + kitName + " armor items."); e.printStackTrace(); }); tryLoad(() -> { this.potionEffects.addAll(Arrays.asList(Utils.potionEffectsFromBase64(resultSet.getString("potion_effects")))); }, (e) -> { System.err.println("Could not load kit " + kitName + " potion effects."); e.printStackTrace(); }); if (displayItem != null) { this.displayItem.setItemMeta(null); } } private void tryLoad(ThrowableRunnable<Exception> runnable, ThrowableConsumer<Exception> defaultRunnable) { try { runnable.run(); } catch (Exception e) { try { defaultRunnable.acceptThrows(e); } catch (Exception ex) { System.out.println("Exception handing exception"); ex.printStackTrace(); } } } @AssistedInject private Kit(CorePlugin plugin, PermissionGroupManager permissionGroupManager, Provider<Storage> storageProvider, @Assisted String kitName, @Assisted PlayerInventory playerInventory) { this.plugin = plugin; this.kitName = kitName; this.storageProvider = storageProvider; this.armorItems = playerInventory.getArmorContents(); this.inventoryItems = playerInventory.getContents(); this.description = new ArrayList<>(); this.potionEffects = new ArrayList<>(); this.displayItem = inventoryItems[0] == null ? new ItemStackBuilder().material(Material.DIRT) : inventoryItems[0]; this.enabled = false; this.permissionGroup = permissionGroupManager.getDefaultPermissionGroup(); this.oneTimeKit = false; this.cost = 0; this.displayItem.setItemMeta(null); } public void applyKit(IPlayer player) { ItemStack[] inventoryItemsCopy = new ItemStack[inventoryItems.length]; ItemStack[] armorItemsCopy = armorItems.clone(); int[] layout = player.getLayout(this) == null ? DEFAULT_LAYOUT : player.getLayout(this).getRemap(); for (int i = 0; i < inventoryItems.length; ++i) { int slot = i >= 36 ? i : layout[i]; ItemStack item = inventoryItems[slot] != null ? inventoryItems[slot].clone() : null; if (item != null && item.getType() != org.bukkit.Material.AIR) { if (i >= 36) { inventoryItemsCopy[i] = new ItemStackBuilder(item).lore(ChatColor.YELLOW + "Kit " + kitName); } else { inventoryItemsCopy[i] = new ItemStackBuilder(item).lore(ChatColor.YELLOW + "Kit " + kitName); } } } for (int i = 0; i < armorItemsCopy.length; ++i) { final ItemStack item = armorItemsCopy[i]; if (item != null && item.getType() != org.bukkit.Material.AIR) { armorItemsCopy[i] = new ItemStackBuilder(item).lore(ChatColor.YELLOW + "Kit " + kitName); } } player.getPlayerInventory().clearPlayer(); for (int i = 0; i < player.getPlayer().getInventory().getContents().length && i < inventoryItemsCopy.length; i++) { player.getPlayer().getInventory().setItem(i, inventoryItemsCopy[i]); } player.getPlayer().getInventory().setArmorContents(armorItemsCopy); } public void applyPotionEffects(Player player) { potionEffects.forEach(player::addPotionEffect); } public void delete() { if(kitFile != null) { kitFile.delete(); } else if(storageProvider != null) { storageProvider.get().deleteKit(this); } } public void save() { if(kitFile != null) { kitFile.save(); } else if(storageProvider != null) { storageProvider.get().saveKit(this); } } public void saveToFile() { if(kitFile == null) { this.kitFile = new KitFile(this); } kitFile.save(); } @Override public Map<String, Object> serialize() { Map<String, Object> result = new HashMap<>(); result.put("name", kitName); result.put("description", description); result.put("display-item", Utils.itemStackToString(displayItem)); result.put("items", inventoryItems); result.put("armor", armorItems); result.put("potion-effects", potionEffects.toArray(new WrappedPotionEffect[potionEffects.size()])); result.put("permission-group", permissionGroup.getName()); result.put("one-time-kit", oneTimeKit); result.put("enabled", enabled); result.put("cost", cost); return result; } public String getKitName() { return kitName; } @Override public String getName() { return kitName; } public void setKitName(String kitName) { this.kitName = kitName; } public List<String> getDescription() { return description; } public ItemStack[] getArmorItems() { return armorItems; } public void setArmorItems(ItemStack[] armorItems) { this.armorItems = armorItems; } public ItemStack[] getInventoryItems() { return inventoryItems; } public void setInventoryItems(ItemStack[] inventoryItems) { this.inventoryItems = inventoryItems; } public ItemStack getDisplayItem() { return displayItem; } public ItemStackBuilder finalDisplayItem(IPlayer player, boolean extraLore) { return finalDisplayItem(player, extraLore, false); } public ItemStackBuilder finalDisplayItem(IPlayer player, boolean extraLore, boolean showChooseDefaultKit) { return finalDisplayItem(player, extraLore, showChooseDefaultKit, true); } public ItemStackBuilder finalDisplayItem(IPlayer player, boolean extraLore, boolean showChooseDefaultKit, boolean addClickMessages) { if (displayItem == null) { return new ItemStackBuilder(Material.REDSTONE_BLOCK).name(ChatColor.RED + "ERROR KIT" + kitName); } ItemStackBuilder itemStackBuilder = new ItemStackBuilder(displayItem).name(ChatColor.GREEN + kitName); if(extraLore) { description.forEach(s -> itemStackBuilder.addLore(ChatColor.GRAY + s)); itemStackBuilder.blankLine(); itemStackBuilder.addLore(CoreLang.GUI_SHOP_PRICE.replace(player, (isFree() ? CoreLang.GUI_SHOP_FREE.getMessage(player) : cost + ""))); if (permissionGroup.hasPermission(player)) { if (player.getKit() == this) { if (!isFree() && oneTimeKit && !player.isPermanentKit(this)) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_KIT_USES.replace(player, player.getKitUses().getOrDefault(this, 0))); } itemStackBuilder.glowing(true); if (addClickMessages) { itemStackBuilder.blankLine(); if (!isFree() && oneTimeKit && !player.isPermanentKit(this)) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_RIGHT_CLICK_OPTIONS.getMessage(player)); } itemStackBuilder.addLore(CoreLang.GUI_SHOP_SELECTED.getMessage(player)); } } else if (isFree()) { if (addClickMessages) { itemStackBuilder.blankLine(); if(showChooseDefaultKit) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_DEFAULT.getMessage(player)); } else { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_SELECT.getMessage(player)); } } } else if (oneTimeKit && !player.isPermanentKit(this)) { if (player.canUseKit(this)) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_KIT_USES.replace(player, player.getKitUses().get(this))); if (addClickMessages) { itemStackBuilder.blankLine(); itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_RIGHT_CLICK_OPTIONS.getMessage(player)); if (showChooseDefaultKit) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_LEFT_CLICK.getMessage(player)); } else { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_LEFT_CLICK_SELECT.getMessage(player)); } } } else { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_KIT_USES.replace(player, 0)); if (addClickMessages) { itemStackBuilder.blankLine(); itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_BUY.getMessage(player)); } } } else if (addClickMessages){ itemStackBuilder.blankLine(); if (player.canUseKit(this)) { if(showChooseDefaultKit) { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_DEFAULT.getMessage(player)); } else { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_SELECT.getMessage(player)); } } else { itemStackBuilder.addLore(CoreLang.GUI_KIT_SHOP_CLICK_BUY_PERMANENT.replace(player)); } } } else { itemStackBuilder.addLore(CoreLang.GUI_SHOP_NO_PERMISSION.replace(player, permissionGroup.getName())); } } return itemStackBuilder; } public void setDisplayItem(ItemStack displayItem) { this.displayItem = displayItem; this.displayItem.setItemMeta(null); } public boolean isOneTimeKit() { return oneTimeKit; } public void setOneTimeKit(boolean oneTimeKit) { this.oneTimeKit = oneTimeKit; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isFree() { return cost < 1; } public List<WrappedPotionEffect> getPotionEffects() { return potionEffects; } @Override public PermissionGroup getPermissionGroup() { return permissionGroup; } @Override public void setPermissionGroup(PermissionGroup permissionGroup) { this.permissionGroup = permissionGroup; } @Override public String toString() { return "Kit{" + "kitFile=" + kitFile + ", potionEffects=" + potionEffects + ", description=" + description + ", kitName='" + kitName + '\'' + ", armorItems=" + Arrays.toString(armorItems) + ", inventoryItems=" + Arrays.toString(inventoryItems) + ", displayItem=" + displayItem + ", oneTimeKit=" + oneTimeKit + ", enabled=" + enabled + ", cost=" + cost + '}'; } }
17,454
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitLayout.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/KitLayout.java
package me.patothebest.gamecore.kit; import me.patothebest.gamecore.file.ParserException; public class KitLayout { private int[] remap = new int[36]; public KitLayout() {} public KitLayout(int[] remap) { this.remap = remap; } public KitLayout(String layout) { parseLayout(layout); } public void parseLayout(String input) throws ParserException { String[] split = input.split(","); for (int i = 0; i < split.length && i < remap.length; i++) { try { remap[i] = Integer.parseInt(split[i]); } catch (NumberFormatException e) { throw new ParserException(split[i] + " is not a number!"); } } } public String toString() { StringBuilder stb = new StringBuilder(); stb.append(remap[0]); for (int i = 1; i < remap.length; i++) { stb.append(",").append(remap[i]); } return stb.toString(); } public int[] getRemap() { return remap; } }
1,049
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitMySQLEntity.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/entities/KitMySQLEntity.java
package me.patothebest.gamecore.kit.entities; import me.patothebest.gamecore.PluginConfig; import me.patothebest.gamecore.file.ParserException; import me.patothebest.gamecore.kit.KitLayout; import me.patothebest.gamecore.storage.mysql.MySQLEntity; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.kit.KitManager; import me.patothebest.gamecore.player.CorePlayer; import me.patothebest.gamecore.player.modifiers.KitModifier; import me.patothebest.gamecore.player.modifiers.PlayerModifier; import me.patothebest.gamecore.util.ThrowableBiConsumer; import javax.inject.Inject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class KitMySQLEntity implements MySQLEntity { private final KitManager kitManager; @Inject private KitMySQLEntity(KitManager kitManager) { this.kitManager = kitManager; } @Override public void loadPlayer(CorePlayer player, Connection connection) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(Queries.SELECT_KIT); preparedStatement.setInt(1, player.getPlayerId()); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String kitName = resultSet.getString("kit_name"); Kit kit = kitManager.getKits().get(kitName); int kitUses = resultSet.getInt("uses"); if(kit != null) { player.addKitUses(kit, kitUses); } } resultSet.close(); preparedStatement.close(); PreparedStatement selectDefaultKit = connection.prepareStatement(Queries.SELECT_DEFAULT_KIT); selectDefaultKit.setString(1, PluginConfig.PLUGIN_NAME); selectDefaultKit.setInt(2, player.getPlayerId()); ResultSet selectDefaultKitResultSet = selectDefaultKit.executeQuery(); if(selectDefaultKitResultSet.next()) { player.setKit(kitManager.getKits().get(selectDefaultKitResultSet.getString("kit_name"))); } else { PreparedStatement insertRecord = connection.prepareStatement(Queries.INSERT_DEFAULT_KIT); insertRecord.setString(1, PluginConfig.PLUGIN_NAME); insertRecord.setInt(2, player.getPlayerId()); insertRecord.setString(3, "default"); insertRecord.executeUpdate(); } selectDefaultKitResultSet.close(); selectDefaultKit.close(); PreparedStatement selectLayout = connection.prepareCall(Queries.SELECT_LAYOUT); selectLayout.setInt(1, player.getPlayerId()); ResultSet layouts = selectLayout.executeQuery(); while(layouts.next()) { String kitName = layouts.getString("kit_name"); Kit kit = kitManager.getKits().get(kitName); String kitLayout = layouts.getString("layout"); KitLayout layout = new KitLayout(); try { layout.parseLayout(kitLayout); } catch (ParserException e) { Utils.printError("Could not load layout!", "PlayerID: " + player.getPlayerId(), "Player: " + player.getName(), "Kit: " + kitName, "Layout: " + layout, e); } if(kit != null) { player.modifyKitLayout(kit, layout); } } layouts.close(); selectLayout.close(); } @Override public void savePlayer(CorePlayer player, Connection connection) throws SQLException { PreparedStatement deleteAll = connection.prepareStatement(Queries.DELETE_ALL); deleteAll.setInt(1, player.getPlayerId()); deleteAll.executeUpdate(); if(!player.getKitUses().isEmpty()) { PreparedStatement preparedStatement = connection.prepareStatement(Queries.INSERT_KIT); player.getKitUses().forEach((ThrowableBiConsumer<Kit, Integer>) (kit, uses) -> { preparedStatement.setInt(1, player.getPlayerId()); preparedStatement.setString(2, kit.getKitName()); preparedStatement.setInt(3, uses); preparedStatement.executeUpdate(); preparedStatement.addBatch(); }); preparedStatement.executeBatch(); } } @Override public void updatePlayer(CorePlayer player, Connection connection, PlayerModifier updatedType, Object... args) throws SQLException { if(!(updatedType instanceof KitModifier)) { return; } Kit kit = (Kit) args[0]; switch (((KitModifier)updatedType)) { case ADD_KIT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.INSERT_KIT); preparedStatement.setInt(1, player.getPlayerId()); preparedStatement.setString(2, kit.getKitName()); preparedStatement.setInt(3, (Integer) args[1]); preparedStatement.executeUpdate(); break; } case REMOVE_KIT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.DELETE_KIT); preparedStatement.setInt(1, player.getPlayerId()); preparedStatement.setString(2, kit.getKitName()); preparedStatement.executeUpdate(); break; } case MODIFY_KIT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.UPDATE_KIT); preparedStatement.setInt(1, (Integer) args[1]); preparedStatement.setInt(2, player.getPlayerId()); preparedStatement.setString(3, kit.getKitName()); preparedStatement.executeUpdate(); break; } case SET_LAYOUT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.INSERT_LAYOUT); preparedStatement.setInt(1, player.getPlayerId()); preparedStatement.setString(2, kit.getKitName()); preparedStatement.setString(3, args[1].toString()); preparedStatement.executeUpdate(); break; } case MODIFY_LAYOUT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.UPDATE_LAYOUT); preparedStatement.setString(1, args[1].toString()); preparedStatement.setInt(2, player.getPlayerId()); preparedStatement.setString(3, kit.getKitName()); preparedStatement.executeUpdate(); break; } case SET_DEFAULT: { PreparedStatement preparedStatement = connection.prepareStatement(Queries.UPDATE_DEFAULT_KIT); preparedStatement.setString(1, kit.getKitName()); preparedStatement.setString(2, PluginConfig.PLUGIN_NAME); preparedStatement.setInt(3, player.getPlayerId()); preparedStatement.executeUpdate(); break; } } } @Override public String[] getCreateTableStatements() { return new String[] {Queries.CREATE_TABLE, Queries.CREATE_DEFAULT_KIT_TABLEE, Queries.CREATE_KITS_LAYOUT_TABLE}; } }
7,399
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitFlatFileEntity.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/entities/KitFlatFileEntity.java
package me.patothebest.gamecore.kit.entities; import me.patothebest.gamecore.kit.KitLayout; import me.patothebest.gamecore.storage.StorageException; import me.patothebest.gamecore.storage.flatfile.FlatFileEntity; import me.patothebest.gamecore.storage.flatfile.PlayerProfileFile; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.kit.KitManager; import me.patothebest.gamecore.player.CorePlayer; import javax.inject.Inject; import java.util.Map; import java.util.stream.Collectors; public class KitFlatFileEntity implements FlatFileEntity { private final KitManager kitManager; @Inject private KitFlatFileEntity(KitManager kitManager) { this.kitManager = kitManager; } @Override public void loadPlayer(CorePlayer player, PlayerProfileFile playerProfileFile) throws StorageException { if(playerProfileFile.isSet("kit-uses")) { playerProfileFile.getConfigurationSection("kit-uses").getValues(true).forEach((kitName, uses) -> { Kit kit = kitManager.getKits().get(kitName); player.addKitUses(kit, (Integer) uses); }); } if(playerProfileFile.isSet("kit-layouts")) { playerProfileFile.getConfigurationSection("kit-layouts").getValues(true).forEach((kitName, layout) -> { Kit kit = kitManager.getKits().get(kitName); player.modifyKitLayout(kit, new KitLayout((String) layout)); }); } } @Override public void savePlayer(CorePlayer player, PlayerProfileFile playerProfileFile) throws StorageException { playerProfileFile.set("kit-uses", player.getKitUses().entrySet().stream().collect(Collectors.toMap(o -> o.getKey().getKitName(), Map.Entry::getValue))); playerProfileFile.set("kit-layouts", player.getKitLayouts().entrySet().stream().collect(Collectors.toMap(o -> o.getKey().getKitName(), Map.Entry::getValue))); } }
1,943
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Queries.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/entities/Queries.java
package me.patothebest.gamecore.kit.entities; import me.patothebest.gamecore.PluginConfig; class Queries { private static final String TABLE_NAME_KITS = PluginConfig.SQL_PREFIX + "_kits"; private static final String TABLE_NAME_LAYOUT = PluginConfig.SQL_PREFIX + "_kits_layouts"; static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `" + TABLE_NAME_KITS + "` (\n" + " `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `player_id` int(11) NOT NULL,\n" + " `kit_name` varchar(36) NOT NULL,\n" + " `uses` int(11) NOT NULL,\n" + " PRIMARY KEY (`entry_id`),\n" + " UNIQUE KEY `entry_id` (`entry_id`)\n" + ") ENGINE=InnoDB DEFAULT CHARSET=latin1;"; static final String CREATE_DEFAULT_KIT_TABLEE = "CREATE TABLE IF NOT EXISTS `default_kits` (\n" + " `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `minigame` varchar(36) NOT NULL,\n" + " `player_id` int(11) NOT NULL,\n" + " `kit_name` varchar(36) NOT NULL,\n" + " PRIMARY KEY (`entry_id`),\n" + " UNIQUE KEY `entry_id` (`entry_id`)\n" + ") ENGINE=MyISAM DEFAULT CHARSET=latin1;\n"; static final String CREATE_KITS_LAYOUT_TABLE = "CREATE TABLE IF NOT EXISTS `" + TABLE_NAME_LAYOUT + "` (\n" + " `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `player_id` int(11) NOT NULL,\n" + " `kit_name` varchar(36) NOT NULL,\n" + " `layout` varchar(100) NOT NULL,\n" + " PRIMARY KEY (`entry_id`),\n" + " UNIQUE KEY `entry_id` (`entry_id`)\n" + ") ENGINE=InnoDB DEFAULT CHARSET=latin1;"; static final String INSERT_DEFAULT_KIT = "INSERT INTO default_kits VALUES(NULL, ?, ?, ?)"; static final String UPDATE_DEFAULT_KIT = "UPDATE default_kits SET kit_name=? WHERE minigame=? AND player_id=?"; static final String SELECT_DEFAULT_KIT = "SELECT kit_name FROM default_kits WHERE minigame=? AND player_id=?"; static final String INSERT_KIT = "INSERT INTO " + TABLE_NAME_KITS + " VALUES(NULL, ?, ?, ?);"; static final String UPDATE_KIT = "UPDATE " + TABLE_NAME_KITS + " SET uses=? WHERE player_id=? AND kit_name=?"; static final String DELETE_KIT = "DELETE FROM " + TABLE_NAME_KITS + " WHERE player_id=? AND kit_name=?"; static final String SELECT_KIT = "SELECT kit_name,uses FROM " + TABLE_NAME_KITS + " WHERE player_id=?"; static final String INSERT_LAYOUT = "INSERT INTO " + TABLE_NAME_LAYOUT + " VALUES(NULL, ?, ?, ?);"; static final String UPDATE_LAYOUT = "UPDATE " + TABLE_NAME_LAYOUT + " SET layout=? WHERE player_id=? AND kit_name=?"; static final String DELETE_LAYOUT = "DELETE FROM " + TABLE_NAME_LAYOUT + " WHERE player_id=? AND kit_name=?"; static final String SELECT_LAYOUT = "SELECT kit_name,layout FROM " + TABLE_NAME_LAYOUT + " WHERE player_id=?"; static final String DELETE_ALL = "DELETE FROM " + TABLE_NAME_KITS + " WHERE player_id=?"; }
3,247
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitDefault.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/kit/defaults/KitDefault.java
package me.patothebest.gamecore.kit.defaults; import com.google.inject.Inject; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.permission.PermissionGroupManager; import me.patothebest.gamecore.kit.Kit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class KitDefault extends Kit { @Inject private KitDefault(CorePlugin plugin, PermissionGroupManager permissionGroupManager) { super(plugin, permissionGroupManager, "Default", getDefaultArmor(), getDefaultItems()); } private static ItemStack[] getDefaultArmor() { final ItemStack helmet = new ItemStackBuilder(Material.LEATHER_HELMET); final ItemStack chestplate = new ItemStackBuilder(Material.LEATHER_CHESTPLATE); final ItemStack legs = new ItemStackBuilder(Material.LEATHER_LEGGINGS); final ItemStack boots = new ItemStackBuilder(Material.LEATHER_BOOTS); return new ItemStack[] { boots, legs, chestplate, helmet }; } private static ItemStack[] getDefaultItems() { return new ItemStack[] { new ItemStackBuilder(Material.BAKED_POTATO).amount(8) }; } public void applyKit(Player player) { player.getInventory().setContents(getInventoryItems()); player.getInventory().setArmorContents(getArmorItems()); } }
1,432
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
TopEntry.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/TopEntry.java
package me.patothebest.gamecore.leaderboards; public class TopEntry { private final String name; private final Integer amount; public TopEntry(String name, Integer amount) { this.name = name; this.amount = amount; } public String getName() { return name; } public Integer getAmount() { return amount; } }
374
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderboardCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/LeaderboardCommand.java
package me.patothebest.gamecore.leaderboards; import me.patothebest.gamecore.chat.CommandPagination; import me.patothebest.gamecore.command.BaseCommand; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.command.NestedCommand; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.permission.Permission; import org.bukkit.command.CommandSender; import javax.inject.Inject; @ChildOf(BaseCommand.class) public class LeaderboardCommand implements RegisteredCommandModule { private final CommandsManager<CommandSender> commandsManager; @Inject private LeaderboardCommand(CommandsManager<CommandSender> commandsManager) { this.commandsManager = commandsManager; } @Command( aliases = "leaderboard", langDescription = @LangDescription( langClass = CoreLang.class, element = "LEADERBOARD_COMMAND_DESC" ) ) @CommandPermissions(permission = Permission.SETUP) @NestedCommand public void leaderboards(CommandContext args, CommandSender sender) throws CommandException { new CommandPagination(commandsManager, args).display(sender); } }
1,608
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderboardModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/LeaderboardModule.java
package me.patothebest.gamecore.leaderboards; import com.google.inject.assistedinject.FactoryModuleBuilder; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.injector.AbstractBukkitModule; import me.patothebest.gamecore.leaderboards.signs.AttachmentCommand; import me.patothebest.gamecore.leaderboards.holograms.HolographicCommand; import me.patothebest.gamecore.leaderboards.holograms.HolographicFactory; import me.patothebest.gamecore.leaderboards.holograms.LeaderHologramManager; import me.patothebest.gamecore.leaderboards.signs.LeaderSignListener; import me.patothebest.gamecore.leaderboards.signs.LeaderSignsCommand; import me.patothebest.gamecore.leaderboards.signs.LeaderSignsManager; public class LeaderboardModule extends AbstractBukkitModule<CorePlugin> { public LeaderboardModule(CorePlugin plugin) { super(plugin); } @Override protected void configure() { registerModule(LeaderboardManager.class); registerModule(LeaderboardCommand.class); registerModule(LeaderSignsManager.class); registerModule(LeaderSignListener.class); registerModule(LeaderSignsCommand.Parent.class); registerModule(LeaderSignsCommand.class); registerModule(AttachmentCommand.Parent.class); registerModule(HolographicCommand.Parent.class); registerModule(LeaderHologramManager.class); install(new FactoryModuleBuilder().build(HolographicFactory.class)); } }
1,481
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderboardQueries.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/LeaderboardQueries.java
package me.patothebest.gamecore.leaderboards; import me.patothebest.gamecore.PluginConfig; public class LeaderboardQueries { private final static String TABLE_NAME = PluginConfig.SQL_PREFIX + "_stats"; private final static String ORDER = " ORDER BY stat " + "DESC LIMIT 10"; public final static String SELECT_WEEKLY = "SELECT players.name, stat " + "FROM " + TABLE_NAME + " " + "INNER JOIN players " + "ON players.id = " + TABLE_NAME + ".player_id " + "WHERE stat_name=? AND week=? AND year=? " + ORDER; public final static String SELECT_MONTHLY = "SELECT players.name, (SUM(" + TABLE_NAME + ".stat)) AS stat " + "FROM " + TABLE_NAME + " " + "INNER JOIN players " + "ON players.id = " + TABLE_NAME + ".player_id " + "WHERE stat_name=? AND month=? AND year=? " + "GROUP BY name " + ORDER; public final static String SELECT_ALL_TIME = "SELECT players.name, " + TABLE_NAME + ".stat " + "FROM " + TABLE_NAME + " " + "INNER JOIN players " + "ON players.id = " + TABLE_NAME + ".player_id " + "WHERE stat_name=? AND week=0 AND month=0 AND year=0" + ORDER; }
1,743
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderboardManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/LeaderboardManager.java
package me.patothebest.gamecore.leaderboards; import com.google.inject.Inject; import com.google.inject.Singleton; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.event.EventRegistry; import me.patothebest.gamecore.event.other.LeaderboardUpdateEvent; import me.patothebest.gamecore.file.CoreConfig; import me.patothebest.gamecore.logger.InjectLogger; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.scheduler.PluginScheduler; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.storage.StorageManager; import me.patothebest.gamecore.storage.mysql.MySQLStorage; import org.bukkit.scheduler.BukkitTask; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.logging.Logger; @Singleton @ModuleName("Leaderboard Manager") public class LeaderboardManager implements ActivableModule, Runnable, ReloadableModule { private final Map<Class<? extends Statistic>, Map<StatPeriod, LinkedList<TopEntry>>> top10Map = new HashMap<>(); private final CoreConfig coreConfig; private final EventRegistry eventRegistry; private final StorageManager storageManager; private final PluginScheduler pluginScheduler; private final StatsManager statsManager; private BukkitTask currentTask; @InjectLogger private Logger logger; private boolean hasLoadedAll; @Inject private LeaderboardManager(CoreConfig coreConfig, EventRegistry eventRegistry, StorageManager storageManager, PluginScheduler pluginScheduler, StatsManager statsManager) { this.coreConfig = coreConfig; this.eventRegistry = eventRegistry; this.storageManager = storageManager; this.pluginScheduler = pluginScheduler; this.statsManager = statsManager; } @Override public void onPreEnable() { for (Statistic statistic : statsManager.getStatistics()) { Map<StatPeriod, LinkedList<TopEntry>> topEntryMap = new HashMap<>(); for (StatPeriod value : StatPeriod.values()) { topEntryMap.put(value, new LinkedList<>()); } top10Map.put(statistic.getClass(), topEntryMap); } } @Override public void onPostEnable() { if (!storageManager.arePlayersOnDatabase()) { return; } if(!coreConfig.getBoolean("leaderboard.enabled")) { return; } hasLoadedAll = false; int interval = 20 * 60 * coreConfig.getInt("leaderboard.interval"); currentTask = pluginScheduler.runTaskTimerAsynchronously(this, 0L, interval); // run every x minutes } @Override public void run() { MySQLStorage mySQLStorage = storageManager.getMySQLStorage(); logger.fine("Getting all stats..."); mySQLStorage.getConnectionHandler().executeSQLQuery(connection -> { for (Statistic statistic : statsManager.getStatistics()) { logger.finer("Getting stat " + statistic.getStatName()); if(statistic.hasWeeklyAndMonthlyStats()) { logger.finest("Getting weekly stat " + statistic.getStatName()); LinkedList<TopEntry> top10Weekly = getTop10Map().get(statistic.getClass()).get(StatPeriod.WEEK); try { LinkedList<TopEntry> top10Weekly1 = statistic.getTop10Weekly(connection); top10Weekly.clear(); top10Weekly.addAll(top10Weekly1); } catch (Throwable e) { if (connection.isClosed()) { logger.warning("Aborting leaderboard stat collection because connection was closed. (Reload?)"); return; } logger.severe("Could not get weekly stats " + statistic.getStatName() + "!"); e.printStackTrace(); } logger.finest("Getting monthly stat " + statistic.getStatName()); LinkedList<TopEntry> top10Monthly = getTop10Map().get(statistic.getClass()).get(StatPeriod.MONTH); try { LinkedList<TopEntry> top10Monthly1 = statistic.getTop10Monthly(connection); top10Monthly.clear(); top10Monthly.addAll(top10Monthly1); } catch (Throwable e) { if (connection.isClosed()) { logger.warning("Aborting leaderboard stat collection because connection was closed. (Reload?)"); return; } logger.severe("Could not get monthly stats " + statistic.getStatName() + "!"); e.printStackTrace(); } } logger.finest("Getting all time stat " + statistic.getStatName()); LinkedList<TopEntry> top10AllTime = getTop10Map().get(statistic.getClass()).get(StatPeriod.ALL); try { LinkedList<TopEntry> top10AllTime1 = statistic.getTop10AllTime(connection); top10AllTime.clear(); top10AllTime.addAll(top10AllTime1); } catch (Throwable e) { if (connection.isClosed()) { logger.warning("Aborting leaderboard stat collection because connection was closed. (Reload?)"); return; } logger.severe("Could not get all time stats " + statistic.getStatName() + "!"); e.printStackTrace(); } } }, false); eventRegistry.callEvent(new LeaderboardUpdateEvent()); hasLoadedAll = true; logger.fine("Got all stats!"); } @Override public void onDisable() { if(currentTask != null) { currentTask.cancel(); } } @Override public void onReload() { onDisable(); top10Map.clear(); onPreEnable(); pluginScheduler.runTaskAsynchronously(this::onPostEnable); } @Override public String getReloadName() { return "leaderboard"; } public Map<Class<? extends Statistic>, Map<StatPeriod, LinkedList<TopEntry>>> getTop10Map() { return top10Map; } public boolean hasLoadedAll() { return hasLoadedAll; } }
6,671
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HolographicStat.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/HolographicStat.java
package me.patothebest.gamecore.leaderboards.holograms; import com.gmail.filoghost.holographicdisplays.api.Hologram; import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import me.patothebest.gamecore.file.CoreConfig; import me.patothebest.gamecore.leaderboards.LeaderboardManager; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.SerializableObject; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.LinkedList; import java.util.Map; public class HolographicStat implements SerializableObject { private final Hologram hologram; private final LeaderHologram parent; private final Statistic statistic; private final StatPeriod period; private final String title; private final String style; private final String none; private final String change; private final LeaderboardManager leaderboardManager; @AssistedInject private HolographicStat(Plugin plugin, CoreConfig config, @Assisted LeaderHologram parent, @Assisted Statistic statistic, @Assisted StatPeriod period, @Assisted String title, LeaderboardManager leaderboardManager) { this.parent = parent; this.statistic = statistic; this.period = period; this.title = title; this.leaderboardManager = leaderboardManager; this.hologram = HologramsAPI.createHologram(plugin, parent.getHologramLocation()); this.style = config.getString("stat-holograms.style"); this.none = config.getString("stat-holograms.none"); this.change = config.getString("stat-holograms.change"); } @AssistedInject private HolographicStat(Plugin plugin, CoreConfig config, @Assisted LeaderHologram parent, StatsManager statsManager, @Assisted Map<String, Object> data, LeaderboardManager leaderboardManager) { this.parent = parent; this.leaderboardManager = leaderboardManager; this.hologram = HologramsAPI.createHologram(plugin, parent.getHologramLocation()); this.style = config.getString("stat-holograms.style"); this.none = config.getString("stat-holograms.none"); this.change = config.getString("stat-holograms.change"); this.statistic = statsManager.getStatisticByName((String) data.get("stat")); this.period = Utils.getEnumValueFromString(StatPeriod.class, (String) data.get("period")); this.title = (String) data.get("title"); } public void updateStats() { hologram.clearLines(); hologram.appendTextLine(ChatColor.translateAlternateColorCodes('&', title)) .setTouchHandler(parent.getTouchHandler()); LinkedList<TopEntry> topEntries = leaderboardManager.getTop10Map().get(statistic.getClass()).get(period); for (int i = 0; i < parent.getAmountToDisplay(); i++) { String base; if (topEntries.size() > i) { TopEntry topEntry = topEntries.get(i); base = style.replace("%player_name%", topEntry.getName()) .replace("%amount%", String.valueOf(topEntry.getAmount())); } else { base = none; } base = base.replace("%place%", String.valueOf(i + 1)); hologram.appendTextLine(ChatColor.translateAlternateColorCodes('&', base)) .setTouchHandler(parent.getTouchHandler()); } if (parent.hasPages()) { hologram.appendTextLine(ChatColor.translateAlternateColorCodes('&', change)) .setTouchHandler(parent.getTouchHandler()); } } public void updateLocation() { hologram.teleport(parent.getHologramLocation()); } public String getTitle() { return title; } @Override public void serialize(Map<String, Object> data) { data.put("stat", statistic.getName()); data.put("period", period.name()); data.put("title", title); } public void setDefaultVisible(boolean value) { hologram.getVisibilityManager().setVisibleByDefault(value); } public void showToPlayer(Player player) { hologram.getVisibilityManager().showTo(player); } public void hideFromPlayer(Player player) { hologram.getVisibilityManager().hideTo(player); } public void destroy() { hologram.delete(); } public Statistic getStatistic() { return statistic; } public StatPeriod getPeriod() { return period; } }
4,842
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HolographicFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/HolographicFile.java
package me.patothebest.gamecore.leaderboards.holograms; import com.google.inject.Inject; import me.patothebest.gamecore.file.FlatFile; import me.patothebest.gamecore.modules.Module; public class HolographicFile extends FlatFile implements Module { @Inject private HolographicFile() { super("leader-holograms"); this.header = "Leaderboard Holograms"; load(); } }
398
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HolographicFactory.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/HolographicFactory.java
package me.patothebest.gamecore.leaderboards.holograms; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import org.bukkit.Location; import java.util.Map; public interface HolographicFactory { HolographicStat createHoloStat(LeaderHologram parent, Statistic statistic, StatPeriod period, String title); HolographicStat createHoloStat(LeaderHologram parent, Map<String, Object> data); LeaderHologram createLeaderHologram(String name, Location location); LeaderHologram createLeaderHologram(Map<String, Object> data); }
588
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderHologramManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/LeaderHologramManager.java
package me.patothebest.gamecore.leaderboards.holograms; import com.google.inject.Inject; import com.google.inject.Singleton; import me.patothebest.gamecore.event.other.LeaderboardUpdateEvent; import me.patothebest.gamecore.file.CoreConfig; import me.patothebest.gamecore.file.ParserException; import me.patothebest.gamecore.logger.InjectLogger; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ListenerModule; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.pluginhooks.PluginHookManager; import me.patothebest.gamecore.pluginhooks.hooks.HolographicDisplaysHook; import me.patothebest.gamecore.scheduler.PluginScheduler; import me.patothebest.gamecore.util.Utils; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerQuitEvent; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; @Singleton @ModuleName("Leader Holograms Manager") public class LeaderHologramManager implements ActivableModule, ReloadableModule, ListenerModule { private final List<LeaderHologram> holograms = new ArrayList<>(); private final HolographicFactory factory; private final PluginScheduler pluginScheduler; private final PluginHookManager pluginHookManager; private final CoreConfig config; private final HolographicFile holoFile; @InjectLogger private Logger logger; @Inject private LeaderHologramManager(HolographicFactory factory, PluginScheduler pluginScheduler, PluginHookManager pluginHookManager, CoreConfig config, HolographicFile holoFile) { this.factory = factory; this.pluginScheduler = pluginScheduler; this.pluginHookManager = pluginHookManager; this.config = config; this.holoFile = holoFile; } @SuppressWarnings("unchecked") @Override public void onPostEnable() { if(!config.getBoolean("leaderboard.enabled")) { return; } if (!pluginHookManager.isHookLoaded(HolographicDisplaysHook.class)) { logger.info("Holographic displays not found. Leader Holograms won't be enabled."); return; } List<Map<String, Object>> hologramsData = (List<Map<String, Object>>) holoFile.get("holograms"); if (hologramsData == null || hologramsData.isEmpty()) { return; } logger.info(ChatColor.YELLOW + "Loading leaderboard holograms..."); for (Map<String, Object> holoData : hologramsData) { try { holograms.add(factory.createLeaderHologram(holoData)); } catch (ParserException e) { Utils.printError("Could not parse leaderboard hologram", e.getMessage()); } catch (Throwable t) { logger.severe(ChatColor.RED + "Could not load leaderboard hologram"); t.printStackTrace(); } } logger.info("Loaded " + holograms.size() + " hologram(s)"); } @Override public void onDisable() { for (LeaderHologram hologram : holograms) { hologram.destroy(); } holograms.clear(); } @EventHandler public void onStatsUpdate(LeaderboardUpdateEvent event) { pluginScheduler.ensureSync(() -> { for (LeaderHologram hologram : holograms) { hologram.updateHolograms(); } }); } @EventHandler public void onQuit(PlayerQuitEvent event) { for (LeaderHologram hologram : holograms) { hologram.playerQuit(event.getPlayer()); } } @Override public void onReload() { onDisable(); onPostEnable(); } @Override public String getReloadName() { return "leaderholograms"; } public void saveData() { List<Map<String, Object>> hologramsData = new ArrayList<>(); for (LeaderHologram sign : holograms) { hologramsData.add(sign.serialize()); } holoFile.set("holograms", hologramsData); holoFile.save(); } public void createHologram(String name, Location location) { holograms.add(factory.createLeaderHologram(name, location)); } public LeaderHologram getHologram(String name) { for (LeaderHologram hologram : holograms) { if (hologram.getName().equalsIgnoreCase(name)) { return hologram; } } return null; } public List<LeaderHologram> getHolograms() { return holograms; } }
4,692
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderHologram.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/LeaderHologram.java
package me.patothebest.gamecore.leaderboards.holograms; import com.gmail.filoghost.holographicdisplays.api.handler.TouchHandler; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.util.NameableObject; import me.patothebest.gamecore.util.SerializableObject; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LeaderHologram implements SerializableObject, NameableObject { private final List<HolographicStat> pages = new ArrayList<>(); private final String name; private final HolographicFactory factory; private final Map<Player, Integer> index = new HashMap<>(); private final TouchHandler touchHandler = this::update; private Location location; private int amountToDisplay = 10; @AssistedInject private LeaderHologram(HolographicFactory factory, @Assisted String name, @Assisted Location location) { this.factory = factory; this.location = location; this.name = name; updateHolograms(); } @SuppressWarnings("unchecked") @AssistedInject private LeaderHologram(HolographicFactory factory, @Assisted Map<String, Object> data) { this.factory = factory; this.location = Location.deserialize((Map<String, Object>) data.get("location")); this.name = (String) data.get("name"); this.amountToDisplay = (int) data.get("amount-to-display"); List<Map<String, Object>> pagesData = (List<Map<String, Object>>) data.get("pages"); for (Map<String, Object> page : pagesData) { pages.add(factory.createHoloStat(this, page)); } updateHolograms(); } public void updateHolograms() { for (HolographicStat stat : pages) { stat.updateStats(); stat.setDefaultVisible(false); } if (!pages.isEmpty()) { pages.get(0).setDefaultVisible(true); } } public void setAmountToDisplay(int amountToDisplay) { this.amountToDisplay = amountToDisplay; updateHolograms(); } private void update(Player player) { if (pages.size() <= 1) { return; } int currentIndex = index.getOrDefault(player, 0); int nextIndex = (currentIndex + 1) % pages.size(); pages.get(currentIndex).hideFromPlayer(player); pages.get(nextIndex).showToPlayer(player); index.put(player, nextIndex); } public void playerQuit(Player player) { this.index.remove(player); } @Override public void serialize(Map<String, Object> data) { data.put("name", name); data.put("location", location.serialize()); List<Map<String, Object>> pageData = new ArrayList<>(); for (HolographicStat page : pages) { pageData.add(page.serialize()); } data.put("pages", pageData); data.put("amount-to-display", amountToDisplay); } public void addPage(Statistic statistic, StatPeriod period, String title) { HolographicStat holoStat = factory.createHoloStat(this, statistic, period, title); pages.add(holoStat); updateHolograms(); } public List<HolographicStat> getPages() { return pages; } public void removePage(int page) { pages.get(page).destroy(); pages.remove(page); updateHolograms(); } public boolean hasPages() { return pages.size() > 1; } public int getAmountToDisplay() { return amountToDisplay; } public Location getHologramLocation() { return location.clone(); } public void setLocation(Location location) { this.location = location; for (HolographicStat page : pages) { page.updateLocation(); } } public TouchHandler getTouchHandler() { return touchHandler; } public void destroy() { for (HolographicStat page : pages) { page.destroy(); } pages.clear(); index.clear(); } @Override public String getName() { return name; } }
4,356
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HolographicCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/holograms/HolographicCommand.java
package me.patothebest.gamecore.leaderboards.holograms; import me.patothebest.gamecore.chat.CommandPagination; import me.patothebest.gamecore.chat.Pagination; import me.patothebest.gamecore.command.ChatColor; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.command.NestedCommand; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.leaderboards.LeaderboardCommand; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import javax.inject.Inject; import java.util.List; public class HolographicCommand implements RegisteredCommandModule { private final StatsManager statsManager; private final LeaderHologramManager leaderHologramManager; @Inject private HolographicCommand(StatsManager statsManager, LeaderHologramManager leaderHologramManager) { this.statsManager = statsManager; this.leaderHologramManager = leaderHologramManager; } @ChildOf(LeaderboardCommand.class) public static class Parent implements RegisteredCommandModule { private final CommandsManager<CommandSender> commandsManager; @Inject private Parent(CommandsManager<CommandSender> commandsManager) { this.commandsManager = commandsManager; } @Command( aliases = {"holo", "holograms"}, langDescription = @LangDescription( langClass = CoreLang.class, element = "LEADERBOARD_HOLOGRAM_DESC" ) ) @CommandPermissions(permission = Permission.SETUP) @NestedCommand(value = HolographicCommand.class) public void holograms(CommandContext args, CommandSender sender) throws CommandException { new CommandPagination(commandsManager, args).display(sender); } } @Command( aliases = {"create"}, usage = "<name>", min = 1, max = 1, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_CREATE", langClass = CoreLang.class ) ) public void create(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); String name = args.getString(0); CommandUtils.validateTrue(leaderHologramManager.getHologram(name) == null, CoreLang.LEADERBOARD_HOLOGRAM_ALREADY_EXISTS); leaderHologramManager.createHologram(name, player.getLocation()); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_CREATED.sendMessage(player); } @Command( aliases = {"add"}, usage = "<hologram> <stat> <periodicity> <title>", min = 4, max = -1, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_ADD", langClass = CoreLang.class ) ) public List<String> add(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } else if (args.getSuggestionContext().getIndex() == 1) { return CommandUtils.completeNameable(args.getString(1), statsManager.getStatistics()); } else if (args.getSuggestionContext().getIndex() == 2) { return CommandUtils.complete(args.getString(2), StatPeriod.values()); } return null; } Player player = CommandUtils.getPlayer(sender); LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(player, args.getString(0))); } Statistic statistic = statsManager.getStatisticByName(args.getString(1)); CommandUtils.validateNotNull(statistic, CoreLang.LEADERBOARD_STATISTIC_NOT_FOUND); StatPeriod statPeriod = CommandUtils.getEnumValueFromString(StatPeriod.class, args.getString(2), CoreLang.LEADERBOARD_PERIOD_NOT_FOUND); String title = args.getJoinedStrings(3); hologram.addPage(statistic, statPeriod, title); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_ADDED.replaceAndSend(player, statistic.getName(), hologram.getName()); return null; } @Command( aliases = {"list"}, usage = "[hologram] [page]", min = 0, max = 2, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_LIST", langClass = CoreLang.class ) ) public List<String> list(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } if (args.isInBounds(0) && !args.isInteger(0)) { LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(sender, args.getString(0))); } int page = 1; if(args.isInBounds(1)) { page = args.getInteger(1); } new Pagination<HolographicStat>() { @Override protected String title() { return CoreLang.LEADERBOARD_HOLOGRAM_LIST_TITLE.getMessage(sender); } @Override protected String entry(HolographicStat entry, int index, CommandSender commandSender) { return ChatColor.GRAY + "* " + ChatColor.GOLD.toString() + (index+1) + ". " + ChatColor.BLUE + entry.getTitle() + " " + ChatColor.YELLOW + " Stat: " + entry.getStatistic().getStatName() + " Period: " + Utils.capitalizeFirstLetter(entry.getPeriod().name()); } }.display(sender, hologram.getPages(), page); } else { int page = 1; if(args.isInBounds(0)) { page = args.getInteger(0); } new Pagination<LeaderHologram>() { @Override protected String title() { return CoreLang.LEADERBOARD_HOLOGRAM_LIST_TITLE.getMessage(sender); } @Override protected String entry(LeaderHologram entry, int index, CommandSender commandSender) { return ChatColor.GRAY + "* " + ChatColor.GOLD.toString() + (index+1) + ". " + ChatColor.BLUE + entry.getName() + " " + ChatColor.YELLOW + " Location: " + Utils.locationToCoords(entry.getHologramLocation(), commandSender) + " Entries: " + entry.getAmountToDisplay(); } }.display(sender, leaderHologramManager.getHolograms(), page); } return null; } @Command( aliases = {"setsize"}, usage = "<hologram> <size>", min = 2, max = 2, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_SETSIZE", langClass = CoreLang.class ) ) public List<String> setsize(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } return null; } Player player = CommandUtils.getPlayer(sender); LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(player, args.getString(0))); } int integer = args.getInteger(1); CommandUtils.validateTrue(integer <= 10, CoreLang.LEADERBOARD_MAX_PLACE); hologram.setAmountToDisplay(integer); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_SETSIZE_SUCCESS.replaceAndSend(sender, integer); return null; } @Command( aliases = {"move", "tp"}, usage = "<hologram>", min = 1, max = 1, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_MOVE", langClass = CoreLang.class ) ) public List<String> move(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } return null; } Player player = CommandUtils.getPlayer(sender); LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(player, args.getString(0))); } hologram.setLocation(player.getLocation()); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_MOVED.sendMessage(sender); return null; } @Command( aliases = {"remove"}, usage = "<hologram> <index>", min = 2, max = 2, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_REMOVE", langClass = CoreLang.class ) ) public List<String> remove(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } return null; } Player player = CommandUtils.getPlayer(sender); LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(player, args.getString(0))); } int integer = args.getInteger(1); CommandUtils.validateTrue(hologram.getPages().size() >= integer && integer > 0, CoreLang.LEADERBOARD_HOLOGRAM_REMOVE_INDEX); HolographicStat holographicStat = hologram.getPages().get(integer - 1); hologram.removePage(integer - 1); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_REMOVED.replaceAndSend(player, holographicStat.getStatistic().getName(), Utils.capitalizeFirstLetter(holographicStat.getPeriod().name())); return null; } @Command( aliases = {"delete"}, usage = "<hologram>", flags = "c", min = 1, max = 1, langDescription = @LangDescription( element = "LEADERBOARD_HOLOGRAM_DELETE", langClass = CoreLang.class ) ) public List<String> delete(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), leaderHologramManager.getHolograms()); } return null; } Player player = CommandUtils.getPlayer(sender); LeaderHologram hologram = leaderHologramManager.getHologram(args.getString(0)); if (hologram == null) { throw new CommandException(CoreLang.LEADERBOARD_HOLOGRAM_NOT_FOUND.replace(player, args.getString(0))); } if (!args.hasFlag('c')) { CoreLang.LEADERBOARD_HOLOGRAM_DELETE_CONFIRM.replaceAndSend(sender, hologram.getName()); } else { hologram.destroy(); leaderHologramManager.getHolograms().remove(hologram); leaderHologramManager.saveData(); CoreLang.LEADERBOARD_HOLOGRAM_DELETED.sendMessage(sender); } return null; } }
13,435
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AttachmentCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/AttachmentCommand.java
package me.patothebest.gamecore.leaderboards.signs; import me.patothebest.gamecore.chat.CommandPagination; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.command.NestedCommand; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.leaderboards.LeaderboardCommand; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import javax.inject.Inject; import java.util.List; public class AttachmentCommand implements RegisteredCommandModule { private final StatsManager statsManager; private final LeaderSignsManager leaderSignsManager; @Inject private AttachmentCommand(StatsManager statsManager, LeaderSignsManager leaderSignsManager) { this.statsManager = statsManager; this.leaderSignsManager = leaderSignsManager; } @ChildOf(LeaderboardCommand.class) public static class Parent implements RegisteredCommandModule { private final CommandsManager<CommandSender> commandsManager; @Inject private Parent(CommandsManager<CommandSender> commandsManager) { this.commandsManager = commandsManager; } @Command( aliases = {"attachments", "attach"}, langDescription = @LangDescription( langClass = CoreLang.class, element = "LEADERBOARD_ATTACHMENTS_DESC" ) ) @CommandPermissions(permission = Permission.SETUP) @NestedCommand(value = AttachmentCommand.class) public void attachments(CommandContext args, CommandSender sender) throws CommandException { new CommandPagination(commandsManager, args).display(sender); } } @Command( aliases = {"add"}, usage = "<type>", min = 1, max = 1, langDescription = @LangDescription( element = "LEADERBOARD_ATTACHMENTS_ADD", langClass = CoreLang.class ) ) public List<String> add(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { return CommandUtils.complete(args.getString(0), AttachmentType.usableValues()); } Player player = CommandUtils.getPlayer(sender); AttachmentType attachmentType = CommandUtils.getEnumValueFromString(AttachmentType.class, args.getString(0), CoreLang.LEADERBOARD_ATTACHMENTS_NOT_FOUND); if (!attachmentType.canBeUsed()) { throw new CommandException(CoreLang.LEADERBOARD_ATTACHMENTS_NOT_USABLE.replace(sender, attachmentType.getDependencyClass().getSimpleName())); } leaderSignsManager.getSignInteractCallback().put(player, leaderSign -> { for (Attachment attachment : leaderSign.getAttachmentSet()) { if (attachment.getType() == attachmentType) { CoreLang.LEADERBOARD_ATTACHMENTS_ALREADY_ATTACHED.sendMessage(player); return; } } Attachment attachment = leaderSignsManager.createAttachment(attachmentType); if (attachment.createNew(leaderSign)) { leaderSign.getAttachmentSet().add(attachment); leaderSign.update(); CoreLang.LEADERBOARD_ATTACHMENTS_ADDED.sendMessage(player); } else { CoreLang.LEADERBOARD_ATTACHMENTS_COULD_NOT_ADD.sendMessage(player); } }); CoreLang.LEADERBOARD_ATTACHMENTS_RIGHT_CLICK.sendMessage(sender); return null; } }
4,166
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AttachmentType.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/AttachmentType.java
package me.patothebest.gamecore.leaderboards.signs; import com.google.inject.Injector; import me.patothebest.gamecore.leaderboards.signs.attachments.ArmorStandAttachment; import me.patothebest.gamecore.leaderboards.signs.attachments.HologramAttachment; import me.patothebest.gamecore.leaderboards.signs.attachments.NPCAttachment; import me.patothebest.gamecore.leaderboards.signs.attachments.SkullAttachment; import me.patothebest.gamecore.pluginhooks.PluginHook; import me.patothebest.gamecore.pluginhooks.PluginHookManager; import me.patothebest.gamecore.pluginhooks.hooks.CitizensPluginHook; import me.patothebest.gamecore.pluginhooks.hooks.HolographicDisplaysHook; import org.apache.commons.lang.Validate; import java.util.HashSet; import java.util.Set; public enum AttachmentType { SKULL(SkullAttachment.class, null, true), NPC(NPCAttachment.class, CitizensPluginHook.class, true), HOLOGRAM(HologramAttachment.class, HolographicDisplaysHook.class, false), ARMOR_STAND(ArmorStandAttachment.class, null, false); private final Class<? extends Attachment> attachmentClass; private final Class<? extends PluginHook> dependencyClass; private final boolean implemented; private boolean canBeUsed; private static AttachmentType[] usableValues; AttachmentType(Class<? extends Attachment> attachmentClass, Class<? extends PluginHook> dependencyClass, boolean implemented) { this.attachmentClass = attachmentClass; this.dependencyClass = dependencyClass; this.implemented = implemented; } public static void setup(PluginHookManager pluginHookManager) { Set<AttachmentType> usableTypes = new HashSet<>(); for (AttachmentType value : values()) { if (value.dependencyClass == null || pluginHookManager.isHookLoaded(value.dependencyClass)) { value.canBeUsed = true; if (value.implemented) { usableTypes.add(value); } } } usableValues = usableTypes.toArray(new AttachmentType[0]); } public Attachment createNew(Injector injector) { Validate.isTrue(canBeUsed, "Dependency " + dependencyClass + " is missing for attachment " + name() + "!"); return injector.getInstance(attachmentClass); } public boolean canBeUsed() { return implemented && canBeUsed; } public static AttachmentType[] usableValues() { return usableValues.clone(); } public Class<? extends PluginHook> getDependencyClass() { return dependencyClass; } }
2,590
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Attachment.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/Attachment.java
package me.patothebest.gamecore.leaderboards.signs; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.util.SerializableObject; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; public interface Attachment extends SerializableObject { /** * Method for parsing an already configured attachment * * @param data the data to parse */ void parse(Map<String, Object> data); /** * Method to setup a new attachment */ boolean createNew(LeaderSign sign); /** * Update the attachment, will be called sync * * @param sign the sign to reference * @param entry the current top entry */ void update(LeaderSign sign, @Nullable TopEntry entry); /** * @return the attachment type */ AttachmentType getType(); /** * Deletes any data associated with this attachment, such as entities */ default void destroy() {} @Override default Map<String, Object> serialize() { Map<String, Object> data = new HashMap<>(); data.put("type", getType().name()); serialize(data); return data; } }
1,194
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderSign.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/LeaderSign.java
package me.patothebest.gamecore.leaderboards.signs; import me.patothebest.gamecore.file.ParserValidations; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.SerializableObject; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Sign; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class LeaderSign implements SerializableObject { private final LeaderSignsManager leaderSignsManager; private final Location location; private final Statistic statistic; private final StatPeriod period; private final int place; // place number, not index private final Set<Attachment> attachmentSet = new HashSet<>(); public LeaderSign(LeaderSignsManager leaderSignsManager, Location location, Statistic statistic, StatPeriod period, int place) { this.leaderSignsManager = leaderSignsManager; this.location = location; this.statistic = statistic; this.period = period; this.place = place; } @SuppressWarnings("unchecked") public LeaderSign(LeaderSignsManager leaderSignsManager, StatsManager statsManager, Map<String, Object> data) { this.leaderSignsManager = leaderSignsManager; this.location = Location.deserialize((Map<String, Object>) data.get("location")); this.statistic = statsManager.getStatisticByName((String) data.get("stat")); this.place = (int) data.get("place"); this.period = Utils.getEnumValueFromString(StatPeriod.class, (String) data.get("period")); if (data.get("attachments") != null) { List<Map<String, Object>> attachments = (List<Map<String, Object>>) data.get("attachments"); for (Map<String, Object> attachmentData : attachments) { String type = (String) attachmentData.get("type"); AttachmentType attachmentType = Utils.getEnumValueFromString(AttachmentType.class, type); ParserValidations.isTrue(attachmentType.canBeUsed(), "Missing dependency for " + attachmentType.name() + "!"); Attachment attachment = leaderSignsManager.createAttachment(attachmentType); attachment.parse(attachmentData); attachmentSet.add(attachment); } } } public void update() { if(!(location.getBlock().getState() instanceof Sign)) { return; } Sign sign = (Sign) location.getBlock().getState(); LinkedList<TopEntry> topEntries = leaderSignsManager.getLeaderboardManager().getTop10Map().get(statistic.getClass()).get(period); TopEntry topEntry = (topEntries.size() >= place ? topEntries.get(place - 1) : null); if (topEntry == null) { for (int i = 0; i < 4; i++) { String line = leaderSignsManager.getFallbackSignTemplate()[i]; sign.setLine(i, ChatColor.translateAlternateColorCodes('&', line)); } } else { for (int i = 0; i < 4; i++) { String line = leaderSignsManager.getSignTemplate()[i] .replace("%place%", String.valueOf(place)) .replace("%player_name%", topEntry.getName()) .replace("%stat_name%", statistic.getStatName()) .replace("%amount%", String.valueOf(topEntry.getAmount())); sign.setLine(i, ChatColor.translateAlternateColorCodes('&', line)); } } sign.update(true, false); for (Attachment attachment : attachmentSet) { attachment.update(this, topEntry); } } @Override public void serialize(Map<String, Object> data) { data.put("stat", statistic.getStatName()); data.put("place", place); data.put("period", period.name()); data.put("location", location.serialize()); if (!attachmentSet.isEmpty()) { List<Map<String, Object>> attachments = new ArrayList<>(); for (Attachment attachment : attachmentSet) { attachments.add(attachment.serialize()); } data.put("attachments", attachments); } } @Override public String toString() { return "LeaderSign{" + "location=" + location + ", statistic=" + statistic + ", period=" + period + ", place=" + place + '}'; } public Location getLocation() { return location; } public Statistic getStatistic() { return statistic; } public StatPeriod getPeriod() { return period; } public int getPlace() { return place; } public Set<Attachment> getAttachmentSet() { return attachmentSet; } public void destroy() { for (Attachment attachment : attachmentSet) { attachment.destroy(); } } }
5,244
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderSignsFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/LeaderSignsFile.java
package me.patothebest.gamecore.leaderboards.signs; import com.google.inject.Inject; import me.patothebest.gamecore.file.FlatFile; import me.patothebest.gamecore.modules.Module; public class LeaderSignsFile extends FlatFile implements Module { @Inject private LeaderSignsFile() { super("leader-signs"); this.header = "Leaderboard Signs"; load(); } }
386
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderSignsCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/LeaderSignsCommand.java
package me.patothebest.gamecore.leaderboards.signs; import me.patothebest.gamecore.chat.CommandPagination; import me.patothebest.gamecore.chat.Pagination; import me.patothebest.gamecore.command.ChatColor; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.command.NestedCommand; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.leaderboards.LeaderboardCommand; import me.patothebest.gamecore.modules.Module; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import javax.inject.Inject; import java.util.List; public class LeaderSignsCommand implements Module { private final StatsManager statsManager; private final LeaderSignsManager leaderSignsManager; @Inject private LeaderSignsCommand(StatsManager statsManager, LeaderSignsManager leaderSignsManager) { this.statsManager = statsManager; this.leaderSignsManager = leaderSignsManager; } @ChildOf(LeaderboardCommand.class) public static class Parent implements RegisteredCommandModule { private final CommandsManager<CommandSender> commandsManager; @Inject private Parent(CommandsManager<CommandSender> commandsManager) { this.commandsManager = commandsManager; } @Command( aliases = "signs", langDescription = @LangDescription( langClass = CoreLang.class, element = "LEADERBOARD_SIGNS_DESC" ) ) @CommandPermissions(permission = Permission.SETUP) @NestedCommand(value = LeaderSignsCommand.class) public void signs(CommandContext args, CommandSender sender) throws CommandException { new CommandPagination(commandsManager, args).display(sender); } } @Command( aliases = {"add"}, usage = "<stat> <periodicity> <place>", min = 3, max = 3, langDescription = @LangDescription( element = "LEADERBOARD_SIGNS_ADD", langClass = CoreLang.class ) ) public List<String> add(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { if (args.getSuggestionContext().getIndex() == 0) { return CommandUtils.completeNameable(args.getString(0), statsManager.getStatistics()); } else if (args.getSuggestionContext().getIndex() == 1) { return CommandUtils.complete(args.getString(1), StatPeriod.values()); } return null; } Player player = CommandUtils.getPlayer(sender); Statistic statistic = statsManager.getStatisticByName(args.getString(0)); CommandUtils.validateNotNull(statistic, CoreLang.LEADERBOARD_STATISTIC_NOT_FOUND); StatPeriod statPeriod = CommandUtils.getEnumValueFromString(StatPeriod.class, args.getString(1), CoreLang.LEADERBOARD_PERIOD_NOT_FOUND); int place = args.getInteger(2); CommandUtils.validateTrue(place <= 10, CoreLang.LEADERBOARD_MAX_PLACE); leaderSignsManager.getBlockInteractCallback().put(player, block -> { LeaderSign leaderSign = leaderSignsManager.createSign(block.getLocation(), statistic, statPeriod, place); leaderSignsManager.getSigns().add(leaderSign); try { for (AttachmentType attachmentType : AttachmentType.usableValues()) { Attachment attachment = leaderSignsManager.createAttachment(attachmentType); if (attachment.createNew(leaderSign)) { leaderSign.getAttachmentSet().add(attachment); break; } } } catch (Throwable t) { t.printStackTrace(); } leaderSignsManager.saveData(); leaderSignsManager.updateData(); CoreLang.SIGN_CREATED.sendMessage(player); }); CoreLang.LEADERBOARD_SIGNS_CLICK_TO_ADD.sendMessage(sender); return null; } @Command( aliases = {"list", "listsigns", "signs", "l"}, usage = "[page]", max = 1, langDescription = @LangDescription( langClass = CoreLang.class, element = "LEADERBOARD_SIGNS_LIST" ) ) @CommandPermissions(permission = Permission.SETUP) public void list(CommandContext args, CommandSender sender) throws CommandException { CommandUtils.getPlayer(sender); List<LeaderSign> signs = leaderSignsManager.getSigns(); int page = 1; if(args.isInBounds(0) && args.isInteger(0)) { page = args.getInteger(0); } new Pagination<LeaderSign>() { @Override protected String title() { return "Signs"; } @Override protected String entry(LeaderSign entry, int index, CommandSender commandSender) { return ChatColor.GRAY + "* " + ChatColor.GOLD.toString() + (index+1) + ". " + ChatColor.BLUE + entry.getStatistic().getStatName() + " " + ChatColor.YELLOW + " Location: " + Utils.locationToString(entry.getLocation(), sender); } }.display(sender, signs, page); } }
6,105
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderSignsManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/LeaderSignsManager.java
package me.patothebest.gamecore.leaderboards.signs; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Singleton; import me.patothebest.gamecore.event.other.LeaderboardUpdateEvent; import me.patothebest.gamecore.file.CoreConfig; import me.patothebest.gamecore.file.ParserException; import me.patothebest.gamecore.leaderboards.LeaderboardManager; import me.patothebest.gamecore.logger.InjectParentLogger; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ListenerModule; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.pluginhooks.PluginHookManager; import me.patothebest.gamecore.scheduler.PluginScheduler; import me.patothebest.gamecore.stats.StatPeriod; import me.patothebest.gamecore.stats.Statistic; import me.patothebest.gamecore.stats.StatsManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.Callback; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @Singleton @ModuleName("Leader Signs Manager") public class LeaderSignsManager implements ActivableModule, ReloadableModule, ListenerModule { private final LeaderboardManager leaderboardManager; private final CoreConfig coreConfig; private final StatsManager statsManager; private final PluginHookManager pluginHookManager; private final PluginScheduler pluginScheduler; private final Provider<Injector> injectorProvider; private final LeaderSignsFile leaderSignsFile; private final List<LeaderSign> signs = new ArrayList<>(); private final Map<Player, Callback<Block>> blockInteractCallback = new HashMap<>(); private final Map<Player, Callback<LeaderSign>> signInteractCallback = new HashMap<>(); private String[] signTemplate; private String[] fallbackSignTemplate; @InjectParentLogger(parent = LeaderboardManager.class) private Logger logger; @Inject private LeaderSignsManager(LeaderboardManager leaderboardManager, CoreConfig coreConfig, StatsManager statsManager, PluginHookManager pluginHookManager, PluginScheduler pluginScheduler, Provider<Injector> injectorProvider, LeaderSignsFile leaderSignsFile) { this.leaderboardManager = leaderboardManager; this.coreConfig = coreConfig; this.statsManager = statsManager; this.pluginHookManager = pluginHookManager; this.pluginScheduler = pluginScheduler; this.injectorProvider = injectorProvider; this.leaderSignsFile = leaderSignsFile; } @Override public void onPreEnable() { signTemplate = coreConfig.getStringList("leaderboard-signs").toArray(new String[4]); fallbackSignTemplate = coreConfig.getStringList("leaderboard-signs-fallback").toArray(new String[4]); } @SuppressWarnings("unchecked") @Override public void onPostEnable() { if(!coreConfig.getBoolean("leaderboard.enabled")) { return; } AttachmentType.setup(pluginHookManager); List<Map<String, Object>> signsData = (List<Map<String, Object>>) leaderSignsFile.get("signs"); if (signsData == null || signsData.isEmpty()) { return; } logger.info(ChatColor.YELLOW + "Loading leaderboard signs..."); for (Map<String, Object> signData : signsData) { try { signs.add(new LeaderSign(this, statsManager, signData)); } catch (ParserException e) { Utils.printError("Could not parse leaderboard sign", e.getMessage()); } catch (Throwable t) { logger.log(Level.SEVERE, ChatColor.RED + "Could not load sign", t); } } logger.info("Loaded " + signs.size() + " sign(s)"); } @Override public void onReload() { onDisable(); onPreEnable(); onPostEnable(); } @Override public void onDisable() { signs.clear(); } @Override public String getReloadName() { return "leadersigns"; } public void saveData() { List<Map<String, Object>> signData = new ArrayList<>(); for (LeaderSign sign : signs) { signData.add(sign.serialize()); } leaderSignsFile.set("signs", signData); leaderSignsFile.save(); } @EventHandler public void onLeaderboardUpdate(LeaderboardUpdateEvent event) { updateData(); } public void updateData() { pluginScheduler.ensureSync(() -> { logger.fine("Updating leader signs"); for (LeaderSign sign : signs) { try { sign.update(); } catch (Throwable t) { logger.log(Level.SEVERE, "Could not update sign " + sign.toString(), t); } } }); } public LeaderSign createSign(Location location, Statistic statistic, StatPeriod period, int place) { return new LeaderSign(this, location, statistic, period, place); } public String[] getSignTemplate() { return signTemplate; } public String[] getFallbackSignTemplate() { return fallbackSignTemplate; } public Attachment createAttachment(AttachmentType attachmentType) { return attachmentType.createNew(injectorProvider.get()); } public LeaderboardManager getLeaderboardManager() { return leaderboardManager; } public List<LeaderSign> getSigns() { return signs; } public Map<Player, Callback<Block>> getBlockInteractCallback() { return blockInteractCallback; } public Map<Player, Callback<LeaderSign>> getSignInteractCallback() { return signInteractCallback; } }
6,103
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LeaderSignListener.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/LeaderSignListener.java
package me.patothebest.gamecore.leaderboards.signs; import com.google.inject.Inject; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.modules.ListenerModule; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.util.Callback; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; public class LeaderSignListener implements ListenerModule { private final LeaderSignsManager leaderSignsManager; @Inject LeaderSignListener(LeaderSignsManager leaderSignsManager) { this.leaderSignsManager = leaderSignsManager; } @EventHandler public void onQuit(PlayerQuitEvent event) { leaderSignsManager.getBlockInteractCallback().remove(event.getPlayer()); } @EventHandler public void onSignClick(PlayerInteractEvent event) { if (event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } if (!event.getClickedBlock().getType().name().contains("SIGN")) { return; } Callback<Block> callback = leaderSignsManager.getBlockInteractCallback().remove(event.getPlayer()); if(callback != null) { callback.call(event.getClickedBlock()); event.setCancelled(true); return; } Callback<LeaderSign> signCallback = leaderSignsManager.getSignInteractCallback().get(event.getPlayer()); if (signCallback == null) { return; } for (LeaderSign sign : leaderSignsManager.getSigns()) { if (sign.getLocation().equals(event.getClickedBlock().getLocation())) { signCallback.call(sign); leaderSignsManager.getSignInteractCallback().remove(event.getPlayer()); return; } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onSignBreak(BlockBreakEvent event) { if(!event.getBlock().getType().name().contains("SIGN")) { return; } LeaderSign sign = null; for (LeaderSign signI : leaderSignsManager.getSigns()) { if (signI.getLocation().equals(event.getBlock().getLocation())) { sign = signI; break; } } if(sign == null) { return; } if(!event.getPlayer().hasPermission(Permission.ADMIN.getBukkitPermission())) { event.setCancelled(true); return; } sign.destroy(); leaderSignsManager.getSigns().remove(sign); leaderSignsManager.saveData(); event.getPlayer().sendMessage(CoreLang.SIGN_REMOVED.getMessage(event.getPlayer())); } }
2,989
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ArmorStandAttachment.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/attachments/ArmorStandAttachment.java
package me.patothebest.gamecore.leaderboards.signs.attachments; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.leaderboards.signs.Attachment; import me.patothebest.gamecore.leaderboards.signs.AttachmentType; import me.patothebest.gamecore.leaderboards.signs.LeaderSign; import java.util.Map; public class ArmorStandAttachment implements Attachment { @Override public void parse(Map<String, Object> data) { } @Override public boolean createNew(LeaderSign sign) { return false; } @Override public void update(LeaderSign sign, TopEntry entry) { } @Override public AttachmentType getType() { return AttachmentType.ARMOR_STAND; } @Override public void serialize(Map<String, Object> data) { } }
814
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SkullAttachment.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/attachments/SkullAttachment.java
package me.patothebest.gamecore.leaderboards.signs.attachments; import com.google.inject.Inject; import com.google.inject.Provider; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.leaderboards.signs.Attachment; import me.patothebest.gamecore.logger.InjectLogger; import me.patothebest.gamecore.nms.NMS; import me.patothebest.gamecore.player.PlayerSkinCache; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.leaderboards.signs.AttachmentType; import me.patothebest.gamecore.leaderboards.signs.LeaderSign; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Skull; import java.lang.reflect.Field; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; public class SkullAttachment implements Attachment { private final static EnumSet<BlockFace> ADJACENT_FACES = EnumSet.of(BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST); private final PlayerSkinCache playerSkinCache; private final Provider<NMS> nmsProvider; private Location skullLocation; private String lastPerson = null; @InjectLogger(name = "Skins") private Logger logger; @Inject private SkullAttachment(PlayerSkinCache playerSkinCache, Provider<NMS> nmsProvider) { this.playerSkinCache = playerSkinCache; this.nmsProvider = nmsProvider; } @SuppressWarnings("unchecked") @Override public void parse(Map<String, Object> data) { skullLocation = Location.deserialize((Map<String, Object>) data.get("location")); } @Override public boolean createNew(LeaderSign sign) { Block signBlock = sign.getLocation().getBlock(); Block blockAttachedToSign = nmsProvider.get().getBlockAttachedToSign(signBlock); for (BlockFace adjacentFace : ADJACENT_FACES) { if (isHead(signBlock.getRelative(adjacentFace).getType())) { skullLocation = signBlock.getRelative(adjacentFace).getLocation(); return true; } } Block upwardsBlock = blockAttachedToSign.getRelative(BlockFace.UP); if (isHead(upwardsBlock.getType())) { skullLocation = upwardsBlock.getLocation(); return true; } return false; } private boolean isHead(Material material) { return material.name().contains("SKULL") || material.name().contains("HEAD"); } @Override public void update(LeaderSign sign, TopEntry topEntry) { BlockState state = skullLocation.getBlock().getState(); if (!(state instanceof Skull)) { return; } String skinName; if (topEntry == null) { skinName = "None"; } else { skinName = topEntry.getName(); } if (Objects.equals(skinName, lastPerson)) { return; } lastPerson = skinName; playerSkinCache.getPlayerSkin(skinName, skinURL -> { logger.log(Level.FINEST, "skinName={0}, skinURL={1}", new Object[] {skinName, skinURL}); if (skinURL == null || skinURL.isEmpty()) { ((Skull) state).setOwner(null); return; } try { Object profile = Utils.createGameProfile(); Object profileProperties = Utils.invokeMethod(profile, "getProperties", null); Object property = Utils.createProperty("textures", skinURL); Utils.invokeMethod(profileProperties, Utils.getMethodNotDeclaredValue(profileProperties.getClass(), "put", new Class[] {Object.class, Object.class}), "textures", property); Field profileField; profileField = state.getClass().getDeclaredField("profile"); profileField.setAccessible(true); profileField.set(state, profile); state.update(true, false); } catch (Exception e1) { e1.printStackTrace(); } }); } @Override public AttachmentType getType() { return AttachmentType.SKULL; } @Override public void serialize(Map<String, Object> data) { data.put("location", skullLocation.serialize()); } }
4,451
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HologramAttachment.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/attachments/HologramAttachment.java
package me.patothebest.gamecore.leaderboards.signs.attachments; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.leaderboards.signs.Attachment; import me.patothebest.gamecore.leaderboards.signs.AttachmentType; import me.patothebest.gamecore.leaderboards.signs.LeaderSign; import java.util.Map; public class HologramAttachment implements Attachment { @Override public void parse(Map<String, Object> data) { } @Override public boolean createNew(LeaderSign sign) { return false; } @Override public void update(LeaderSign sign, TopEntry entry) { } @Override public AttachmentType getType() { return AttachmentType.HOLOGRAM; } @Override public void serialize(Map<String, Object> data) { } }
809
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
NPCAttachment.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/leaderboards/signs/attachments/NPCAttachment.java
package me.patothebest.gamecore.leaderboards.signs.attachments; import com.google.inject.Inject; import com.google.inject.Provider; import me.patothebest.gamecore.leaderboards.TopEntry; import me.patothebest.gamecore.leaderboards.signs.Attachment; import me.patothebest.gamecore.nms.NMS; import me.patothebest.gamecore.pluginhooks.hooks.CitizensPluginHook; import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.trait.SkinTrait; import me.patothebest.gamecore.leaderboards.signs.AttachmentType; import me.patothebest.gamecore.leaderboards.signs.LeaderSign; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import java.util.Map; import java.util.Objects; public class NPCAttachment implements Attachment { private final CitizensPluginHook citizensPluginHook; private final Provider<NMS> nmsProvider; private Location npcLocation; private String lastPerson = null; private NPC npc; private int npcId = -1; @Inject private NPCAttachment(CitizensPluginHook citizensPluginHook, Provider<NMS> nmsProvider) { this.citizensPluginHook = citizensPluginHook; this.nmsProvider = nmsProvider; } @SuppressWarnings("unchecked") @Override public void parse(Map<String, Object> data) { npcLocation = Location.deserialize((Map<String, Object>) data.get("npc-location")); npcId = (int) data.getOrDefault("npc-id", -1); } @Override public boolean createNew(LeaderSign sign) { Block blockAttachedToSign = nmsProvider.get().getBlockAttachedToSign(sign.getLocation().getBlock()); Block npcBlock = blockAttachedToSign.getRelative(BlockFace.UP); if (npcBlock.getType() != Material.AIR) { return false; } npcLocation = npcBlock.getLocation().add(0.5, 0, 0.5); npcLocation.setDirection(sign.getLocation().toVector().subtract(blockAttachedToSign.getLocation().toVector())); return true; } @Override public void update(LeaderSign sign, TopEntry entry) { if (npc == null && npcId != -1) { npc = citizensPluginHook.getNPC(npcId); } if (npc == null) { npc = citizensPluginHook.createNPC((entry == null ? "n/a" : entry.getName()), npcLocation); npcId = npc.getId(); } if (entry == null) { npc.setName(ChatColor.GRAY + "n/a"); return; } if(Objects.equals(entry.getName(), lastPerson)) { return; } npc.setName(ChatColor.GREEN + entry.getName()); SkinTrait trait = npc.getTrait(SkinTrait.class); trait.setSkinName(entry.getName(), true); lastPerson = entry.getName(); } @Override public void destroy() { if (npc != null) { npc.destroy(); npcId = -1; } } @Override public AttachmentType getType() { return AttachmentType.NPC; } @Override public void serialize(Map<String, Object> data) { data.put("npc-location", npcLocation.serialize()); data.put("npc-id", npcId); } }
3,198
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
StainedClay.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/StainedClay.java
package me.patothebest.gamecore.itemstack; import me.patothebest.gamecore.util.Utils; import org.bukkit.inventory.ItemStack; public class StainedClay { public static final ItemStack WHITE = Material.WHITE_TERRACOTTA.parseItem(); public static final ItemStack ORANGE = Material.ORANGE_TERRACOTTA.parseItem(); public static final ItemStack MAGENTA = Material.MAGENTA_TERRACOTTA.parseItem(); public static final ItemStack LIGHT_BLUE = Material.LIGHT_BLUE_TERRACOTTA.parseItem(); public static final ItemStack YELLOW = Material.YELLOW_TERRACOTTA.parseItem(); public static final ItemStack LIME = Material.LIME_TERRACOTTA.parseItem(); public static final ItemStack PINK = Material.PINK_TERRACOTTA.parseItem(); public static final ItemStack GRAY = Material.GRAY_TERRACOTTA.parseItem(); public static final ItemStack LIGHT_GRAY = Material.LIGHT_GRAY_TERRACOTTA.parseItem(); public static final ItemStack CYAN = Material.CYAN_TERRACOTTA.parseItem(); public static final ItemStack PURPLE = Material.PURPLE_TERRACOTTA.parseItem(); public static final ItemStack BLUE = Material.BLUE_TERRACOTTA.parseItem(); public static final ItemStack BROWN = Material.BROWN_TERRACOTTA.parseItem(); public static final ItemStack GREEN = Material.GREEN_TERRACOTTA.parseItem(); public static final ItemStack RED = Material.RED_TERRACOTTA.parseItem(); public static final ItemStack BLACK = Material.BLACK_TERRACOTTA.parseItem(); public static ItemStack getRandom() { switch (Utils.randInt(0, 15)) { case 0: return WHITE; case 1: return ORANGE; case 2: return MAGENTA; case 3: return LIGHT_BLUE; case 4: return YELLOW; case 5: return LIME; case 6: return PINK; case 7: return GRAY; case 8: return LIGHT_GRAY; case 9: return CYAN; case 10: return PURPLE; case 11: return BLUE; case 12: return BROWN; case 13: return GREEN; case 14: return RED; case 15: return BLACK; } return WHITE; } public static Material getRandomMaterial() { switch (Utils.randInt(0, 15)) { case 0: return Material.WHITE_TERRACOTTA; case 1: return Material.ORANGE_TERRACOTTA; case 2: return Material.MAGENTA_TERRACOTTA; case 3: return Material.LIGHT_BLUE_TERRACOTTA; case 4: return Material.YELLOW_TERRACOTTA; case 5: return Material.LIME_TERRACOTTA; case 6: return Material.PINK_TERRACOTTA; case 7: return Material.GRAY_TERRACOTTA; case 8: return Material.LIGHT_GRAY_TERRACOTTA; case 9: return Material.CYAN_TERRACOTTA; case 10: return Material.PURPLE_TERRACOTTA; case 11: return Material.BLUE_TERRACOTTA; case 12: return Material.BROWN_TERRACOTTA; case 13: return Material.GREEN_TERRACOTTA; case 14: return Material.RED_TERRACOTTA; case 15: return Material.BLACK_TERRACOTTA; } return Material.WHITE_TERRACOTTA; } }
3,689
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ColoredWool.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/ColoredWool.java
package me.patothebest.gamecore.itemstack; import me.patothebest.gamecore.util.Utils; import org.bukkit.inventory.ItemStack; public class ColoredWool { public static final ItemStack WHITE = Material.WHITE_WOOL.parseItem(); public static final ItemStack ORANGE = Material.ORANGE_WOOL.parseItem(); public static final ItemStack MAGENTA = Material.MAGENTA_WOOL.parseItem(); public static final ItemStack LIGHT_BLUE = Material.LIGHT_BLUE_WOOL.parseItem(); public static final ItemStack YELLOW = Material.YELLOW_WOOL.parseItem(); public static final ItemStack LIME = Material.LIME_WOOL.parseItem(); public static final ItemStack PINK = Material.PINK_WOOL.parseItem(); public static final ItemStack GRAY = Material.GRAY_WOOL.parseItem(); public static final ItemStack LIGHT_GRAY = Material.LIGHT_GRAY_WOOL.parseItem(); public static final ItemStack CYAN = Material.CYAN_WOOL.parseItem(); public static final ItemStack PURPLE = Material.PURPLE_WOOL.parseItem(); public static final ItemStack BLUE = Material.BLUE_WOOL.parseItem(); public static final ItemStack BROWN = Material.BROWN_WOOL.parseItem(); public static final ItemStack GREEN = Material.GREEN_WOOL.parseItem(); public static final ItemStack RED = Material.RED_WOOL.parseItem(); public static final ItemStack BLACK = Material.BLACK_WOOL.parseItem(); public static ItemStack getRandom() { switch (Utils.randInt(0, 15)) { case 0: return WHITE; case 1: return ORANGE; case 2: return MAGENTA; case 3: return LIGHT_BLUE; case 4: return YELLOW; case 5: return LIME; case 6: return PINK; case 7: return GRAY; case 8: return LIGHT_GRAY; case 9: return CYAN; case 10: return PURPLE; case 11: return BLUE; case 12: return BROWN; case 13: return GREEN; case 14: return RED; case 15: return BLACK; } return WHITE; } public static Material getRandomMaterial() { switch (Utils.randInt(0, 15)) { case 0: return Material.WHITE_WOOL; case 1: return Material.ORANGE_WOOL; case 2: return Material.MAGENTA_WOOL; case 3: return Material.LIGHT_BLUE_WOOL; case 4: return Material.YELLOW_WOOL; case 5: return Material.LIME_WOOL; case 6: return Material.PINK_WOOL; case 7: return Material.GRAY_WOOL; case 8: return Material.LIGHT_GRAY_WOOL; case 9: return Material.CYAN_WOOL; case 10: return Material.PURPLE_WOOL; case 11: return Material.BLUE_WOOL; case 12: return Material.BROWN_WOOL; case 13: return Material.GREEN_WOOL; case 14: return Material.RED_WOOL; case 15: return Material.BLACK_WOOL; } return Material.WHITE_WOOL; } }
3,491
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
StainedGlassPane.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/StainedGlassPane.java
package me.patothebest.gamecore.itemstack; import me.patothebest.gamecore.util.Utils; import org.bukkit.inventory.ItemStack; public class StainedGlassPane { public static final ItemStack WHITE = Material.WHITE_STAINED_GLASS_PANE.parseItem(); public static final ItemStack ORANGE = Material.ORANGE_STAINED_GLASS_PANE.parseItem(); public static final ItemStack MAGENTA = Material.MAGENTA_STAINED_GLASS_PANE.parseItem(); public static final ItemStack LIGHT_BLUE = Material.LIGHT_BLUE_STAINED_GLASS_PANE.parseItem(); public static final ItemStack YELLOW = Material.YELLOW_STAINED_GLASS_PANE.parseItem(); public static final ItemStack LIME = Material.LIME_STAINED_GLASS_PANE.parseItem(); public static final ItemStack PINK = Material.PINK_STAINED_GLASS_PANE.parseItem(); public static final ItemStack GRAY = Material.GRAY_STAINED_GLASS_PANE.parseItem(); public static final ItemStack LIGHT_GRAY = Material.LIGHT_GRAY_STAINED_GLASS_PANE.parseItem(); public static final ItemStack CYAN = Material.CYAN_STAINED_GLASS_PANE.parseItem(); public static final ItemStack PURPLE = Material.PURPLE_STAINED_GLASS_PANE.parseItem(); public static final ItemStack BLUE = Material.BLUE_STAINED_GLASS_PANE.parseItem(); public static final ItemStack BROWN = Material.BROWN_STAINED_GLASS_PANE.parseItem(); public static final ItemStack GREEN = Material.GREEN_STAINED_GLASS_PANE.parseItem(); public static final ItemStack RED = Material.RED_STAINED_GLASS_PANE.parseItem(); public static final ItemStack BLACK = Material.BLACK_STAINED_GLASS_PANE.parseItem(); public static ItemStack getRandom() { switch (Utils.randInt(0, 15)) { case 0: return WHITE; case 1: return ORANGE; case 2: return MAGENTA; case 3: return LIGHT_BLUE; case 4: return YELLOW; case 5: return LIME; case 6: return PINK; case 7: return GRAY; case 8: return LIGHT_GRAY; case 9: return CYAN; case 10: return PURPLE; case 11: return BLUE; case 12: return BROWN; case 13: return GREEN; case 14: return RED; case 15: return BLACK; } return WHITE; } }
2,539
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Material.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/Material.java
/* * The MIT License (MIT) * * Copyright (c) 2018 Hex_27 * Copyright (c) 2020 Crypto Morin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package me.patothebest.gamecore.itemstack; import com.google.common.base.Enums; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import me.patothebest.gamecore.util.ServerVersion; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.math.NumberUtils; import org.bukkit.Bukkit; import org.bukkit.inventory.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.stream.Collectors; /* * References * * * * GitHub: https://github.com/CryptoMorin/XSeries/blob/master/Material.java * * XSeries: https://www.spigotmc.org/threads/378136/ * Pre-flattening: https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening * Materials: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html * Materials (1.8): https://helpch.at/docs/1.8/org/bukkit/Material.html * Material IDs: https://minecraft-ids.grahamedgecombe.com/ * Material Source Code: https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse/src/main/java/org/bukkit/Material.java * Material v1: https://www.spigotmc.org/threads/329630/ */ /** * <b>Material</b> - Data Values/Pre-flattening<br> * Supports 1.8-1.15<br> * 1.13 and above as priority. * * @author Crypto Morin * @version 3.3.0 * @see org.bukkit.Material * @see ItemStack */ public enum Material { ACACIA_BOAT("BOAT_ACACIA"), ACACIA_BUTTON("WOOD_BUTTON"), ACACIA_DOOR("ACACIA_DOOR_ITEM"), ACACIA_FENCE, ACACIA_FENCE_GATE, ACACIA_LEAVES("LEAVES_2"), ACACIA_LOG("LOG_2"), ACACIA_PLANKS(4, "WOOD"), ACACIA_PRESSURE_PLATE("WOOD_PLATE"), ACACIA_SAPLING(4, "SAPLING"), ACACIA_SIGN("SIGN"), ACACIA_SLAB(4, "WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), ACACIA_STAIRS, ACACIA_TRAPDOOR("TRAP_DOOR"), ACACIA_WALL_SIGN("SIGN_POST", "WALL_SIGN"), ACACIA_WOOD("LOG_2"), ACTIVATOR_RAIL, /** * https://minecraft.gamepedia.com/Air * * @see #VOID_AIR * @see #CAVE_AIR */ AIR, ALLIUM(2, "RED_ROSE"), ANDESITE(5, "STONE"), ANDESITE_SLAB, ANDESITE_STAIRS, ANDESITE_WALL, ANVIL, APPLE, ARMOR_STAND, ARROW, ATTACHED_MELON_STEM(7, "MELON_STEM"), ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"), AZURE_BLUET(3, "RED_ROSE"), BAKED_POTATO, BAMBOO("1.14", "SUGAR_CANE"), BAMBOO_SAPLING("1.14"), BARREL("1.14", "CHEST"), BARRIER, BAT_SPAWN_EGG(65, "MONSTER_EGG"), BEACON, BEDROCK, BEEF("RAW_BEEF"), BEEHIVE("1.15"), BEETROOT("BEETROOT_BLOCK"), BEETROOTS("BEETROOT"), BEETROOT_SEEDS, BEETROOT_SOUP, BEE_NEST("1.15"), BEE_SPAWN_EGG("1.15"), BELL("1.14"), BIRCH_BOAT("BOAT_BIRCH"), BIRCH_BUTTON("WOOD_BUTTON"), BIRCH_DOOR("BIRCH_DOOR_ITEM"), BIRCH_FENCE, BIRCH_FENCE_GATE, BIRCH_LEAVES(2, "LEAVES"), BIRCH_LOG(2, "LOG"), BIRCH_PLANKS(2, "WOOD"), BIRCH_PRESSURE_PLATE("WOOD_PLATE"), BIRCH_SAPLING(2, "SAPLING"), BIRCH_SIGN("SIGN"), BIRCH_SLAB(2, "WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), BIRCH_STAIRS("BIRCH_WOOD_STAIRS"), BIRCH_TRAPDOOR("TRAP_DOOR"), BIRCH_WALL_SIGN("SIGN_POST", "WALL_SIGN"), BIRCH_WOOD(2, "LOG"), BLACK_BANNER("STANDING_BANNER", "BANNER"), BLACK_BED(15, "1.12", "BED_BLOCK", "BED"), BLACK_CARPET(15, "CARPET"), BLACK_CONCRETE(15, "CONCRETE"), BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"), BLACK_DYE("1.14", "INK_SACK"), BLACK_GLAZED_TERRACOTTA(15, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLACK_TERRACOTTA"), BLACK_SHULKER_BOX, BLACK_STAINED_GLASS(15, "STAINED_GLASS"), BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"), BLACK_TERRACOTTA(15, "HARD_CLAY", "STAINED_CLAY"), BLACK_WALL_BANNER("WALL_BANNER"), BLACK_WOOL(15, "WOOL"), BLAST_FURNACE("1.14", "FURNACE"), BLAZE_POWDER, BLAZE_ROD, BLAZE_SPAWN_EGG(61, "MONSTER_EGG"), BLUE_BANNER(11, "STANDING_BANNER", "BANNER"), BLUE_BED(4, "1.12", "BED_BLOCK", "BED"), BLUE_CARPET(11, "CARPET"), BLUE_CONCRETE(11, "CONCRETE"), BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"), BLUE_DYE(4, "INK_SACK", "LAPIS_LAZULI"), BLUE_GLAZED_TERRACOTTA(11, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLUE_TERRACOTTA"), BLUE_ICE("1.13", "PACKED_ICE"), BLUE_ORCHID(1, "RED_ROSE"), BLUE_SHULKER_BOX, BLUE_STAINED_GLASS(11, "STAINED_GLASS"), BLUE_STAINED_GLASS_PANE(11, "THIN_GLASS", "STAINED_GLASS_PANE"), BLUE_TERRACOTTA(11, "STAINED_CLAY"), BLUE_WALL_BANNER(11, "WALL_BANNER"), BLUE_WOOL(11, "WOOL"), BONE, BONE_BLOCK, BONE_MEAL(15, "INK_SACK"), BOOK, BOOKSHELF, BOW, BOWL, BRAIN_CORAL("1.13"), BRAIN_CORAL_BLOCK("1.13"), BRAIN_CORAL_FAN("1.13"), BRAIN_CORAL_WALL_FAN, BREAD, BREWING_STAND("BREWING_STAND", "BREWING_STAND_ITEM"), BRICK("CLAY_BRICK"), BRICKS("BRICK"), BRICK_SLAB(4, "STEP"), BRICK_STAIRS, BRICK_WALL, BROWN_BANNER(3, "STANDING_BANNER", "BANNER"), BROWN_BED(2, "1.12", "BED_BLOCK", "BED"), BROWN_CARPET(12, "CARPET"), BROWN_CONCRETE(12, "CONCRETE"), BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"), BROWN_DYE(3, "COCOA", "COCOA_BEANS", "INK_SACK"), BROWN_GLAZED_TERRACOTTA(12, "1.12", "HARD_CLAY", "STAINED_CLAY", "BROWN_TERRACOTTA"), BROWN_MUSHROOM, BROWN_MUSHROOM_BLOCK("BROWN_MUSHROOM", "HUGE_MUSHROOM_1"), BROWN_SHULKER_BOX, BROWN_STAINED_GLASS(12, "STAINED_GLASS"), BROWN_STAINED_GLASS_PANE(12, "THIN_GLASS", "STAINED_GLASS_PANE"), BROWN_TERRACOTTA(12, "STAINED_CLAY"), BROWN_WALL_BANNER(3, "WALL_BANNER"), BROWN_WOOL(12, "WOOL"), BUBBLE_COLUMN("1.13"), BUBBLE_CORAL("1.13"), BUBBLE_CORAL_BLOCK("1.13"), BUBBLE_CORAL_FAN("1.13"), BUBBLE_CORAL_WALL_FAN, BUCKET, CACTUS, CAKE("CAKE_BLOCK"), CAMPFIRE("1.14"), CARROT("CARROT_ITEM"), CARROTS("CARROT"), CARROT_ON_A_STICK("CARROT_STICK"), CARTOGRAPHY_TABLE("1.14", "CRAFTING_TABLE"), CARVED_PUMPKIN(1, "1.13", "PUMPKIN"), CAT_SPAWN_EGG, CAULDRON("CAULDRON_ITEM"), /** * 1.13 tag is not added because it's the same thing as {@link #AIR} * * @see #VOID_AIR */ CAVE_AIR("AIR"), CAVE_SPIDER_SPAWN_EGG(59, "MONSTER_EGG"), CHAINMAIL_BOOTS, CHAINMAIL_CHESTPLATE, CHAINMAIL_HELMET, CHAINMAIL_LEGGINGS, CHAIN_COMMAND_BLOCK("COMMAND", "COMMAND_CHAIN"), CHARCOAL(1, "COAL"), CHEST("LOCKED_CHEST"), CHEST_MINECART("STORAGE_MINECART"), CHICKEN("RAW_CHICKEN"), CHICKEN_SPAWN_EGG(93, "MONSTER_EGG"), CHIPPED_ANVIL(1, "ANVIL"), CHISELED_NETHER_BRICKS(1, "NETHER_BRICKS"), CHISELED_POLISHED_BLACKSTONE("1.16", "POLISHED_BLACKSTONE"), CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"), CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"), CHISELED_SANDSTONE(1, "SANDSTONE"), CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"), CHORUS_FLOWER, CHORUS_FRUIT, CHORUS_PLANT, CLAY, CLAY_BALL, CLOCK("WATCH"), COAL, COAL_BLOCK, COAL_ORE, COARSE_DIRT(1, "DIRT"), COBBLESTONE, COBBLESTONE_SLAB(3, "STEP"), COBBLESTONE_STAIRS, COBBLESTONE_WALL("COBBLE_WALL"), COBWEB("WEB"), COCOA("1.15"), COCOA_BEANS(3, "COCOA", "INK_SACK"), COD("RAW_FISH"), COD_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), COD_SPAWN_EGG("1.13", "MONSTER_EGG"), COMMAND_BLOCK("COMMAND"), COMMAND_BLOCK_MINECART("COMMAND_MINECART"), /** * Unlike redstone torch and redstone lamp... neither REDTONE_COMPARATOR_OFF nor REDSTONE_COMPARATOR_ON * are items. REDSTONE_COMPARATOR is. * * @see #REDSTONE_TORCH * @see #REDSTONE_LAMP */ COMPARATOR("REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR_OFF", "REDSTONE_COMPARATOR"), COMPASS, COMPOSTER("1.14", "CAULDRON"), CONDUIT("1.13", "BEACON"), COOKED_BEEF, COOKED_CHICKEN, COOKED_COD("COOKED_FISH"), COOKED_MUTTON, COOKED_PORKCHOP("PORK", "GRILLED_PORK"), COOKED_RABBIT, COOKED_SALMON(1, "COOKED_FISH"), COOKIE, CORNFLOWER(4, "1.14", "BLUE_DYE"), COW_SPAWN_EGG(92, "MONSTER_EGG"), CRACKED_NETHER_BRICKS(2, "NETHER_BRICKS"), CRACKED_POLISHED_BLACKSTONE_BRICKS("1.16", "POLISHED_BLACKSTONE_BRICKS"), CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"), CRAFTING_TABLE("WORKBENCH"), CREEPER_BANNER_PATTERN, CREEPER_HEAD(4, "SKULL", "SKULL_ITEM"), CREEPER_SPAWN_EGG(50, "MONSTER_EGG"), CREEPER_WALL_HEAD(4, "SKULL", "SKULL_ITEM"), CRIMSON_BUTTON("1.16"), CRIMSON_DOOR("1.16"), CRIMSON_FENCE("1.16"), CRIMSON_FENCE_GATE("1.16"), CRIMSON_FUNGUS("1.16"), CRIMSON_HYPHAE("1.16"), CRIMSON_NYLIUM("1.16"), CRIMSON_PLANKS("1.16"), CRIMSON_PRESSURE_PLATE("1.16"), CRIMSON_ROOTS("1.16"), CRIMSON_SIGN("1.16"), CRIMSON_SLAB("1.16"), CRIMSON_STAIRS("1.16"), CRIMSON_STEM("1.16"), CRIMSON_TRAPDOOR("1.16"), CRIMSON_WALL_SIGN("1.16"), CROSSBOW, CRYING_OBSIDIAN("1.16"), CUT_RED_SANDSTONE("1.13"), CUT_RED_SANDSTONE_SLAB("STONE_SLAB2"), CUT_SANDSTONE("1.13"), CUT_SANDSTONE_SLAB("STEP"), CYAN_BANNER(6, "STANDING_BANNER", "BANNER"), CYAN_BED(9, "1.12", "BED_BLOCK", "BED"), CYAN_CARPET(9, "CARPET"), CYAN_CONCRETE(9, "CONCRETE"), CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"), CYAN_DYE(6, "INK_SACK"), CYAN_GLAZED_TERRACOTTA(9, "1.12", "HARD_CLAY", "STAINED_CLAY", "CYAN_TERRACOTTA"), CYAN_SHULKER_BOX, CYAN_STAINED_GLASS(9, "STAINED_GLASS"), CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"), CYAN_TERRACOTTA(9, "HARD_CLAY", "STAINED_CLAY"), CYAN_WALL_BANNER(6, "WALL_BANNER"), CYAN_WOOL(9, "WOOL"), DAMAGED_ANVIL(2, "ANVIL"), DANDELION("YELLOW_FLOWER"), DARK_OAK_BOAT("BOAT_DARK_OAK"), DARK_OAK_BUTTON("WOOD_BUTTON"), DARK_OAK_DOOR("DARK_OAK_DOOR_ITEM"), DARK_OAK_FENCE, DARK_OAK_FENCE_GATE, DARK_OAK_LEAVES(4, "LEAVES", "LEAVES_2"), DARK_OAK_LOG(1, "LOG", "LOG_2"), DARK_OAK_PLANKS(5, "WOOD"), DARK_OAK_PRESSURE_PLATE("WOOD_PLATE"), DARK_OAK_SAPLING(5, "SAPLING"), DARK_OAK_SIGN("SIGN"), DARK_OAK_SLAB(5, "WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), DARK_OAK_STAIRS, DARK_OAK_TRAPDOOR("TRAP_DOOR"), DARK_OAK_WALL_SIGN("SIGN_POST", "WALL_SIGN"), DARK_OAK_WOOD(1, "LOG", "LOG_2"), DARK_PRISMARINE(1, "PRISMARINE"), DARK_PRISMARINE_SLAB("1.13"), DARK_PRISMARINE_STAIRS("1.13"), DAYLIGHT_DETECTOR("DAYLIGHT_DETECTOR_INVERTED"), DEAD_BRAIN_CORAL("1.13"), DEAD_BRAIN_CORAL_BLOCK("1.13"), DEAD_BRAIN_CORAL_FAN("1.13"), DEAD_BRAIN_CORAL_WALL_FAN("1.13"), DEAD_BUBBLE_CORAL("1.13"), DEAD_BUBBLE_CORAL_BLOCK("1.13"), DEAD_BUBBLE_CORAL_FAN("1.13"), DEAD_BUBBLE_CORAL_WALL_FAN("1.13"), DEAD_BUSH, DEAD_FIRE_CORAL("1.13"), DEAD_FIRE_CORAL_BLOCK("1.13"), DEAD_FIRE_CORAL_FAN("1.13"), DEAD_FIRE_CORAL_WALL_FAN("1.13"), DEAD_HORN_CORAL("1.13"), DEAD_HORN_CORAL_BLOCK("1.13"), DEAD_HORN_CORAL_FAN("1.13"), DEAD_HORN_CORAL_WALL_FAN("1.13"), DEAD_TUBE_CORAL("1.13"), DEAD_TUBE_CORAL_BLOCK("1.13"), DEAD_TUBE_CORAL_FAN("1.13"), DEAD_TUBE_CORAL_WALL_FAN("1.13"), DEBUG_STICK("1.13", "STICK"), DETECTOR_RAIL, DIAMOND, DIAMOND_AXE, DIAMOND_BLOCK, DIAMOND_BOOTS, DIAMOND_CHESTPLATE, DIAMOND_HELMET, DIAMOND_HOE, DIAMOND_HORSE_ARMOR("DIAMOND_BARDING"), DIAMOND_LEGGINGS, DIAMOND_ORE, DIAMOND_PICKAXE, DIAMOND_SHOVEL("DIAMOND_SPADE"), DIAMOND_SWORD, DIORITE(3, "STONE"), DIORITE_SLAB, DIORITE_STAIRS, DIORITE_WALL, DIRT, DISPENSER, DOLPHIN_SPAWN_EGG("1.13", "MONSTER_EGG"), DONKEY_SPAWN_EGG(32, "MONSTER_EGG"), DRAGON_BREATH("DRAGONS_BREATH"), DRAGON_EGG, DRAGON_HEAD(5, "1.9", "SKULL", "SKULL_ITEM"), DRAGON_WALL_HEAD(5, "SKULL", "SKULL_ITEM"), DRIED_KELP("1.13"), DRIED_KELP_BLOCK("1.13"), DROPPER, DROWNED_SPAWN_EGG("1.13", "MONSTER_EGG"), EGG, ELDER_GUARDIAN_SPAWN_EGG(4, "MONSTER_EGG"), ELYTRA, EMERALD, EMERALD_BLOCK, EMERALD_ORE, ENCHANTED_BOOK, ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"), ENCHANTING_TABLE("ENCHANTMENT_TABLE"), ENDERMAN_SPAWN_EGG(58, "MONSTER_EGG"), ENDERMITE_SPAWN_EGG(67, "MONSTER_EGG"), ENDER_CHEST, ENDER_EYE("EYE_OF_ENDER"), ENDER_PEARL, END_CRYSTAL, END_GATEWAY, END_PORTAL("ENDER_PORTAL"), END_PORTAL_FRAME("ENDER_PORTAL_FRAME"), END_ROD, END_STONE("ENDER_STONE"), END_STONE_BRICKS("END_BRICKS"), END_STONE_BRICK_SLAB(6, "STEP"), END_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), END_STONE_BRICK_WALL, EVOKER_SPAWN_EGG(34, "MONSTER_EGG"), EXPERIENCE_BOTTLE("EXP_BOTTLE"), FARMLAND("SOIL", "DIRT"), FEATHER, FERMENTED_SPIDER_EYE, FERN(1, "LONG_GRASS"), /** * For some reasons filled map items are really special. * Their data value starts from 0 and every time a player * creates a new map that maps data value increases. */ FILLED_MAP("MAP"), FIRE, FIREWORK_ROCKET("FIREWORK"), FIREWORK_STAR("FIREWORK_CHARGE"), FIRE_CHARGE("FIREBALL"), FIRE_CORAL("1.13"), FIRE_CORAL_BLOCK("1.13"), FIRE_CORAL_FAN("1.13"), FIRE_CORAL_WALL_FAN, FISHING_ROD, FLETCHING_TABLE("1.14", "CRAFTING_TABLE"), FLINT, FLINT_AND_STEEL, FLOWER_BANNER_PATTERN, FLOWER_POT("FLOWER_POT_ITEM"), // TODO Fix exceptional material FOX_SPAWN_EGG("1.14"), FROSTED_ICE, FURNACE("BURNING_FURNACE"), FURNACE_MINECART("POWERED_MINECART"), GHAST_SPAWN_EGG(56, "MONSTER_EGG"), GHAST_TEAR, GLASS, GLASS_BOTTLE, GLASS_PANE("THIN_GLASS"), GLISTERING_MELON_SLICE("SPECKLED_MELON"), GLOBE_BANNER_PATTERN, GLOWSTONE, GLOWSTONE_DUST, GOLDEN_APPLE, GOLDEN_AXE("GOLD_AXE"), GOLDEN_BOOTS("GOLD_BOOTS"), GOLDEN_CARROT, GOLDEN_CHESTPLATE("GOLD_CHESTPLATE"), GOLDEN_HELMET("GOLD_HELMET"), GOLDEN_HOE("GOLD_HOE"), GOLDEN_HORSE_ARMOR("GOLD_BARDING"), GOLDEN_LEGGINGS("GOLD_LEGGINGS"), GOLDEN_PICKAXE("GOLD_PICKAXE"), GOLDEN_SHOVEL("GOLD_SPADE"), GOLDEN_SWORD("GOLD_SWORD"), GOLD_BLOCK, GOLD_INGOT, GOLD_NUGGET, GOLD_ORE, GRANITE(1, "STONE"), GRANITE_SLAB, GRANITE_STAIRS, GRANITE_WALL, GRASS, GRASS_BLOCK("GRASS"), GRASS_PATH, GRAVEL, GRAY_BANNER(8, "STANDING_BANNER", "BANNER"), GRAY_BED(7, "1.12", "BED_BLOCK", "BED"), GRAY_CARPET(7, "CARPET"), GRAY_CONCRETE(7, "CONCRETE"), GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"), GRAY_DYE(8, "INK_SACK"), GRAY_GLAZED_TERRACOTTA(7, "1.12", "HARD_CLAY", "STAINED_CLAY", "GRAY_TERRACOTTA"), GRAY_SHULKER_BOX, GRAY_STAINED_GLASS(7, "STAINED_GLASS"), GRAY_STAINED_GLASS_PANE(7, "THIN_GLASS", "STAINED_GLASS_PANE"), GRAY_TERRACOTTA(7, "HARD_CLAY", "STAINED_CLAY"), GRAY_WALL_BANNER(8, "WALL_BANNER"), GRAY_WOOL(7, "WOOL"), GREEN_BANNER(2, "STANDING_BANNER", "BANNER"), GREEN_BED(3, "1.12", "BED_BLOCK", "BED"), GREEN_CARPET(13, "CARPET"), GREEN_CONCRETE(13, "CONCRETE"), GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"), GREEN_DYE(2, "INK_SACK", "CACTUS_GREEN"), GREEN_GLAZED_TERRACOTTA(13, "1.12", "HARD_CLAY", "STAINED_CLAY", "GREEN_TERRACOTTA"), GREEN_SHULKER_BOX, GREEN_STAINED_GLASS(13, "STAINED_GLASS"), GREEN_STAINED_GLASS_PANE(13, "THIN_GLASS", "STAINED_GLASS_PANE"), GREEN_TERRACOTTA(13, "HARD_CLAY", "STAINED_CLAY"), GREEN_WALL_BANNER(2, "WALL_BANNER"), GREEN_WOOL(13, "WOOL"), GRINDSTONE("1.14", "ANVIL"), GUARDIAN_SPAWN_EGG(68, "MONSTER_EGG"), GUNPOWDER("SULPHUR"), HAY_BLOCK, HEART_OF_THE_SEA("1.13"), HEAVY_WEIGHTED_PRESSURE_PLATE("IRON_PLATE"), HONEYCOMB("1.15"), HONEYCOMB_BLOCK("1.15"), HONEY_BLOCK("1.15", "SLIME_BLOCK"), HONEY_BOTTLE("1.15", "GLASS_BOTTLE"), HOPPER, HOPPER_MINECART, HORN_CORAL("1.13"), HORN_CORAL_BLOCK("1.13"), HORN_CORAL_FAN("1.13"), HORN_CORAL_WALL_FAN, HORSE_SPAWN_EGG(100, "MONSTER_EGG"), HUSK_SPAWN_EGG(23, "MONSTER_EGG"), ICE, INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS", "SMOOTH_BRICK"), INFESTED_COBBLESTONE(1, "MONSTER_EGGS"), INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS", "SMOOTH_BRICK"), INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"), INFESTED_STONE("MONSTER_EGGS"), INFESTED_STONE_BRICKS(2, "MONSTER_EGGS", "SMOOTH_BRICK"), INK_SAC("INK_SACK"), IRON_AXE, IRON_BARS("IRON_FENCE"), IRON_BLOCK, IRON_BOOTS, IRON_CHESTPLATE, IRON_DOOR("IRON_DOOR_BLOCK"), IRON_HELMET, IRON_HOE, IRON_HORSE_ARMOR("IRON_BARDING"), IRON_INGOT, IRON_LEGGINGS, IRON_NUGGET, IRON_ORE, IRON_PICKAXE, IRON_SHOVEL("IRON_SPADE"), IRON_SWORD, IRON_TRAPDOOR, ITEM_FRAME, JACK_O_LANTERN, JIGSAW("1.14", "COMMAND_BLOCK", "STRUCTURE_BLOCK"), JUKEBOX, JUNGLE_BOAT("BOAT_JUNGLE"), JUNGLE_BUTTON("WOOD_BUTTON"), JUNGLE_DOOR("JUNGLE_DOOR_ITEM"), JUNGLE_FENCE, JUNGLE_FENCE_GATE, JUNGLE_LEAVES(3, "LEAVES"), JUNGLE_LOG(3, "LOG"), JUNGLE_PLANKS(3, "WOOD"), JUNGLE_PRESSURE_PLATE("WOOD_PLATE"), JUNGLE_SAPLING(3, "SAPLING"), JUNGLE_SIGN("SIGN"), JUNGLE_SLAB(3, "WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), JUNGLE_STAIRS("JUNGLE_WOOD_STAIRS"), JUNGLE_TRAPDOOR("TRAP_DOOR"), JUNGLE_WALL_SIGN("SIGN_POST", "WALL_SIGN"), JUNGLE_WOOD(3, "LOG"), KELP("1.13"), KELP_PLANT("1.13"), KNOWLEDGE_BOOK("1.12", "BOOK"), LADDER, LANTERN("1.14", "SEA_LANTERN"), LAPIS_BLOCK, LAPIS_LAZULI(4, "INK_SACK"), LAPIS_ORE, LARGE_FERN(3, "DOUBLE_PLANT"), LAVA("STATIONARY_LAVA"), LAVA_BUCKET, LEAD("LEASH"), LEATHER, LEATHER_BOOTS, LEATHER_CHESTPLATE, LEATHER_HELMET, LEATHER_HORSE_ARMOR("1.14", "IRON_HORSE_ARMOR"), LEATHER_LEGGINGS, LECTERN("1.14", "BOOKSHELF"), LEVER, LIGHT_BLUE_BANNER(12, "STANDING_BANNER", "BANNER"), LIGHT_BLUE_BED(3, "1.12", "BED_BLOCK", "BED"), LIGHT_BLUE_CARPET(3, "CARPET"), LIGHT_BLUE_CONCRETE(3, "CONCRETE"), LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"), LIGHT_BLUE_DYE(12, "INK_SACK"), LIGHT_BLUE_GLAZED_TERRACOTTA(3, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_BLUE_TERRACOTTA"), LIGHT_BLUE_SHULKER_BOX, LIGHT_BLUE_STAINED_GLASS(3, "STAINED_GLASS"), LIGHT_BLUE_STAINED_GLASS_PANE(3, "THIN_GLASS", "STAINED_GLASS_PANE"), LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"), LIGHT_BLUE_WALL_BANNER(12, "WALL_BANNER", "STANDING_BANNER", "BANNER"), LIGHT_BLUE_WOOL(3, "WOOL"), LIGHT_GRAY_BANNER(7, "STANDING_BANNER", "BANNER"), LIGHT_GRAY_BED(8, "1.12", "BED_BLOCK", "BED"), LIGHT_GRAY_CARPET(8, "CARPET"), LIGHT_GRAY_CONCRETE(8, "CONCRETE"), LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"), LIGHT_GRAY_DYE(7, "INK_SACK"), /** * Renamed to SILVER_GLAZED_TERRACOTTA in 1.12 * Renamed to LIGHT_GRAY_GLAZED_TERRACOTTA in 1.14 */ LIGHT_GRAY_GLAZED_TERRACOTTA( "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_GRAY_TERRACOTTA", "SILVER_GLAZED_TERRACOTTA/1.13"), LIGHT_GRAY_SHULKER_BOX("SILVER_SHULKER_BOX"), LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"), LIGHT_GRAY_STAINED_GLASS_PANE(8, "THIN_GLASS", "STAINED_GLASS_PANE"), LIGHT_GRAY_TERRACOTTA(8, "HARD_CLAY", "STAINED_CLAY"), LIGHT_GRAY_WALL_BANNER(7, "WALL_BANNER"), LIGHT_GRAY_WOOL(8, "WOOL"), LIGHT_WEIGHTED_PRESSURE_PLATE("GOLD_PLATE"), LILAC(1, "DOUBLE_PLANT"), LILY_OF_THE_VALLEY(15, "1.14", "WHITE_DYE"), LILY_PAD("WATER_LILY"), LIME_BANNER(10, "STANDING_BANNER", "BANNER"), LIME_BED(5, "1.12", "BED_BLOCK", "BED"), LIME_CARPET(5, "CARPET"), LIME_CONCRETE(5, "CONCRETE"), LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"), LIME_DYE(10, "INK_SACK"), LIME_GLAZED_TERRACOTTA(5, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIME_TERRACOTTA"), LIME_SHULKER_BOX, LIME_STAINED_GLASS(5, "STAINED_GLASS"), LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"), LIME_TERRACOTTA(5, "HARD_CLAY", "STAINED_CLAY"), LIME_WALL_BANNER(10, "WALL_BANNER"), LIME_WOOL(5, "WOOL"), LINGERING_POTION, LLAMA_SPAWN_EGG(103, "MONSTER_EGG"), LODESTONE("1.16"), LOOM("1.14"), MAGENTA_BANNER(13, "STANDING_BANNER", "BANNER"), MAGENTA_BED(2, "1.12", "BED_BLOCK", "BED"), MAGENTA_CARPET(2, "CARPET"), MAGENTA_CONCRETE(2, "CONCRETE"), MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"), MAGENTA_DYE(13, "INK_SACK"), MAGENTA_GLAZED_TERRACOTTA(2, "1.12", "HARD_CLAY", "STAINED_CLAY", "MAGENTA_TERRACOTTA"), MAGENTA_SHULKER_BOX, MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"), MAGENTA_STAINED_GLASS_PANE(2, "THIN_GLASS", "STAINED_GLASS_PANE"), MAGENTA_TERRACOTTA(2, "HARD_CLAY", "STAINED_CLAY"), MAGENTA_WALL_BANNER(13, "WALL_BANNER"), MAGENTA_WOOL(2, "WOOL"), MAGMA_BLOCK("MAGMA"), MAGMA_CREAM, MAGMA_CUBE_SPAWN_EGG(62, "MONSTER_EGG"), /** * Adding this to the duplicated list will give you a filled map * for 1.13+ versions and removing it from duplicated list will * still give you a filled map in -1.12 versions. * Since higher versions are our priority I'll keep 1.13+ support * until I can come up with something to fix it. */ MAP("EMPTY_MAP"), MELON("MELON_BLOCK"), MELON_SEEDS, MELON_SLICE("MELON"), MELON_STEM, MILK_BUCKET, MINECART, MOJANG_BANNER_PATTERN, MOOSHROOM_SPAWN_EGG(96, "MONSTER_EGG"), MOSSY_COBBLESTONE, MOSSY_COBBLESTONE_SLAB(3, "STEP"), MOSSY_COBBLESTONE_STAIRS, MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL", "COBBLESTONE_WALL"), MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"), MOSSY_STONE_BRICK_SLAB(5, "STEP"), MOSSY_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), MOSSY_STONE_BRICK_WALL, MOVING_PISTON("PISTON_BASE", "PISTON_MOVING_PIECE"), MULE_SPAWN_EGG(32, "MONSTER_EGG"), MUSHROOM_STEM("BROWN_MUSHROOM"), MUSHROOM_STEW("MUSHROOM_SOUP"), MUSIC_DISC_11("GOLD_RECORD"), MUSIC_DISC_13("GREEN_RECORD"), MUSIC_DISC_BLOCKS("RECORD_3"), MUSIC_DISC_CAT("RECORD_4"), MUSIC_DISC_CHIRP("RECORD_5"), MUSIC_DISC_FAR("RECORD_6"), MUSIC_DISC_MALL("RECORD_7"), MUSIC_DISC_MELLOHI("RECORD_8"), MUSIC_DISC_STAL("RECORD_9"), MUSIC_DISC_STRAD("RECORD_10"), MUSIC_DISC_WAIT("RECORD_11"), MUSIC_DISC_WARD("RECORD_12"), MUTTON, MYCELIUM("MYCEL"), NAME_TAG, NAUTILUS_SHELL("1.13"), NETHERITE_AXE("1.16"), NETHERITE_BLOCK("1.16"), NETHERITE_BOOTS("1.16"), NETHERITE_CHESTPLATE("1.16"), NETHERITE_HELMET("1.16"), NETHERITE_HOE("1.16"), NETHERITE_INGOT("1.16"), NETHERITE_LEGGINGS("1.16"), NETHERITE_PICKAXE("1.16"), NETHERITE_SCRAP("1.16"), NETHERITE_SHOVEL("1.16"), NETHERITE_SWORD("1.16"), NETHERRACK, NETHER_BRICK("NETHER_BRICK_ITEM"), NETHER_BRICKS("NETHER_BRICK"), NETHER_BRICK_FENCE("NETHER_FENCE"), NETHER_BRICK_SLAB(6, "STEP"), NETHER_BRICK_STAIRS, NETHER_BRICK_WALL, NETHER_GOLD_ORE("1.16"), NETHER_PORTAL("PORTAL"), NETHER_QUARTZ_ORE("QUARTZ_ORE"), NETHER_SPROUTS("1.16"), NETHER_STAR, NETHER_WART("NETHER_WARTS", "NETHER_STALK"), NETHER_WART_BLOCK, NOTE_BLOCK, OAK_BOAT("BOAT"), OAK_BUTTON("WOOD_BUTTON"), OAK_DOOR("WOODEN_DOOR", "WOOD_DOOR"), OAK_FENCE("FENCE"), OAK_FENCE_GATE("FENCE_GATE"), OAK_LEAVES("LEAVES"), OAK_LOG("LOG"), OAK_PLANKS("WOOD"), OAK_PRESSURE_PLATE("WOOD_PLATE"), OAK_SAPLING("SAPLING"), OAK_SIGN("SIGN"), OAK_SLAB("WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), OAK_STAIRS("WOOD_STAIRS"), OAK_TRAPDOOR("TRAP_DOOR"), OAK_WALL_SIGN("SIGN_POST", "WALL_SIGN"), OAK_WOOD("LOG"), OBSERVER, OBSIDIAN, OCELOT_SPAWN_EGG(98, "MONSTER_EGG"), ORANGE_BANNER(14, "STANDING_BANNER", "BANNER"), ORANGE_BED(1, "1.12", "BED_BLOCK", "BED"), ORANGE_CARPET(1, "CARPET"), ORANGE_CONCRETE(1, "CONCRETE"), ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"), ORANGE_DYE(14, "INK_SACK"), ORANGE_GLAZED_TERRACOTTA(1, "1.12", "HARD_CLAY", "STAINED_CLAY", "ORANGE_TERRACOTTA"), ORANGE_SHULKER_BOX, ORANGE_STAINED_GLASS(1, "STAINED_GLASS"), ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"), ORANGE_TERRACOTTA(1, "HARD_CLAY", "STAINED_CLAY"), ORANGE_TULIP(5, "RED_ROSE"), ORANGE_WALL_BANNER(14, "WALL_BANNER"), ORANGE_WOOL(1, "WOOL"), OXEYE_DAISY(8, "RED_ROSE"), PACKED_ICE, PAINTING, PANDA_SPAWN_EGG("1.14"), PAPER, PARROT_SPAWN_EGG(105, "MONSTER_EGG"), PEONY(5, "DOUBLE_PLANT"), PETRIFIED_OAK_SLAB("WOOD_STEP"), PHANTOM_MEMBRANE("1.13"), PHANTOM_SPAWN_EGG("1.13", "MONSTER_EGG"), PIG_SPAWN_EGG(90, "MONSTER_EGG"), PILLAGER_SPAWN_EGG("1.14"), PINK_BANNER(9, "STANDING_BANNER", "BANNER"), PINK_BED(6, "1.12", "BED_BLOCK", "BED"), PINK_CARPET(6, "CARPET"), PINK_CONCRETE(6, "CONCRETE"), PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"), PINK_DYE(9, "INK_SACK"), PINK_GLAZED_TERRACOTTA(6, "1.12", "HARD_CLAY", "STAINED_CLAY", "PINK_TERRACOTTA"), PINK_SHULKER_BOX, PINK_STAINED_GLASS(6, "STAINED_GLASS"), PINK_STAINED_GLASS_PANE(6, "THIN_GLASS", "STAINED_GLASS_PANE"), PINK_TERRACOTTA(6, "HARD_CLAY", "STAINED_CLAY"), PINK_TULIP(7, "RED_ROSE"), PINK_WALL_BANNER(9, "WALL_BANNER"), PINK_WOOL(6, "WOOL"), PISTON("PISTON_BASE"), PISTON_HEAD("PISTON_EXTENSION"), PLAYER_HEAD(3, "SKULL", "SKULL_ITEM"), PLAYER_WALL_HEAD(3, "SKULL", "SKULL_ITEM"), PODZOL(2, "DIRT"), POISONOUS_POTATO, POLAR_BEAR_SPAWN_EGG(102, "MONSTER_EGG"), POLISHED_ANDESITE(6, "STONE"), POLISHED_ANDESITE_SLAB, POLISHED_ANDESITE_STAIRS, POLISHED_BASALT("1.16"), POLISHED_BLACKSTONE("1.16"), POLISHED_BLACKSTONE_BRICKS("1.16"), POLISHED_BLACKSTONE_BRICK_SLAB("1.16"), POLISHED_BLACKSTONE_BRICK_STAIRS("1.16"), POLISHED_BLACKSTONE_BRICK_WALL("1.16"), POLISHED_BLACKSTONE_BUTTON("1.16"), POLISHED_BLACKSTONE_PRESSURE_PLATE("1.16"), POLISHED_BLACKSTONE_SLAB("1.16"), POLISHED_BLACKSTONE_STAIRS("1.16"), POLISHED_BLACKSTONE_WALL("1.16"), POLISHED_DIORITE(4, "STONE"), POLISHED_DIORITE_SLAB, POLISHED_DIORITE_STAIRS, POLISHED_GRANITE(2, "STONE"), POLISHED_GRANITE_SLAB, POLISHED_GRANITE_STAIRS, POPPED_CHORUS_FRUIT("CHORUS_FRUIT_POPPED"), POPPY("RED_ROSE"), PORKCHOP("PORK"), POTATO("POTATO_ITEM"), POTATOES("POTATO"), POTION, POTTED_ACACIA_SAPLING(4, "SAPLING", "FLOWER_POT"), POTTED_ALLIUM(2, "RED_ROSE", "FLOWER_POT"), POTTED_AZURE_BLUET(3, "RED_ROSE", "FLOWER_POT"), POTTED_BAMBOO, POTTED_BIRCH_SAPLING(2, "SAPLING", "FLOWER_POT"), POTTED_BLUE_ORCHID(1, "RED_ROSE", "FLOWER_POT"), POTTED_BROWN_MUSHROOM("FLOWER_POT"), POTTED_CACTUS("FLOWER_POT"), POTTED_CORNFLOWER, POTTED_DANDELION("YELLOW_FLOWER", "FLOWER_POT"), POTTED_DARK_OAK_SAPLING(5, "SAPLING", "FLOWER_POT"), POTTED_DEAD_BUSH("FLOWER_POT"), POTTED_FERN(2, "LONG_GRASS", "FLOWER_POT"), POTTED_JUNGLE_SAPLING(3, "SAPLING", "FLOWER_POT"), POTTED_LILY_OF_THE_VALLEY, POTTED_OAK_SAPLING("SAPLING", "FLOWER_POT"), POTTED_ORANGE_TULIP(5, "RED_ROSE", "FLOWER_POT"), POTTED_OXEYE_DAISY(8, "RED_ROSE", "FLOWER_POT"), POTTED_PINK_TULIP(7, "RED_ROSE", "FLOWER_POT"), POTTED_POPPY("RED_ROSE", "FLOWER_POT"), POTTED_RED_MUSHROOM("FLOWER_POT"), POTTED_RED_TULIP(4, "RED_ROSE", "FLOWER_POT"), POTTED_SPRUCE_SAPLING(1, "SAPLING", "FLOWER_POT"), POTTED_WHITE_TULIP(6, "RED_ROSE", "FLOWER_POT"), POTTED_WITHER_ROSE, POWERED_RAIL, PRISMARINE, PRISMARINE_BRICKS(2, "PRISMARINE"), PRISMARINE_BRICK_SLAB(4, "STEP"), PRISMARINE_BRICK_STAIRS("1.13"), PRISMARINE_CRYSTALS, PRISMARINE_SHARD, PRISMARINE_SLAB("1.13"), PRISMARINE_STAIRS("1.13"), PRISMARINE_WALL, PUFFERFISH(3, "RAW_FISH"), PUFFERFISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), PUFFERFISH_SPAWN_EGG("1.13", "MONSTER_EGG"), PUMPKIN, PUMPKIN_PIE, PUMPKIN_SEEDS, PUMPKIN_STEM, PURPLE_BANNER(5, "STANDING_BANNER", "BANNER"), PURPLE_BED(0, "1.12", "BED_BLOCK", "BED"), PURPLE_CARPET(10, "CARPET"), PURPLE_CONCRETE(10, "CONCRETE"), PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"), PURPLE_DYE(5, "INK_SACK"), PURPLE_GLAZED_TERRACOTTA(10, "1.12", "HARD_CLAY", "STAINED_CLAY", "PURPLE_TERRACOTTA"), PURPLE_SHULKER_BOX, PURPLE_STAINED_GLASS(10, "STAINED_GLASS"), PURPLE_STAINED_GLASS_PANE(10, "THIN_GLASS", "STAINED_GLASS_PANE"), PURPLE_TERRACOTTA(10, "HARD_CLAY", "STAINED_CLAY"), PURPLE_WALL_BANNER(5, "WALL_BANNER"), PURPLE_WOOL(10, "WOOL"), PURPUR_BLOCK, PURPUR_PILLAR, PURPUR_SLAB("PURPUR_DOUBLE_SLAB"), PURPUR_STAIRS, QUARTZ, QUARTZ_BLOCK, QUARTZ_PILLAR(2, "QUARTZ_BLOCK"), QUARTZ_SLAB(7, "STEP"), QUARTZ_STAIRS, RABBIT, RABBIT_FOOT, RABBIT_HIDE, RABBIT_SPAWN_EGG(101, "MONSTER_EGG"), RABBIT_STEW, RAIL("RAILS"), RAVAGER_SPAWN_EGG("1.14"), REDSTONE, REDSTONE_BLOCK, /** * Unlike redstone torch, REDSTONE_LAMP_ON isn't an item. * The name is just here on the list for matching. * * @see #REDSTONE_TORCH */ REDSTONE_LAMP("REDSTONE_LAMP_ON", "REDSTONE_LAMP_OFF"), REDSTONE_ORE("GLOWING_REDSTONE_ORE"), /** * REDSTONE_TORCH_OFF isn't an item, but a block. * But REDSTONE_TORCH_ON is the item. * The name is just here on the list for matching. */ REDSTONE_TORCH("REDSTONE_TORCH_OFF", "REDSTONE_TORCH_ON"), REDSTONE_WALL_TORCH, REDSTONE_WIRE, RED_BANNER(1, "STANDING_BANNER", "BANNER"), RED_BED(4, "1.12", "BED_BLOCK", "BED"), RED_CARPET(14, "CARPET"), RED_CONCRETE(14, "CONCRETE"), RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"), RED_DYE(1, "INK_SACK"), RED_GLAZED_TERRACOTTA(14, "1.12", "HARD_CLAY", "STAINED_CLAY", "RED_TERRACOTTA"), RED_MUSHROOM, RED_MUSHROOM_BLOCK("RED_MUSHROOM", "HUGE_MUSHROOM_2"), RED_NETHER_BRICKS("RED_NETHER_BRICK"), RED_NETHER_BRICK_SLAB(4, "STEP"), RED_NETHER_BRICK_STAIRS, RED_NETHER_BRICK_WALL, RED_SAND(1, "SAND"), RED_SANDSTONE, RED_SANDSTONE_SLAB("DOUBLE_STONE_SLAB2", "STONE_SLAB2"), RED_SANDSTONE_STAIRS, RED_SANDSTONE_WALL, RED_SHULKER_BOX, RED_STAINED_GLASS(14, "STAINED_GLASS"), RED_STAINED_GLASS_PANE(14, "THIN_GLASS", "STAINED_GLASS_PANE"), RED_TERRACOTTA(14, "HARD_CLAY", "STAINED_CLAY"), RED_TULIP(4, "RED_ROSE"), RED_WALL_BANNER(1, "WALL_BANNER"), RED_WOOL(14, "WOOL"), REPEATER("DIODE_BLOCK_ON", "DIODE_BLOCK_OFF", "DIODE"), REPEATING_COMMAND_BLOCK("COMMAND", "COMMAND_REPEATING"), RESPAWN_ANCHOR("1.16"), ROSE_BUSH(4, "DOUBLE_PLANT"), ROTTEN_FLESH, SADDLE, SALMON(1, "RAW_FISH"), SALMON_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), SALMON_SPAWN_EGG("1.13", "MONSTER_EGG"), SAND, SANDSTONE, SANDSTONE_SLAB(1, "DOUBLE_STEP", "STEP", "STONE_SLAB"), SANDSTONE_STAIRS, SANDSTONE_WALL, SCAFFOLDING("1.14", "SLIME_BLOCK"), SCUTE("1.13"), SEAGRASS("1.13", "GRASS"), SEA_LANTERN, SEA_PICKLE("1.13"), SHEARS, SHEEP_SPAWN_EGG(91, "MONSTER_EGG"), SHIELD, SHROOMLIGHT("1.16"), SHULKER_BOX("PURPLE_SHULKER_BOX"), SHULKER_SHELL, SHULKER_SPAWN_EGG(69, "MONSTER_EGG"), SILVERFISH_SPAWN_EGG(60, "MONSTER_EGG"), SKELETON_HORSE_SPAWN_EGG(28, "MONSTER_EGG"), SKELETON_SKULL("SKULL", "SKULL_ITEM"), SKELETON_SPAWN_EGG(51, "MONSTER_EGG"), SKELETON_WALL_SKULL("SKULL", "SKULL_ITEM"), SKULL_BANNER_PATTERN, SLIME_BALL, SLIME_BLOCK, SLIME_SPAWN_EGG(55, "MONSTER_EGG"), SMITHING_TABLE, SMOKER("1.14", "FURNACE"), SMOOTH_QUARTZ("1.13"), SMOOTH_QUARTZ_SLAB(7, "STEP"), SMOOTH_QUARTZ_STAIRS, SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"), SMOOTH_RED_SANDSTONE_SLAB("STONE_SLAB2"), SMOOTH_RED_SANDSTONE_STAIRS, SMOOTH_SANDSTONE(2, "SANDSTONE"), SMOOTH_SANDSTONE_SLAB("STEP"), SMOOTH_SANDSTONE_STAIRS, SMOOTH_STONE("STEP"), SMOOTH_STONE_SLAB("STEP"), SNOW, SNOWBALL("SNOW_BALL"), SNOW_BLOCK, SOUL_CAMPFIRE("1.16"), SOUL_FIRE("1.16"), SOUL_LANTERN("1.16"), SOUL_SAND, SOUL_SOIL("1.16"), SOUL_TORCH("1.16"), SOUL_WALL_TORCH("1.16"), SPAWNER("MOB_SPAWNER"), SPECTRAL_ARROW("1.9", "ARROW"), SPIDER_EYE, SPIDER_SPAWN_EGG(52, "MONSTER_EGG"), SPLASH_POTION, SPONGE, SPRUCE_BOAT("BOAT_SPRUCE"), SPRUCE_BUTTON("WOOD_BUTTON"), SPRUCE_DOOR("SPRUCE_DOOR_ITEM"), SPRUCE_FENCE, SPRUCE_FENCE_GATE, SPRUCE_LEAVES(1, "LEAVES"), SPRUCE_LOG(1, "LOG"), SPRUCE_PLANKS(1, "WOOD"), SPRUCE_PRESSURE_PLATE("WOOD_PLATE"), SPRUCE_SAPLING(1, "SAPLING"), SPRUCE_SIGN("SIGN"), SPRUCE_SLAB(1, "WOOD_DOUBLE_STEP", "WOOD_STEP", "WOODEN_SLAB"), SPRUCE_STAIRS("SPRUCE_WOOD_STAIRS"), SPRUCE_TRAPDOOR("TRAP_DOOR"), SPRUCE_WALL_SIGN("SIGN_POST", "WALL_SIGN"), SPRUCE_WOOD(1, "LOG"), SQUID_SPAWN_EGG(94, "MONSTER_EGG"), STICK, STICKY_PISTON("PISTON_BASE", "PISTON_STICKY_BASE"), STONE, STONECUTTER("1.14"), STONE_AXE, STONE_BRICKS("SMOOTH_BRICK"), STONE_BRICK_SLAB(4, "DOUBLE_STEP", "STEP", "STONE_SLAB"), STONE_BRICK_STAIRS("SMOOTH_STAIRS"), STONE_BRICK_WALL, STONE_BUTTON, STONE_HOE, STONE_PICKAXE, STONE_PRESSURE_PLATE("STONE_PLATE"), STONE_SHOVEL("STONE_SPADE"), STONE_SLAB("DOUBLE_STEP", "STEP"), STONE_STAIRS, STONE_SWORD, STRAY_SPAWN_EGG(6, "MONSTER_EGG"), STRING, STRIPPED_ACACIA_LOG("LOG_2"), STRIPPED_ACACIA_WOOD("LOG_2"), STRIPPED_BIRCH_LOG(2, "LOG"), STRIPPED_BIRCH_WOOD(2, "LOG"), STRIPPED_CRIMSON_HYPHAE("1.16"), STRIPPED_CRIMSON_STEM("1.16"), STRIPPED_DARK_OAK_LOG("LOG"), STRIPPED_DARK_OAK_WOOD("LOG"), STRIPPED_JUNGLE_LOG(3, "LOG"), STRIPPED_JUNGLE_WOOD(3, "LOG"), STRIPPED_OAK_LOG("LOG"), STRIPPED_OAK_WOOD("LOG"), STRIPPED_SPRUCE_LOG(1, "LOG"), STRIPPED_SPRUCE_WOOD(1, "LOG"), STRIPPED_WARPED_HYPHAE("1.16"), STRIPPED_WARPED_STEM("1.16"), STRUCTURE_BLOCK, /** * Originally developers used barrier blocks for its purpose. * 1.10 will be parsed as 1.9 version. */ STRUCTURE_VOID("1.10", "BARRIER"), SUGAR, SUGAR_CANE("SUGAR_CANE_BLOCK"), SUNFLOWER("DOUBLE_PLANT"), SUSPICIOUS_STEW("1.14", "MUSHROOM_STEW"), SWEET_BERRIES("1.14"), SWEET_BERRY_BUSH("1.14", "GRASS"), TALL_GRASS(2, "DOUBLE_PLANT"), TALL_SEAGRASS(2, "1.13", "TALL_GRASS"), TARGET("1.16"), TERRACOTTA("HARD_CLAY"), TIPPED_ARROW("1.9", "ARROW"), TNT, TNT_MINECART("EXPLOSIVE_MINECART"), TORCH, TOTEM_OF_UNDYING("TOTEM"), TRADER_LLAMA_SPAWN_EGG(103, "1.14", "MONSTER_EGG"), TRAPPED_CHEST, TRIDENT("1.13"), TRIPWIRE, TRIPWIRE_HOOK, TROPICAL_FISH(2, "RAW_FISH"), TROPICAL_FISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), TROPICAL_FISH_SPAWN_EGG("1.13", "MONSTER_EGG"), TUBE_CORAL("1.13"), TUBE_CORAL_BLOCK("1.13"), TUBE_CORAL_FAN("1.13"), TUBE_CORAL_WALL_FAN, TURTLE_EGG("1.13", "EGG"), TURTLE_HELMET("1.13", "IRON_HELMET"), TURTLE_SPAWN_EGG("1.13", "CHICKEN_SPAWN_EGG"), TWISTING_VINES("1.16"), TWISTING_VINES_PLANT("1.16"), VEX_SPAWN_EGG(35, "MONSTER_EGG"), VILLAGER_SPAWN_EGG(120, "MONSTER_EGG"), VINDICATOR_SPAWN_EGG(36, "MONSTER_EGG"), VINE, /** * 1.13 tag is not added because it's the same thing as {@link #AIR} * * @see #CAVE_AIR */ VOID_AIR("AIR"), WALL_TORCH("TORCH"), WANDERING_TRADER_SPAWN_EGG("1.14", "VILLAGER_SPAWN_EGG"), WARPED_BUTTON("1.16"), WARPED_DOOR("1.16"), WARPED_FENCE("1.16"), WARPED_FENCE_GATE("1.16"), WARPED_FUNGUS("1.16"), WARPED_FUNGUS_ON_A_STICK("1.16"), WARPED_HYPHAE("1.16"), WARPED_NYLIUM("1.16"), WARPED_PLANKS("1.16"), WARPED_PRESSURE_PLATE("1.16"), WARPED_ROOTS("1.16"), WARPED_SIGN("1.16"), WARPED_SLAB("1.16"), WARPED_STAIRS("1.16"), WARPED_STEM("1.16"), WARPED_TRAPDOOR("1.16"), WARPED_WALL_SIGN("1.16"), WARPED_WART_BLOCK("1.16"), /** * This is used for blocks only. * In 1.13- WATER will turn into STATIONARY_WATER after it finished spreading. * After 1.13+ this uses * https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/data/Levelled.html water flowing system. * Use XBlock for this instead. */ WATER("STATIONARY_WATER"), WATER_BUCKET, WEEPING_VINES("1.16"), WEEPING_VINES_PLANT("1.16"), WET_SPONGE(1, "SPONGE"), WHEAT("CROPS"), WHEAT_SEEDS("SEEDS"), WHITE_BANNER(15, "STANDING_BANNER", "BANNER"), WHITE_BED("BED_BLOCK", "BED"), WHITE_CARPET("CARPET"), WHITE_CONCRETE("CONCRETE"), WHITE_CONCRETE_POWDER("CONCRETE_POWDER"), WHITE_DYE(15, "1.14", "INK_SACK", "BONE_MEAL"), WHITE_GLAZED_TERRACOTTA("1.12", "HARD_CLAY", "STAINED_CLAY"), WHITE_SHULKER_BOX, WHITE_STAINED_GLASS("STAINED_GLASS"), WHITE_STAINED_GLASS_PANE("THIN_GLASS", "STAINED_GLASS_PANE"), WHITE_TERRACOTTA("HARD_CLAY", "STAINED_CLAY", "TERRACOTTA"), WHITE_TULIP(6, "RED_ROSE"), WHITE_WALL_BANNER(15, "WALL_BANNER"), WHITE_WOOL("WOOL"), WITCH_SPAWN_EGG(66, "MONSTER_EGG"), WITHER_ROSE("1.14", "BLACK_DYE"), WITHER_SKELETON_SKULL(1, "SKULL", "SKULL_ITEM"), WITHER_SKELETON_SPAWN_EGG(5, "MONSTER_EGG"), WITHER_SKELETON_WALL_SKULL(1, "SKULL", "SKULL_ITEM"), WOLF_SPAWN_EGG(95, "MONSTER_EGG"), WOODEN_AXE("WOOD_AXE"), WOODEN_HOE("WOOD_HOE"), WOODEN_PICKAXE("WOOD_PICKAXE"), WOODEN_SHOVEL("WOOD_SPADE"), WOODEN_SWORD("WOOD_SWORD"), WRITABLE_BOOK("BOOK_AND_QUILL"), WRITTEN_BOOK, YELLOW_BANNER(11, "STANDING_BANNER", "BANNER"), YELLOW_BED(4, "1.12", "BED_BLOCK", "BED"), YELLOW_CARPET(4, "CARPET"), YELLOW_CONCRETE(4, "CONCRETE"), YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"), YELLOW_DYE(11, "INK_SACK", "DANDELION_YELLOW"), YELLOW_GLAZED_TERRACOTTA(4, "1.12", "HARD_CLAY", "STAINED_CLAY", "YELLOW_TERRACOTTA"), YELLOW_SHULKER_BOX, YELLOW_STAINED_GLASS(4, "STAINED_GLASS"), YELLOW_STAINED_GLASS_PANE(4, "THIN_GLASS", "STAINED_GLASS_PANE"), YELLOW_TERRACOTTA(4, "HARD_CLAY", "STAINED_CLAY"), YELLOW_WALL_BANNER(11, "WALL_BANNER"), YELLOW_WOOL(4, "WOOL"), ZOMBIE_HEAD(2, "SKULL", "SKULL_ITEM"), ZOMBIE_HORSE_SPAWN_EGG(29, "MONSTER_EGG"), ZOMBIE_PIGMAN_SPAWN_EGG(57, "MONSTER_EGG"), ZOMBIE_SPAWN_EGG(54, "MONSTER_EGG"), ZOMBIE_VILLAGER_SPAWN_EGG(27, "MONSTER_EGG"), ZOMBIE_WALL_HEAD(2, "SKULL", "SKULL_ITEM"), ZOMBIFIED_PIGLIN_SPAWN_EGG(54, "MONSTER_EGG"); /** * An immutable cached set of {@link Material#values()} to avoid allocating memory for * calling the method every time. * * @since 2.0.0 */ public static final EnumSet<Material> VALUES = EnumSet.allOf(Material.class); /** * A set of material names that can be damaged. * <p> * Most of the names are not complete as this list is intended to be * checked with {@link String#contains} for memory usage. * * @since 1.0.0 */ private static final ImmutableSet<String> DAMAGEABLE = ImmutableSet.of( "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", "CARROT_ON_A_STICK", "CARROT_STICK", "SPADE", "SHIELD" ); /** * <b>Material Paradox (Duplication Check)</b> * <p> * A map of duplicated material names in 1.13 and 1.12 that will conflict with the legacy names. * Values are the new material names. * <br> * Duplicates are normally only checked by keys, not values. * * @since 3.0.0 */ @SuppressWarnings("UnstableApiUsage") private static final ImmutableMap<Material, Material> DUPLICATED = Maps.immutableEnumMap(ImmutableMap.<Material, Material>builder() .put(MELON, MELON_SLICE) .put(CARROT, CARROTS) .put(POTATO, POTATOES) .put(BEETROOT, BEETROOTS) .put(BRICK, BRICKS) .put(MAP, FILLED_MAP) .put(NETHER_BRICK, NETHER_BRICKS) .put(ACACIA_DOOR, ACACIA_DOOR) .put(BIRCH_DOOR, BIRCH_DOOR) .put(DARK_OAK_DOOR, DARK_OAK_DOOR) .put(JUNGLE_DOOR, JUNGLE_DOOR) .put(SPRUCE_DOOR, SPRUCE_DOOR) .put(OAK_DOOR, OAK_DOOR) .put(BREWING_STAND, BREWING_STAND) .put(CAULDRON, CAULDRON) .put(FLOWER_POT, FLOWER_POT) .put(FARMLAND, FARMLAND) .build() ); /** * A set of all the legacy names without duplicates. * <p> * REMOVE THIS IF YOU DON'T NEED IT. * It'll help to free up a lot of memory. * * @see #containsLegacy(String) * @since 2.2.0 */ private static final ImmutableSet<String> LEGACY_VALUES = VALUES.stream().map(Material::getLegacy) .flatMap(Arrays::stream) .filter(m -> m.charAt(1) == '.') .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf)); /** * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. * For strings that match a certain Material. Mostly cached for configs. * * @since 1.0.0 */ private static final Cache<String, Material> NAME_CACHE = CacheBuilder.newBuilder() .softValues() .expireAfterAccess(15, TimeUnit.MINUTES) .build(); /** * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. * For Materials that are already parsed once. * * @since 3.0.0 */ private static final Cache<Material, org.bukkit.Material> PARSED_CACHE = CacheBuilder.newBuilder() .softValues() .expireAfterAccess(10, TimeUnit.MINUTES) .concurrencyLevel(Runtime.getRuntime().availableProcessors()) .build(); /** * Pre-compiled RegEx pattern. * Include both replacements to avoid recreating string multiple times with multiple RegEx checks. * * @since 3.0.0 */ private static final Pattern FORMAT_PATTERN = Pattern.compile("\\W+"); /** * The current version of the server in the a form of a major version. * * @since 1.0.0 */ private static final int VERSION = NumberUtils.toInt(getMajorVersion(ServerVersion.getBukkitVersion()).substring(2)); /** * Cached result if the server version is after the v1.13 flattening update. * Please don't mistake this with flat-chested people. It happened. * * @since 3.0.0 */ private static final boolean ISFLAT = supports(13); /** * The data value of this material https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening * * @see #getData() */ private final byte data; /** * A list of material names that was being used for older verions. * * @see #getLegacy() */ private final String[] legacy; Material(int data, String... legacy) { this.data = (byte) data; this.legacy = legacy; } Material() { this(0); } Material(String... legacy) { this(0, legacy); } /** * Checks if the version is 1.13 Aquatic Update or higher. * An invocation of this method yields the cached result from the expression: * <p> * <blockquote> * {@link #supports(int 13)}} * </blockquote> * * @return true if 1.13 or higher. * @see #getVersion() * @see #supports(int) * @since 1.0.0 */ public static boolean isNewVersion() { return ISFLAT; } /** * This is just an extra method that method that can be used for many cases. * It can be used in {@link org.bukkit.event.player.PlayerInteractEvent} * or when accessing {@link org.bukkit.entity.Player#getMainHand()}, * or other compatibility related methods. * <p> * An invocation of this method yields exactly the same result as the expression: * <p> * <blockquote> * {@link #getVersion()} == 1.8 * </blockquote> * * @since 2.0.0 */ public static boolean isOneEight() { return !supports(9); } /** * The current version of the server. * * @return the current server version or 0.0 if unknown. * @see #isNewVersion() * @since 2.0.0 */ public static double getVersion() { return VERSION; } /** * When using newer versions of Minecraft ({@link #isNewVersion()}), helps * to find the old material name with its data value using a cached search for optimization. * * @see #matchDefinedMaterial(String, byte) * @since 1.0.0 */ @Nullable private static Material requestOldMaterial(@Nonnull String name, byte data) { String holder = name + data; Material material = NAME_CACHE.getIfPresent(holder); if (material != null) return material; for (Material materials : VALUES) { if ((data == -1 || data == materials.data) && materials.anyMatchLegacy(name)) { NAME_CACHE.put(holder, materials); return materials; } } return null; } /** * Checks if Material enum contains a material with the given name. * <p> * You should use {@link #matchMaterial(String)} instead if you're going * to get the Material object after checking if it's available in the list * by doing a simple {@link Optional#isPresent()} check. * This is just to avoid multiple loops for maximum performance. * * @param name name of the material. * @return true if Material enum has this material. * @see #containsLegacy(String) * @since 1.0.0 */ public static boolean contains(@Nonnull String name) { Validate.notEmpty(name, "Cannot check for null or empty material name"); name = format(name); for (Material materials : VALUES) if (materials.name().equals(name)) return true; return false; } /** * Checks if the given material matches any of the available legacy names. * Changed names between the {@code 1.9} and {@code 1.12} versions are not supported (there are only a few anyway). * * @param name the material name. * @return true if it's a legacy name. * @see #contains(String) * @see #anyMatchLegacy(String) * @since 2.0.0 */ public static boolean containsLegacy(@Nonnull String name) { Validate.notEmpty(name, "Cannot check legacy names for null or empty material name"); return LEGACY_VALUES.contains(format(name)); } /** * Parses the given material name as an Material with unspecified data value. * * @see #matchMaterial(String, byte) * @since 2.0.0 */ @Nonnull public static Optional<Material> matchMaterial(@Nonnull String name) { Optional<Material> material = matchMaterial(name, (byte) 0); if (material.isPresent()) { return material; } return matchMaterial(name, (byte) -1); } /** * Parses the given material name as an Material. * Can also be used like: <b>MATERIAL:DATA</b> * <p> * <b>Examples</b> * <pre> * INK_SACK:1 -> RED_DYE * WOOL, 14 -> RED_WOOL * </pre> * * @see #matchDefinedMaterial(String, byte) * @see #matchMaterial(ItemStack) * @since 2.0.0 */ @Nonnull public static Optional<Material> matchMaterial(@Nonnull String name, byte data) { Validate.notEmpty(name, "Cannot match a material with null or empty material name"); Optional<Material> oldMatch = matchMaterialWithData(name); if (oldMatch.isPresent()) return oldMatch; // -1 Determines whether the item's data value is unknown and only the name is given. // Checking if the item is damageable won't do anything as the data is not going to be checked in requestOldMaterial anyway. return matchDefinedMaterial(format(name), data); } /** * Parses material name and data value from the specified string. * The seperators are: <b>, or :</b> * Spaces are allowed. Mostly used when getting materials from config for old school minecrafters. * <p> * <b>Examples</b> * <p><pre> * INK_SACK:1 -> RED_DYE * WOOL, 14 -> RED_WOOL * </pre> * * @param name the material string that consists of the material name, data and separator character. * @return the parsed Material. * @see #matchMaterial(String) * @since 3.0.0 */ private static Optional<Material> matchMaterialWithData(String name) { for (char separator : new char[]{',', ':'}) { int index = name.indexOf(separator); if (index == -1) continue; String mat = format(name.substring(0, index)); byte data = Byte.parseByte(StringUtils.deleteWhitespace(name.substring(index + 1))); return matchDefinedMaterial(mat, data); } return Optional.empty(); } /** * Parses the given material as an Material. * * @throws IllegalArgumentException may be thrown as an unexpected exception. * @see #matchDefinedMaterial(String, byte) * @see #matchMaterial(ItemStack) * @since 2.0.0 */ @Nonnull public static Material matchMaterial(@Nonnull org.bukkit.Material material) { Objects.requireNonNull(material, "Cannot match null material"); return matchDefinedMaterial(material.name(), (byte) -1) .orElseThrow(() -> new IllegalArgumentException("Unsupported Material: " + material)); } /** * Parses the given item as an Material using its material and data value (durability). * * @param item the ItemStack to match. * @return an Material if matched any. * @throws IllegalArgumentException may be thrown as an unexpected exception. * @see #matchDefinedMaterial(String, byte) * @since 2.0.0 */ @Nonnull @SuppressWarnings("deprecation") public static Material matchMaterial(@Nonnull ItemStack item) { Objects.requireNonNull(item, "Cannot match null ItemStack"); String material = item.getType().name(); return matchDefinedMaterial(material, isDamageable(material) ? (byte) 0 : (byte) item.getDurability()) .orElseThrow(() -> new IllegalArgumentException("Unsupported Material: " + material)); } /** * Parses the given material name and data value as an Material. * All the values passed to this method will not be null or empty and are formatted correctly. * * @param name the formatted name of the material. * @param data the data value of the material. * @return an Material (with the same data value if specified) * @see #matchMaterial(String, byte) * @see #matchMaterial(org.bukkit.Material) * @see #matchMaterial(int, byte) * @see #matchMaterial(ItemStack) * @since 3.0.0 */ @Nonnull private static Optional<Material> matchDefinedMaterial(@Nonnull String name, byte data) { boolean duplicated = isDuplicated(name); // Do basic number and boolean checks before accessing more complex enum stuff. // Maybe we can simplify (ISFLAT || !duplicated) with the (!ISFLAT && duplicated) under it to save a few nanoseconds? // if (!Boolean.valueOf(Boolean.getBoolean(Boolean.TRUE.toString())).equals(Boolean.FALSE.booleanValue())) return null; if (data <= 0 && (ISFLAT || !duplicated)) { // Apparently the transform method is more efficient than toJavaUtil() // toJavaUtil isn't even supported in older versions. Optional<Material> xMat = Enums.getIfPresent(Material.class, name).transform(Optional::of).or(Optional.empty()); if (xMat.isPresent()) return xMat; } // Material Paradox (Duplication Check) // I've concluded that this is just an infinite loop that keeps // going around the Singular Form and the Plural Form materials. A waste of brain cells and a waste of time. // This solution works just fine anyway. if (!ISFLAT && duplicated) return Optional.ofNullable(requestDuplicatedMaterial(name, data)); return Optional.ofNullable(requestOldMaterial(name, data)); } /** * <b>Material Paradox (Duplication Check)</b> * Checks if the material has any duplicates. * <p> * <b>Example:</b> * <p>{@code MELON, CARROT, POTATO, BEETROOT -> true} * * @param name the name of the material to check. * @return true if there's a duplicated material for this material, otherwise false. * @see #isDuplicated() * @since 2.0.0 */ public static boolean isDuplicated(@Nonnull String name) { Validate.notEmpty(name, "Cannot check duplication for null or empty material name"); name = format(name); // Don't use matchMaterial() since this method is being called from matchMaterial() itself and will cause a StackOverflowError. for (Map.Entry<Material, Material> duplicated : DUPLICATED.entrySet()) if (duplicated.getKey().name().equals(name) || duplicated.getKey().anyMatchLegacy(name)) return true; return false; } /** * Gets the Material based on the material's ID (Magic Value) and data value.<br> * You should avoid using this for performance issues. * * @param id the ID (Magic value) of the material. * @param data the data value of the material. * @return a parsed Material with the same ID and data value. * @see #matchMaterial(ItemStack) * @since 2.0.0 */ @Nonnull public static Optional<Material> matchMaterial(int id, byte data) { if (id < 0 || data < 0) return Optional.empty(); // Looping through Material.values() will take longer. for (Material materials : VALUES) if (materials.data == data && materials.getId() == id) return Optional.of(materials); return Optional.empty(); } /** * A solution for <b>Material Paradox</b>. * Manually parses the duplicated materials to find the exact material based on the server version. * * @param name the name of the material. * @return the duplicated Material based on the version. * @throws IllegalArgumentException may be thrown. If thrown, it's a bug. * @since 2.0.0 */ @Nullable private static Material requestDuplicatedMaterial(@Nonnull String name, byte data) { Material mat = requestOldMaterial(name, data); // If ends with "S" -> Plural Form Material return mat.name().charAt(mat.name().length() - 1) == 'S' ? Enums.getIfPresent(Material.class, name).orNull() : mat; } /** * Always returns the value with the given duplicated material key name. * * @param name the name of the material. * @return the new Material of this duplicated material. * @see #getMaterialIfDuplicated(String) * @since 2.0.0 */ @Nonnull public static Optional<Material> getNewMaterialIfDuplicated(@Nonnull String name) { Validate.notEmpty(name, "Cannot get new duplicated material for null or empty material name"); name = format(name); for (Map.Entry<Material, Material> duplicated : DUPLICATED.entrySet()) if (duplicated.getKey().name().equals(name)) return Optional.of(duplicated.getKey()); return Optional.empty(); } /** * Checks if the item is duplicated for a different purpose in new versions from {@link #DUPLICATED}. * * @param name the name of the material. * @return the other Material (key or value) of the Material (key or value). * @see #matchMaterial(String, byte) * @since 2.0.0 */ @Nullable public static Material getMaterialIfDuplicated(@Nonnull String name) { Validate.notEmpty(name, "Cannot get duplicated material for null or empty material name"); name = format(name); for (Map.Entry<Material, Material> duplicated : DUPLICATED.entrySet()) if (duplicated.getKey().name().equals(name)) return duplicated.getValue(); else if (duplicated.getValue().name().equals(name)) return duplicated.getKey(); return null; } /** * Attempts to build the string like an enum name. * Removes all the spaces, numbers and extra non-English characters. Also removes some config/in-game based strings. * * @param name the material name to modify. * @return a Material enum name. * @since 2.0.0 */ @Nonnull private static String format(@Nonnull String name) { return FORMAT_PATTERN.matcher( name.trim().replace('-', '_').replace(' ', '_')).replaceAll("").toUpperCase(Locale.ENGLISH); } /** * Parses the material name if the legacy name has a version attached to it. * * @param name the material name to parse. * @return the material name with the version removed. * @since 2.0.0 */ @Nonnull private static String parseLegacyMaterialName(String name) { int index = name.indexOf('/'); return index == -1 ? name : name.substring(0, index); } /** * Checks if the specified version is the same version or higher than the current server version. * * @param version the major version to be checked. "1." is ignored -> 1.12 = 12 | 1.9 = 9 * @return true of the version is equal or higher than the current version. * @since 2.0.0 */ public static boolean supports(int version) { return VERSION >= version; } /** * Converts the enum names to a more friendly and readable string. * * @return a formatted string. * @see #toWord(String) * @since 2.1.0 */ @Nonnull public static String toWord(@Nonnull org.bukkit.Material material) { Objects.requireNonNull(material, "Cannot translate a null material to a word"); return toWord(material.name()); } /** * Parses an enum name to a normal word. * Normal names have underlines removed and each word capitalized. * <p> * <b>Examples:</b> * <pre> * EMERALD -> Emerald * EMERALD_BLOCK -> Emerald Block * ENCHANTED_GOLDEN_APPLE -> Enchanted Golden Apple * </pre> * * @param name the name of the enum. * @return a cleaned more readable enum name. * @since 2.1.0 */ @Nonnull private static String toWord(@Nonnull String name) { return WordUtils.capitalize(name.replace('_', ' ').toLowerCase(Locale.ENGLISH)); } /** * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) * * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" * @return the exact major version. * @since 2.0.0 */ @Nonnull public static String getMajorVersion(@Nonnull String version) { Validate.notEmpty(version, "Cannot get exact major minecraft version for null or empty version"); // getBukkitVersion() if (version.contains("-R") || version.endsWith("SNAPSHOT")) version = version.substring(0, version.indexOf('-')); // getVersion() int index = version.indexOf("MC:"); if (index != -1) version = version.substring(index + 4, version.length() - 1); // 1.13.2, 1.14.4, etc... int lastDot = version.lastIndexOf('.'); if (version.indexOf('.') != lastDot) version = version.substring(0, lastDot); return version; } /** * Checks if the material can be damaged by using it. * Names going through this method are not formatted. * * @param name the name of the material. * @return true of the material can be damaged. * @see #isDamageable() * @since 1.0.0 */ public static boolean isDamageable(@Nonnull String name) { Objects.requireNonNull(name, "Material name cannot be null"); for (String damageable : DAMAGEABLE) if (name.contains(damageable)) return true; return false; } /** * Checks if the list of given material names matches the given base material. * Mostly used for configs. * <p> * Supports {@link String#contains} {@code CONTAINS:NAME} and Regular Expression {@code REGEX:PATTERN} formats. * <p> * <b>Example:</b> * <blockquote><pre> * Material material = {@link #matchMaterial(ItemStack)}; * if (material.isOneOf(plugin.getConfig().getStringList("disabled-items")) return; * </pre></blockquote> * <br> * <b>{@code CONTAINS} Examples:</b> * <pre> * "CONTAINS:CHEST" -> CHEST, ENDERCHEST, TRAPPED_CHEST -> true * "cOnTaINS:dYe" -> GREEN_DYE, YELLOW_DYE, BLUE_DYE, INK_SACK -> true * </pre> * <p> * <b>{@code REGEX} Examples</b> * <pre> * "REGEX:^.+_.+_.+$" -> Every Material with 3 underlines or more: SHULKER_SPAWN_EGG, SILVERFISH_SPAWN_EGG, SKELETON_HORSE_SPAWN_EGG * "REGEX:^.{1,3}$" -> Material names that have 3 letters only: BED, MAP, AIR * </pre> * <p> * The reason that there are tags for {@code CONTAINS} and {@code REGEX} * is for the performance. * Please avoid using the {@code REGEX} tag if you can use the {@code CONTAINS} tag. * It'll have a huge impact on performance. * Please avoid using {@code (capturing groups)} there's no use for them in this case. * If you want to use groups, use {@code (?: non-capturing groups)}. It's faster. * <p> * You can make a cache for pre-compiled RegEx patterns from your config. * It's better, but not much faster since these patterns are not that complex. * <p> * Want to learn RegEx? You can mess around in <a href="https://regexr.com/">RegExr</a> website. * * @param material the base material to match other materials with. * @param materials the material names to check base material on. * @return true if one of the given material names is similar to the base material. * @since 3.1.1 */ public static boolean isOneOf(@Nonnull org.bukkit.Material material, @Nullable List<String> materials) { if (materials == null || materials.isEmpty()) return false; Objects.requireNonNull(material, "Cannot match materials with a null material"); String name = material.name(); for (String comp : materials) { comp = comp.toUpperCase(); if (comp.startsWith("CONTAINS:")) { comp = format(comp.substring(9)); if (name.contains(comp)) return true; continue; } if (comp.startsWith("REGEX:")) { comp = comp.substring(6); if (name.matches(comp)) return true; continue; } // Direct Object Equals Optional<Material> mat = matchMaterial(comp); if (mat.isPresent() && mat.get().parseMaterial() == material) return true; } return false; } /** * Gets the version which this material was added in. * If the material doesn't have a version it'll return 0; * * @return the Minecraft version which tihs material was added in. * @since 3.0.0 */ public int getMaterialVersion() { if (this.legacy.length == 0) return 0; String version = this.legacy[0]; if (version.charAt(1) != '.') return 0; return Integer.parseInt(version.substring(2)); } /** * Sets the {@link org.bukkit.Material} (and data value on older versions) of an item. * Damageable materials will not have their durability changed. * <p> * Use {@link #parseItem()} instead when creating new ItemStacks. * * @param item the item to change its type. * @see #parseItem() * @since 3.0.0 */ @Nonnull @SuppressWarnings("deprecation") public ItemStack setType(@Nonnull ItemStack item) { Objects.requireNonNull(item, "Cannot set material for null ItemStack"); item.setType(this.parseMaterial()); if (!ISFLAT && !this.isDamageable()) item.setDurability(this.data); return item; } /** * Checks if the list of given material names matches the given base material. * Mostly used for configs. * * @param materials the material names to check base material on. * @return true if one of the given material names is similar to the base material. * @see #isOneOf(org.bukkit.Material, List) * @since 3.0.0 */ public boolean isOneOf(@Nullable List<String> materials) { org.bukkit.Material material = this.parseMaterial(); if (material == null) return false; return isOneOf(material, materials); } /** * Checks if the given string matches any of this material's legacy material names. * All the values passed to this method will not be null or empty and are formatted correctly. * * @param name the name to check * @return true if it's one of the legacy names. * @see #containsLegacy(String) * @since 2.0.0 */ private boolean anyMatchLegacy(@Nonnull String name) { // If it's a new material, everything after this is a suggestion. // At least until now except one or two materials. if (this.isNew()) return false; for (String legacy : this.legacy) if (parseLegacyMaterialName(legacy).equals(name)) return true; return false; } /** * User-friendly readable name for this material * In most cases you should be using {@link #name()} instead. * * @return string of this object. * @see #toWord(String) * @since 3.0.0 */ @Override public String toString() { return toWord(this.name()); } /** * Gets the ID (Magic value) of the material. * * @return the ID of the material or <b>-1</b> if it's a new block or the material is not supported. * @see #matchMaterial(int, byte) * @since 2.2.0 */ @SuppressWarnings("deprecation") public int getId() { if (this.isNew()) return -1; org.bukkit.Material material = this.parseMaterial(); return material == null ? -1 : material.getId(); } /** * Checks if the material has any duplicates. * * @return true if there is a duplicated name for this material, otherwise false. * @see #getMaterialIfDuplicated() * @see #isDuplicated(String) * @since 2.0.0 */ public boolean isDuplicated() { return DUPLICATED.containsKey(this); } /** * Checks if the item is duplicated for a different purpose in new versions. * * @return true if the item's name is duplicated, otherwise false. * @see #isDuplicated() * @see #getNewMaterialIfDuplicated(String) * @since 2.0.0 */ @Nullable public Material getMaterialIfDuplicated() { return DUPLICATED.get(this); } /** * Checks if the material can be damaged by using it. * Names going through this method are not formatted. * * @return true if the item can be damaged (have its durability changed), otherwise false. * @see #isDamageable(String) * @since 1.0.0 */ public boolean isDamageable() { return isDamageable(this.name()); } /** * The data value of this material <a href="https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening">pre-flattening</a>. * <p> * Can be accessed with {@link ItemStack#getData()} then {@code MaterialData#getData()} * or {@link ItemStack#getDurability()} if not damageable. * * @return data of this material, or 0 if none. * @since 1.0.0 */ @SuppressWarnings("deprecation") public byte getData() { return data; } /** * Get a list of materials names that was previously used by older versions. * If the material was added in a new version {@link #isNewVersion()}, * then the first element will indicate which version the material was added in. * * @return a list of legacy material names and the first element as the version the material was added in if new. * @since 1.0.0 */ @Nonnull public String[] getLegacy() { return legacy; } /** * Parses an item from this Material. * Uses data values on older versions. * * @return an ItemStack with the same material (and data value if in older versions.) * @see #parseItem(boolean) * @see #setType(ItemStack) * @since 1.0.0 */ @Nullable public ItemStack parseItem() { return parseItem(true); } /** * Parses an item from this Material. * Uses data values on older versions. * * @param suggest if true {@link #parseMaterial(boolean true)} will be used. * @return an ItemStack with the same material (and data value if in older versions.) * @see #setType(ItemStack) * @since 2.0.0 */ @Nullable @SuppressWarnings("deprecation") public ItemStack parseItem(boolean suggest) { org.bukkit.Material material = this.parseMaterial(suggest); if (material == null) return null; return ISFLAT ? new ItemStack(material) : new ItemStack(material, 1, this.data); } /** * Parses the material of this Material. * * @return the material related to this Material based on the server version. * @see #parseMaterial(boolean) * @since 1.0.0 */ @Nullable public org.bukkit.Material parseMaterial() { return parseMaterial(true); } /** * Parses the material of this Material and accepts suggestions. * * @param suggest use a suggested material (from older materials) if the material is added in a later version of Minecraft. * @return the material related to this Material based on the server version. * @see #matchMaterial(String, byte) * @since 2.0.0 */ @Nullable public org.bukkit.Material parseMaterial(boolean suggest) { org.bukkit.Material mat = PARSED_CACHE.getIfPresent(this); if (mat != null) return mat; if (!ISFLAT && this.isDuplicated()) mat = requestOldMaterial(suggest); else { mat = org.bukkit.Material.getMaterial(this.name()); if (mat == null) mat = requestOldMaterial(suggest); } if (mat != null) PARSED_CACHE.put(this, mat); return mat; } /** * Parses a material for older versions of Minecraft. * Accepts suggestions if specified. * * @param suggest if true suggested materials will be considered for old versions. * @return a parsed material suitable for the current Minecraft version. * @see #parseMaterial(boolean) * @since 2.0.0 */ @Nullable private org.bukkit.Material requestOldMaterial(boolean suggest) { boolean noMaterialParse = this.isNew() && !suggest; org.bukkit.Material material; for (int i = this.legacy.length - 1; i >= 0; i--) { String legacy = this.legacy[i]; // Slash means it's just another name for the material in another version. int index = legacy.indexOf('/'); if (index != -1) { legacy = legacy.substring(0, index); material = org.bukkit.Material.getMaterial(legacy); if (material != null) return material; else continue; } // According to the suggestion format list, all the other names continuing // from here are considered as a "suggestion" if there's no slash anymore. // But continue if it's not even a new material. if (noMaterialParse) return null; material = org.bukkit.Material.getMaterial(legacy); if (material != null) return material; } return null; } /** * Checks if an item has the same material (and data value on older versions). * * @param item item to check. * @return true if the material is the same as the item's material (and data value if on older versions), otherwise false. * @since 1.0.0 */ @SuppressWarnings("deprecation") public boolean isSimilar(@Nonnull ItemStack item) { Objects.requireNonNull(item, "Cannot compare with null ItemStack"); if (item.getType() != this.parseMaterial()) return false; return (ISFLAT || this.isDamageable()) || item.getDurability() == this.data; } /** * Gets the suggested material names that can be used * if the material is not supported in the current version. * * @return a list of suggested material names. * @see #parseMaterial(boolean) * @since 2.0.0 */ @Nonnull public List<String> getSuggestions() { return this.isNew() ? Arrays.stream(this.legacy).skip(1).collect(Collectors.toList()) : new ArrayList<>(); } /** * Checks if this material is supported in the current version. * Suggested materials will be ignored. * <p> * Note that you should use {@link #parseMaterial()} and check if it's null * if you're going to parse and use the material later. * * @return true if the material exists in {@link org.bukkit.Material} list. * @see #isNew() * @since 2.0.0 */ public boolean isSupported() { int version = this.getMaterialVersion(); if (version != 0) return supports(version); org.bukkit.Material material = org.bukkit.Material.getMaterial(this.name()); if (material == null) { for (int i = this.legacy.length - 1; i != -1; i--) { String legacy = this.legacy[i]; if (StringUtils.contains(legacy, '/')) continue; material = org.bukkit.Material.getMaterial(legacy); if (material != null) break; } } return material != null; } /** * Checks if the material is newly added after the 1.13 Aquatic Update * * @return true if the material was newly added, otherwise false. * @see #getMaterialVersion() * @since 2.0.0 */ public boolean isNew() { return this.legacy.length != 0 && this.legacy[0].charAt(1) == '.'; } /** * Checks if this Material is an obtainable item. * * @return true if this material is an item */ public boolean isItem() { switch (this) { //<editor-fold defaultstate="collapsed" desc="isItem"> case ACACIA_WALL_SIGN: case ATTACHED_MELON_STEM: case ATTACHED_PUMPKIN_STEM: case BAMBOO_SAPLING: case BEETROOTS: case BIRCH_WALL_SIGN: case BLACK_WALL_BANNER: case BLUE_WALL_BANNER: case BRAIN_CORAL_WALL_FAN: case BROWN_WALL_BANNER: case BUBBLE_COLUMN: case BUBBLE_CORAL_WALL_FAN: case CARROTS: case CAVE_AIR: case COCOA: case CREEPER_WALL_HEAD: case CYAN_WALL_BANNER: case DARK_OAK_WALL_SIGN: case DEAD_BRAIN_CORAL_WALL_FAN: case DEAD_BUBBLE_CORAL_WALL_FAN: case DEAD_FIRE_CORAL_WALL_FAN: case DEAD_HORN_CORAL_WALL_FAN: case DEAD_TUBE_CORAL_WALL_FAN: case DRAGON_WALL_HEAD: case END_GATEWAY: case END_PORTAL: case FIRE: case FIRE_CORAL_WALL_FAN: case FROSTED_ICE: case GRAY_WALL_BANNER: case GREEN_WALL_BANNER: case HORN_CORAL_WALL_FAN: case JUNGLE_WALL_SIGN: case KELP_PLANT: case LAVA: case LIGHT_BLUE_WALL_BANNER: case LIGHT_GRAY_WALL_BANNER: case LIME_WALL_BANNER: case MAGENTA_WALL_BANNER: case MELON_STEM: case MOVING_PISTON: case NETHER_PORTAL: case OAK_WALL_SIGN: case ORANGE_WALL_BANNER: case PINK_WALL_BANNER: case PISTON_HEAD: case PLAYER_WALL_HEAD: case POTATOES: case POTTED_ACACIA_SAPLING: case POTTED_ALLIUM: case POTTED_AZURE_BLUET: case POTTED_BAMBOO: case POTTED_BIRCH_SAPLING: case POTTED_BLUE_ORCHID: case POTTED_BROWN_MUSHROOM: case POTTED_CACTUS: case POTTED_CORNFLOWER: case POTTED_DANDELION: case POTTED_DARK_OAK_SAPLING: case POTTED_DEAD_BUSH: case POTTED_FERN: case POTTED_JUNGLE_SAPLING: case POTTED_LILY_OF_THE_VALLEY: case POTTED_OAK_SAPLING: case POTTED_ORANGE_TULIP: case POTTED_OXEYE_DAISY: case POTTED_PINK_TULIP: case POTTED_POPPY: case POTTED_RED_MUSHROOM: case POTTED_RED_TULIP: case POTTED_SPRUCE_SAPLING: case POTTED_WHITE_TULIP: case POTTED_WITHER_ROSE: case PUMPKIN_STEM: case PURPLE_WALL_BANNER: case REDSTONE_WALL_TORCH: case REDSTONE_WIRE: case RED_WALL_BANNER: case SKELETON_WALL_SKULL: case SPRUCE_WALL_SIGN: case SWEET_BERRY_BUSH: case TALL_SEAGRASS: case TRIPWIRE: case TUBE_CORAL_WALL_FAN: case VOID_AIR: case WALL_TORCH: case WATER: case WHITE_WALL_BANNER: case WITHER_SKELETON_WALL_SKULL: case YELLOW_WALL_BANNER: case ZOMBIE_WALL_HEAD: //</editor-fold> return false; default: return true; } } }
80,464
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
StainedGlass.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/StainedGlass.java
package me.patothebest.gamecore.itemstack; import me.patothebest.gamecore.util.Utils; import org.bukkit.inventory.ItemStack; public class StainedGlass { public static final ItemStack WHITE = Material.WHITE_STAINED_GLASS.parseItem(); public static final ItemStack ORANGE = Material.ORANGE_STAINED_GLASS.parseItem(); public static final ItemStack MAGENTA = Material.MAGENTA_STAINED_GLASS.parseItem(); public static final ItemStack LIGHT_BLUE = Material.LIGHT_BLUE_STAINED_GLASS.parseItem(); public static final ItemStack YELLOW = Material.YELLOW_STAINED_GLASS.parseItem(); public static final ItemStack LIME = Material.LIME_STAINED_GLASS.parseItem(); public static final ItemStack PINK = Material.PINK_STAINED_GLASS.parseItem(); public static final ItemStack GRAY = Material.GRAY_STAINED_GLASS.parseItem(); public static final ItemStack LIGHT_GRAY = Material.LIGHT_GRAY_STAINED_GLASS.parseItem(); public static final ItemStack CYAN = Material.CYAN_STAINED_GLASS.parseItem(); public static final ItemStack PURPLE = Material.PURPLE_STAINED_GLASS.parseItem(); public static final ItemStack BLUE = Material.BLUE_STAINED_GLASS.parseItem(); public static final ItemStack BROWN = Material.BROWN_STAINED_GLASS.parseItem(); public static final ItemStack GREEN = Material.GREEN_STAINED_GLASS.parseItem(); public static final ItemStack RED = Material.RED_STAINED_GLASS.parseItem(); public static final ItemStack BLACK = Material.BLACK_STAINED_GLASS.parseItem(); public static ItemStack getRandom() { switch (Utils.randInt(0, 15)) { case 0: return WHITE; case 1: return ORANGE; case 2: return MAGENTA; case 3: return LIGHT_BLUE; case 4: return YELLOW; case 5: return LIME; case 6: return PINK; case 7: return GRAY; case 8: return LIGHT_GRAY; case 9: return CYAN; case 10: return PURPLE; case 11: return BLUE; case 12: return BROWN; case 13: return GREEN; case 14: return RED; case 15: return BLACK; } return WHITE; } }
2,454
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ItemStackBuilder.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/ItemStackBuilder.java
package me.patothebest.gamecore.itemstack; import com.google.common.base.Strings; import com.google.common.collect.Lists; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.player.IPlayer; import me.patothebest.gamecore.util.EnchantGlow; import me.patothebest.gamecore.util.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * The ItemStackBuilder. */ public class ItemStackBuilder extends ItemStack { private static final boolean ISFLAT = Material.isNewVersion(); /** * Instantiates a new item stack builder with no material. */ public ItemStackBuilder() { this(org.bukkit.Material.QUARTZ); } /** * Instantiates a new item stack builder. * * @param material the material */ public ItemStackBuilder(org.bukkit.Material material) { super(material); } public ItemStackBuilder(Material material) { super(material.parseMaterial(true)); material(material); } /** * Instantiates a new item stack builder copying all the * attributes from another itemstack. * * @param itemStack the item stack */ public ItemStackBuilder(ItemStack itemStack) { setData(itemStack.getData()); data(itemStack.getDurability()); setAmount(itemStack.getAmount()); setType(itemStack.getType()); setItemMeta(itemStack.getItemMeta()); } /** * Instantiates a new item stack builder copying attributes from * another itemstack, everything except the item meta. * * @param itemStack the item stack */ public ItemStackBuilder(ItemStack itemStack, Object n) { setData(itemStack.getData()); data(itemStack.getDurability()); setAmount(itemStack.getAmount()); setType(itemStack.getType()); } /** * Sets the itemstack material. * * @param material the material * @return the item stack builder */ public ItemStackBuilder material(org.bukkit.Material material) { setType(material); return this; } /** * Sets the itemstack material. * * @param material the material * @return the item stack builder */ public ItemStackBuilder material(Material material) { setType(material.parseMaterial(true)); if (!Material.isNewVersion()) { data(material.getData()); } return this; } /** * Adds the specified amount to the itemstack amount. * * @param change the amount to add * @return the item stack builder */ public ItemStackBuilder addAmount(int change) { setAmount(getAmount() + change); return this; } /** * Sets the itemstack amount * * @param amount the amount * @return the item stack builder */ public ItemStackBuilder amount(int amount) { setAmount(amount); return this; } /** * Data. * * @param data the data * @return the item stack builder */ @Deprecated public ItemStackBuilder data(short data) { setDurability(data); return this; } /** * Data. * * @param data the data * @return the item stack builder */ @Deprecated public ItemStackBuilder data(MaterialData data) { setData(data); return this; } @SuppressWarnings("ConstantConditions") public ItemStackBuilder color(DyeColor color) { if (ISFLAT) { String type = getType().name(); if (type.endsWith("WOOL")) setType(org.bukkit.Material.getMaterial(color.name() + "_WOOL")); else if (type.endsWith("BED")) setType(org.bukkit.Material.getMaterial(color.name() + "_BED")); else if (type.endsWith("STAINED_GLASS")) setType(org.bukkit.Material.getMaterial(color.name() + "_STAINED_GLASS")); else if (type.endsWith("STAINED_GLASS_PANE")) setType(org.bukkit.Material.getMaterial(color.name() + "_STAINED_GLASS_PANE")); else if (type.endsWith("TERRACOTTA")) setType(org.bukkit.Material.getMaterial(color.name() + "_TERRACOTTA")); else if (type.endsWith("GLAZED_TERRACOTTA")) setType(org.bukkit.Material.getMaterial(color.name() + "_GLAZED_TERRACOTTA")); else if (type.endsWith("BANNER")) setType(org.bukkit.Material.getMaterial(color.name() + "_BANNER")); else if (type.endsWith("WALL_BANNER")) setType(org.bukkit.Material.getMaterial(color.name() + "_WALL_BANNER")); else if (type.endsWith("CARPET")) setType(org.bukkit.Material.getMaterial(color.name() + "_CARPET")); else if (type.endsWith("SHULKER_BOX")) setType(org.bukkit.Material.getMaterial(color.name() + "_SHULKERBOX")); else if (type.endsWith("CONCRETE")) setType(org.bukkit.Material.getMaterial(color.name() + "_CONCRETE")); else if (type.endsWith("CONCRETE_POWDER")) setType(org.bukkit.Material.getMaterial(color.name() + "_CONCRETE_POWDER")); return this; } data(color.getWoolData()); return this; } /* (non-Javadoc) * @see org.bukkit.inventory.ItemStack#setAmount(int) */ @Override public void setAmount(int amount) { super.setAmount(Math.max(1, amount)); } /** * Add a map of enchantments and enchantmnent level to the itemstack. * * @param enchantments the enchantments to add * @return the item stack builder */ public ItemStackBuilder enchantments(HashMap<Enchantment, Integer> enchantments) { getEnchantments().keySet().forEach(this::removeEnchantment); addUnsafeEnchantments(enchantments); return this; } /** * Enchants the itemstack. * * @param enchantment the enchantment * @param level the level * @return the item stack builder */ public ItemStackBuilder enchant(Enchantment enchantment, int level) { addUnsafeEnchantment(enchantment, level); return this; } /** * Sets the item name. * * @param player the player * @param lang the lang * @return the item stack builder */ public ItemStackBuilder name(Player player, ILang lang) { return name(lang.getMessage(player)); } /** * Sets the item name. * * @param player the player * @param lang the lang * @return the item stack builder */ public ItemStackBuilder name(IPlayer player, ILang lang) { return name(lang.getMessage(player)); } /** * Sets the item name. * * @param name the name * @return the item stack builder */ public ItemStackBuilder name(String name) { if (name == null) { return this; } ItemMeta itemMeta = getItemMeta(); itemMeta.setDisplayName(name.equals("") ? " " : format(name)); setItemMeta(itemMeta); return this; } /** * Sets the MaterialData for this item stack * * @param data New MaterialData for this item * @see ItemStack#setData(MaterialData) */ @Override public void setData(MaterialData data) { Field dataField; try { dataField = ItemStack.class.getDeclaredField("data"); dataField.setAccessible(true); dataField.set(this, data); } catch (Exception e) { e.printStackTrace(); } } /** * Adds a glow effect to the item. * * @param glowing the glowing * @return the item stack builder */ public ItemStackBuilder glowing(boolean glowing) { if (glowing) { this.addEnchantment(EnchantGlow.getGlow(), 4); } return this; } /** * Adds an enchantment to the book * * @param ench the enchantment * @param level the level * @return the item stack builder */ public ItemStackBuilder enchantedBook(Enchantment ench, int level) { EnchantmentStorageMeta meta = (EnchantmentStorageMeta)getItemMeta(); meta.addEnchant(ench, level, true); return this; } /** * Sets the leather armor color. * * @param red the red * @param green the green * @param blue the blue * @return the item stack builder */ public ItemStackBuilder color(int red, int green, int blue) { return color(Color.fromRGB(red, green, blue)); } /** * Sets the leather armor color. * * @param color the color * @return the item stack builder */ public ItemStackBuilder color(Color color) { LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) getItemMeta(); leatherArmorMeta.setColor(color); setItemMeta(leatherArmorMeta); return this; } /** * Creates a confirm item. * * @return the item stack builder */ public ItemStackBuilder createConfirmItem() { material(org.bukkit.Material.EMERALD_BLOCK); name(ChatColor.GREEN + "CONFIRM"); return this; } /** * Creates a cancel item. * * @return the item stack builder */ public ItemStackBuilder createCancelItem() { material(org.bukkit.Material.REDSTONE_BLOCK); name(ChatColor.GREEN + "CANCEL"); return this; } /** * Creates a back item. * * @param player the player * @return the item stack builder */ public ItemStackBuilder createBackItem(Player player) { material(org.bukkit.Material.ARROW); name(CoreLang.GUI_BACK.getMessage(player)); return this; } /** * Creates a togglable item. * * @param player the player * @param enabled the enabled * @return the item stack builder */ public ItemStackBuilder createTogglableItem(Player player, boolean enabled) { if(enabled) { return createEnabledItem(player); } return createDisabledItem(player); } /** * Creates the enabled item. * * @param player the player * @return the item stack builder */ public ItemStackBuilder createEnabledItem(Player player) { material(Material.LIME_DYE); name(CoreLang.GUI_ENABLED.getMessage(player)); return this; } /** * Creates a disabled item. * * @param player the player * @return the item stack builder */ public ItemStackBuilder createDisabledItem(Player player) { material(Material.GRAY_DYE); name(CoreLang.GUI_DISABLED.getMessage(player)); return this; } /** * Creates a togglable slimball. * * @param player the player * @param enabled the enabled * @return the item stack builder */ public ItemStackBuilder createTogglableSlimball(Player player, boolean enabled) { if(enabled) { return createEnabledSlimeball(player); } return createDisableSlimeball(player); } /** * Creates the enabled slimeball. * * @param player the player * @return the item stack builder */ public ItemStackBuilder createEnabledSlimeball(Player player) { material(org.bukkit.Material.MAGMA_CREAM); name(CoreLang.GUI_ENABLED.getMessage(player)); return this; } /** * Creates the disable slimeball. * * @param player the player * @return the item stack builder */ public ItemStackBuilder createDisableSlimeball(Player player) { material(org.bukkit.Material.SLIME_BALL); name(CoreLang.GUI_DISABLED.getMessage(player)); return this; } /** * Adds a blank line to the lore. * * @return the item stack builder */ public ItemStackBuilder blankLine() { addLore(" "); return this; } /** * Adds a line separator to the lore. * * @return the item stack builder */ public ItemStackBuilder lineLore() { return lineLore(20); } /** * Adds a separator line to the lore. * * @param length the length * @return the item stack builder */ public ItemStackBuilder lineLore(int length) { addLore("&8&m&l" + Strings.repeat("-", length)); return this; } /** * Creates and sets the skull owner. * * @param owner the owner * @return the item stack builder */ public ItemStackBuilder skullOwner(String owner) { material(Material.PLAYER_HEAD); SkullMeta meta = (SkullMeta) Bukkit.getItemFactory().getItemMeta(Material.PLAYER_HEAD.parseMaterial()); meta.setOwner(owner); setItemMeta(meta); return this; } /** * Creates a custom skull based on a URL. * * @param url the url * @return the item stack builder */ public ItemStackBuilder customSkull(String url) { createPlayerHead(); SkullMeta headMeta = (SkullMeta) getItemMeta(); try { Object profile = Utils.createGameProfile(); Object profileProperties = Utils.invokeMethod(profile, "getProperties", null); Object property = Utils.createProperty("textures", url); Utils.invokeMethod(profileProperties, Utils.getMethodNotDeclaredValue(profileProperties.getClass(), "put", Object.class, Object.class), "textures", property); Field profileField; profileField = headMeta.getClass().getDeclaredField("profile"); profileField.setAccessible(true); profileField.set(headMeta, profile); } catch (Exception e1) { e1.printStackTrace(); } setItemMeta(headMeta); return this; } @Override public ItemStackBuilder clone() { return (ItemStackBuilder) super.clone(); } /** * Creates a player head. * * @return the item stack builder */ public ItemStackBuilder createPlayerHead() { material(Material.PLAYER_HEAD); return this; } /** * Adds the lore. * * @param lore the lore * @return the item stack builder */ public ItemStackBuilder addLore(String... lore) { if (lore == null) { return this; } ItemMeta itemMeta = getItemMeta(); List<String> original = itemMeta.getLore(); if (original == null) original = new ArrayList<>(); Collections.addAll(original, format(lore)); itemMeta.setLore(original); setItemMeta(itemMeta); return this; } /** * Adds the lore. * * @param lore the lore * @return the item stack builder */ public ItemStackBuilder addLore(List<String> lore) { if (lore == null) { return this; } ItemMeta itemMeta = getItemMeta(); List<String> original = itemMeta.getLore(); if (original == null) original = new ArrayList<>(); original.addAll(format(lore)); itemMeta.setLore(original); setItemMeta(itemMeta); return this; } /** * Lore. * * @param lore the lore * @return the item stack builder */ public ItemStackBuilder lore(String lore) { if (lore == null) { return this; } if(!lore.contains("\n")) { ItemMeta itemMeta = getItemMeta(); itemMeta.setLore(format(Collections.singletonList(lore))); setItemMeta(itemMeta); return this; } return lore(lore.split("\n")); } /** * Set the lore. * * @param lore the lore * @return the item stack builder */ public ItemStackBuilder lore(String... lore) { if (lore == null) { return this; } ItemMeta itemMeta = getItemMeta(); itemMeta.setLore(format(Lists.newArrayList(lore))); setItemMeta(itemMeta); return this; } /** * Set the lore. * * @param lore the lore * @return the item stack builder */ public ItemStackBuilder lore(List<String> lore) { if (lore == null) { return this; } ItemMeta itemMeta = getItemMeta(); itemMeta.setLore(format(lore)); setItemMeta(itemMeta); return this; } /** * Format a string. * * @param string the string * @return the string */ public String format(String string) { return (string == null ? null : string.replace("&", "§")); } /** * Format a string. * * @param strings the strings * @return the string[] */ public String[] format(String[] strings) { return format(Arrays.asList(strings)).toArray(new String[strings.length]); } /** * Format a string. * * @param strings the strings * @return the list */ public List<String> format(List<String> strings) { List<String> collection = new ArrayList<>(); for (String string : strings) { if (string == null || string.isEmpty()) { continue; } collection.add(format(string)); } return collection; } }
17,986
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PotionBuilder.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/itemstack/PotionBuilder.java
package me.patothebest.gamecore.itemstack; import org.bukkit.potion.Potion; import org.bukkit.potion.PotionType; /** * The PotionBuilder. */ @SuppressWarnings("deprecation") public class PotionBuilder extends Potion { /** * Instantiates a new potion builder. */ public PotionBuilder() { super(PotionType.SPEED); } /** * Sets the effect type to the potion. * * @param type the potion type * @return the potion builder */ public PotionBuilder effect(PotionType type) { setType(type); return this; } /** * Makes the potion splash. * * @param splash if the potion should be a splash potion * @return the potion builder */ public PotionBuilder splash(boolean splash) { setSplash(splash); return this; } /** * Sets the potion's level. * * @param level the level * @return the potion builder */ public PotionBuilder level(int level) { setLevel(level); return this; } /** * Sets if the potion should have an extended duration. * * @param isExtended if the potion should have an extended duration * @return the potion builder */ public PotionBuilder extendedDuration(boolean isExtended) { setHasExtendedDuration(isExtended); return this; } }
1,385
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GhostFactory.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/ghost/GhostFactory.java
package me.patothebest.gamecore.ghost; import com.google.inject.Singleton; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ModuleName; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @Singleton @ModuleName("Ghost Manager") public class GhostFactory implements ActivableModule { /** * Team of ghosts and people who can see ghosts. */ private static final String GHOST_TEAM_NAME = "Ghosts"; // No players in the ghost factory private static final Player[] EMPTY_PLAYERS = new Player[0]; private final Map<Player, Team> ghostTeams = new HashMap<>(); // Players that are actually ghosts private final Set<Player> ghosts = new HashSet<>(); // Team nametags addon private boolean teamPrefix; private String teamName; @Override public void onDisable() { clearMembers(); } /** * Remove all existing player members and ghosts. */ public void clearMembers() { for (Player player : getGhosts()) { removePlayer(player); } } /** * Add the given player to this ghost manager. This ensures that it can see ghosts, and later become one. * * @param player - the player to add to the ghost manager. */ public void addPlayer(Player player) { if(!ghosts.contains(player)) { Team team = createTeam(player); team.addEntry(player.getName()); for (Player ghost : ghosts) { team.addEntry(ghost.getName()); ghostTeams.get(ghost).addEntry(player.getName()); } player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 15)); ghosts.add(player); } } /** * Determine if the given player is tracked by this ghost manager and is a ghost. * * @param player - the player to test. * * @return TRUE if it is, FALSE otherwise. */ public boolean isGhost(Player player) { return player != null && hasPlayer(player); } /** * Determine if the current player is tracked by this ghost manager, or is a ghost. * * @param player - the player to check. * * @return TRUE if it is, FALSE otherwise. */ public boolean hasPlayer(Player player) { return ghosts.contains(player); } /** * Set whether or not a given player is a ghost. * * @param player - the player to set as a ghost. * @param isGhost - TRUE to make the given player into a ghost, FALSE otherwise. */ public void setGhost(Player player, boolean isGhost) { if (isGhost) { addPlayer(player); } else { removePlayer(player); } } /** * Remove the given player from the manager, turning it back into the living and making it unable to see ghosts. * * @param player - the player to remove from the ghost manager. */ public void removePlayer(Player player) { if(ghosts.contains(player)) { Team team = ghostTeams.get(player); ghosts.remove(player); ghostTeams.remove(player); for (Player ghost : ghosts) { ghostTeams.get(ghost).removeEntry(player.getName()); } team.unregister(); player.removePotionEffect(PotionEffectType.INVISIBILITY); } } /** * Retrieve every ghost and every player that can see ghosts. * * @return Every ghost or every observer. */ public Player[] getGhosts() { return toArray(ghosts); } private Player[] toArray(Set<Player> players) { if (players != null) { return players.toArray(new Player[players.size()]); } else { return EMPTY_PLAYERS; } } private Team createTeam(Player player) { Scoreboard board = player.getScoreboard(); Team ghostTeam = board.getTeam(GHOST_TEAM_NAME); // Create a new ghost team if needed if (ghostTeam == null) { ghostTeam = board.registerNewTeam(GHOST_TEAM_NAME); if(teamPrefix) { ghostTeam.setPrefix(ChatColor.GRAY + "[" + teamName + "] "); } } // Thanks to Rprrr for noticing a bug here ghostTeam.setCanSeeFriendlyInvisibles(true); ghostTeams.put(player, ghostTeam); return ghostTeam; } public void setTeamPrefix(boolean teamPrefix) { this.teamPrefix = teamPrefix; } public void setTeamName(String teamName) { this.teamName = teamName; } }
4,934
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArenasModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/PrivateArenasModule.java
package me.patothebest.gamecore.privatearenas; import com.google.inject.assistedinject.FactoryModuleBuilder; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.injector.AbstractBukkitModule; import me.patothebest.gamecore.privatearenas.ui.PrivateArenaUIFactory; public class PrivateArenasModule extends AbstractBukkitModule<CorePlugin> { public PrivateArenasModule(CorePlugin plugin) { super(plugin); } @Override protected void configure() { install(new FactoryModuleBuilder().build(PrivateArenaUIFactory.class)); registerModule(PrivateArenasCommand.class); registerModule(PrivateArenasManager.class); } }
685
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArena.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/PrivateArena.java
package me.patothebest.gamecore.privatearenas; import me.patothebest.gamecore.arena.AbstractArena; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; public class PrivateArena { private final String owner; private final List<String> coHosts = new ArrayList<>(); private AbstractArena arena; public PrivateArena(String owner, AbstractArena arena) { this.owner = owner; this.arena = arena; coHosts.add(owner); } public Player getOwner() { return Bukkit.getPlayer(owner); } public String getOwnerName() { return owner; } public AbstractArena getArena() { return arena; } public List<String> getWhitelistedPlayers() { return arena.getWhitelistedPlayers(); } public List<String> getCoHosts() { return coHosts; } public void setArena(AbstractArena arena) { this.arena = arena; } }
985
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArenasManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/PrivateArenasManager.java
package me.patothebest.gamecore.privatearenas; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.ArenaManager; import me.patothebest.gamecore.event.arena.ArenaPreRegenEvent; import me.patothebest.gamecore.event.player.ArenaPreLeaveEvent; import me.patothebest.gamecore.feature.features.other.CountdownFeature; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.logger.InjectLogger; import me.patothebest.gamecore.logger.Logger; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ListenerModule; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.player.PlayerManager; import me.patothebest.gamecore.util.PlayerList; import me.patothebest.gamecore.util.Utils; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @Singleton @ModuleName("Private Arenas Manager") public class PrivateArenasManager implements ReloadableModule, ActivableModule, ListenerModule { private final Map<String, PrivateArena> privateArenaMap = new HashMap<>(); private final List<AbstractArena> changingArenas = new ArrayList<>(); private final ArenaManager arenaManager; private final PlayerManager playerManager; private final List<String> enabledArenas = new ArrayList<>(); private final AtomicInteger id = new AtomicInteger(1); @InjectLogger private Logger logger; @Inject private PrivateArenasManager(ArenaManager arenaManager, PlayerManager playerManager) { this.arenaManager = arenaManager; this.playerManager = playerManager; } @Override public void onPreEnable() { enabledArenas.clear(); File[] files = ArenaManager.ARENA_DIRECTORY.listFiles(); if (files == null) { return; } for (File file : files) { String name = file.getName().replace(".yml", ""); String contents = Utils.readFileAsString(file); if (contents.contains("enabled: true")) { enabledArenas.add(name); logger.config("Adding arena {0} as an option", name); } } } @Override public void onReload() { onDisable(); onPreEnable(); } @Override public void onDisable() { for (PrivateArena value : privateArenaMap.values()) { removePrivateArena(value); } } @EventHandler public void onPreRegen(ArenaPreRegenEvent event) { for (PrivateArena value : privateArenaMap.values()) { if (event.getArena() == value.getArena()) { event.setCancelled(true); changeArena(value, Utils.getRandomElementFromList(enabledArenas)); return; } } } @EventHandler public void onLeave(ArenaPreLeaveEvent event) { if (changingArenas.contains(event.getArena())) { event.setCancelTeleport(true); } } public void changeArena(PrivateArena arena, String newMap) { AbstractArena newArena = loadArena(arena.getOwnerName(), newMap); AbstractArena oldArena = arena.getArena(); PlayerList playersToMove = oldArena.getPlayers(); PlayerList spectatorsToMove = oldArena.getSpectators(); newArena.setWhitelist(oldArena.isWhitelist()); newArena.setDisableSaving(oldArena.isDisableSaving()); newArena.setPublicJoinable(oldArena.isPublicJoinable()); newArena.setPublicSpectable(oldArena.isPublicSpectable()); newArena.setTeamSelector(oldArena.isTeamSelector()); newArena.setDisplayName(oldArena.getDisplayName()); arena.setArena(newArena); changingArenas.add(oldArena); for (Player player : playersToMove) { oldArena.removePlayer(player); newArena.addPlayer(player); } for (Player player : spectatorsToMove) { boolean canPlay = oldArena.canJoin(player); oldArena.removePlayer(player); if (canPlay) { newArena.addPlayer(player); } else { newArena.addSpectator(player); } } changingArenas.remove(oldArena); newArena.getWhitelistedPlayers().addAll(oldArena.getWhitelistedPlayers()); arenaManager.getArenas().values().remove(oldArena); oldArena.getArenaWorld().unloadWorld(false); oldArena.getArenaWorld().deleteWorld(); oldArena.destroy(); } @Override public String getReloadName() { return "private-arenas"; } public void destroy(PrivateArena arena) { AbstractArena oldArena = arena.getArena(); arenaManager.getArenas().values().remove(oldArena); oldArena.destroy(); } public PrivateArena createPrivateArena(Player player) { if (playerManager.getPlayer(player).isInArena()) { CoreLang.ALREADY_IN_ARENA.sendMessage(player); return null; } String randomArena = Utils.getRandomElementFromList(enabledArenas); if (randomArena == null) { return null; } AbstractArena abstractArena = loadArena(player.getName(), randomArena); PrivateArena privateArena = new PrivateArena(player.getName(), abstractArena); privateArenaMap.put(player.getName(), privateArena); abstractArena.addPlayer(player); return privateArena; } private AbstractArena loadArena(String playerName, String arenaName) { String worldName = "private_" + playerName + "_" + arenaName + "_" + id.getAndIncrement(); logger.fine("Loading arena {0} for player {1}. WorldName: {2}", arenaName, playerName, worldName); AbstractArena arena = arenaManager.loadArena(arenaName, worldName, false); arena.setDisableSaving(true); arena.setDisableStats(true); arena.setWhitelist(true); arena.getWhitelistedPlayers().add(playerName); arena.setPublicJoinable(false); arena.setPublicSpectable(false); arena.setPrivateArena(true); arena.initializeData(); arena.setDisplayName(playerName + "'s Private Arena"); arena.getFeature(CountdownFeature.class).setOverrideRunning(true); return arena; } public Map<String, PrivateArena> getPrivateArenaMap() { return privateArenaMap; } public void removePrivateArena(PrivateArena privateArena) { logger.fine("Removing private arena of {0}", privateArena.getOwnerName()); AbstractArena arena = privateArena.getArena(); arena.getArenaWorld().deleteWorld(); arena.destroy(); arenaManager.getArenas().remove(arena.getWorldName()); privateArenaMap.remove(privateArena.getOwnerName()); } public List<String> getEnabledArenas() { return enabledArenas; } public PrivateArena getCurrentArena(Player player) { AbstractArena currentArena = playerManager.getPlayer(player).getCurrentArena(); if (currentArena == null) { return null; } for (PrivateArena value : privateArenaMap.values()) { if (value.getArena() == currentArena) { return value; } } return null; } }
7,602
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArenasCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/PrivateArenasCommand.java
package me.patothebest.gamecore.privatearenas; import me.patothebest.gamecore.command.BaseCommand; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.privatearenas.ui.PrivateArenaUIFactory; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import javax.inject.Inject; @ChildOf(BaseCommand.class) public class PrivateArenasCommand implements RegisteredCommandModule { private final PrivateArenasManager privateArenasManager; private final PrivateArenaUIFactory privateArenaUIFactory; @Inject private PrivateArenasCommand(PrivateArenasManager privateArenasManager, PrivateArenaUIFactory privateArenaUIFactory) { this.privateArenasManager = privateArenasManager; this.privateArenaUIFactory = privateArenaUIFactory; } @Command( aliases = {"private", "privatearena"}, min = 0, max = 0, langDescription = @LangDescription( element = "GUI_PRIVATE_ARENA_COMMAND", langClass = CoreLang.class ) ) @CommandPermissions(permission = Permission.ADMIN) public void create(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); privateArenasManager.createPrivateArena(player); } @Command( aliases = {"privatemenu", "pm"}, usage = "", min = 0, max = -1, langDescription = @LangDescription( element = "", langClass = CoreLang.class ) ) public void testmenu(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); PrivateArena privateArena = privateArenasManager.getPrivateArenaMap().get(player.getName()); if (privateArena == null) { return; } privateArenaUIFactory.createPrivateArenaMenu(player, privateArena); } }
2,516
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ChangeMapUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/ChangeMapUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.privatearenas.PrivateArenasManager; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ChangeMapUI extends StaticPaginatedUI<String> { private final PrivateArena privateArena; private final PrivateArenasManager privateArenasManager; private final ButtonAction backAction; protected ChangeMapUI(Plugin plugin, Player player, PrivateArena privateArena, PrivateArenasManager privateArenasManager, ButtonAction backAction) { super(plugin, player, CoreLang.CHANGE_ARENA, privateArenasManager::getEnabledArenas); this.privateArena = privateArena; this.privateArenasManager = privateArenasManager; this.backAction = backAction; build(); } @Override protected GUIButton createButton(String item) { return new SimpleButton(new ItemStackBuilder() .material(Material.MAP) .name(ChatColor.GOLD + item)) .action(() -> { privateArenasManager.changeArena(privateArena, item); }); } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); } }
1,816
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ArenaOptionsUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/ArenaOptionsUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ArenaOptionsUI extends GUIPage { private final ButtonAction backAction; private final PrivateArena privateArena; protected ArenaOptionsUI(Plugin plugin, Player player, ButtonAction backAction, PrivateArena privateArena) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_OPTIONS, 36); this.backAction = backAction; this.privateArena = privateArena; build(); } @Override protected void buildPage() { addOption(CoreLang.GUI_PRIVATE_ARENA_WHITELIST, Material.PAPER, privateArena.getArena().isWhitelist(), () -> { privateArena.getArena().setWhitelist(!privateArena.getArena().isWhitelist()); refresh(); }, 9); addOption(CoreLang.GUI_PRIVATE_ARENA_TEAM_SELECTOR, Material.LIGHT_BLUE_WOOL, privateArena.getArena().isTeamSelector(), () -> { privateArena.getArena().setTeamSelector(!privateArena.getArena().isTeamSelector()); refresh(); }, 11); addOption(CoreLang.GUI_PRIVATE_ARENA_PUBLIC_JOIN, Material.OAK_FENCE_GATE, privateArena.getArena().isPublicJoinable(), () -> { privateArena.getArena().setPublicJoinable(!privateArena.getArena().isPublicJoinable()); refresh(); }, 13); addOption(CoreLang.GUI_PRIVATE_ARENA_PUBLIC_SPECTATE, Material.COMPASS, privateArena.getArena().isPublicSpectable(), () -> { privateArena.getArena().setPublicSpectable(!privateArena.getArena().isPublicSpectable()); refresh(); }, 15); addOption(CoreLang.GUI_PRIVATE_ARENA_STATS, Material.DIAMOND_SWORD, !privateArena.getArena().isDisableStats(), () -> { privateArena.getArena().setDisableStats(!privateArena.getArena().isDisableStats()); refresh(); }, 17); addButton(new BackButton(getPlayer(), backAction), 27); } private void addOption(CoreLang title, Material displayMaterial, boolean state, ButtonAction onClick, int slot) { addButton(new PlaceHolder(new ItemStackBuilder(displayMaterial).name(title.getMessage(getPlayer()))), slot); addButton(new SimpleButton(new ItemStackBuilder().createTogglableItem(getPlayer(), state)).action(onClick), slot + 9); } }
2,893
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AddPlayerToWhitelistUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/AddPlayerToWhitelistUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButtonAction; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.stream.Collectors; public class AddPlayerToWhitelistUI extends StaticPaginatedUI<Player> { private final PrivateArena privateArena; private final ButtonAction backAction; private final ItemStack displayItem; AddPlayerToWhitelistUI(Plugin plugin, Player player, PrivateArena privateArena, ItemStack displayItem, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_ADD_PLAYERS_TO_WHITELIST, () -> Bukkit.getOnlinePlayers().stream().filter(o -> !privateArena.getWhitelistedPlayers().contains(o.getName())).collect(Collectors.toList())); this.privateArena = privateArena; this.backAction = backAction; this.displayItem = displayItem; build(); } @Override protected GUIButton createButton(Player whitelistPlayer) { ItemStackBuilder addToWhitelist = new ItemStackBuilder().skullOwner(whitelistPlayer.getName()).name(CoreLang.GUI_PRIVATE_ARENA_ADD_PLAYER_TO_WHITELIST.replace(getPlayer(), whitelistPlayer.getName())); return new ConfirmButton(addToWhitelist, displayItem, addToWhitelist, () -> { privateArena.getWhitelistedPlayers().add(whitelistPlayer.getName()); CoreLang.GUI_PRIVATE_ARENA_PLAYER_ADDED_TO_WHITELIST.replaceAndSend(getPlayer(), whitelistPlayer.getName()); new AddPlayerToWhitelistUI(plugin, player, privateArena, displayItem, backAction); }); } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); addButton(new AnvilButton(new ItemStackBuilder().material(Material.WRITABLE_BOOK).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_ADD_PLAYER_TO_WHITELIST_BY_NAME), new AnvilButtonAction() { @Override public void onConfirm(String output) { privateArena.getWhitelistedPlayers().add(output); CoreLang.GUI_PRIVATE_ARENA_PLAYER_ADDED_TO_WHITELIST.replaceAndSend(getPlayer(), output); new AddPlayerToWhitelistUI(plugin, player, privateArena, displayItem, backAction); } @Override public void onCancel() { new AddPlayerToWhitelistUI(plugin, player, privateArena, displayItem, backAction); } }).slot(AnvilSlot.INPUT_LEFT, new ItemStackBuilder(Material.PAPER).name("player")), 51); } }
3,318
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
MovePlayersUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/MovePlayersUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.gui.inventory.page.DualListPage; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.AbstractGameTeam; import me.patothebest.gamecore.event.player.ArenaLeaveEvent; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.util.Utils; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.List; public class MovePlayersUI extends DualListPage<Player> { private final AbstractArena arena; private final AbstractGameTeam gameTeam; private final ButtonAction backAction; protected MovePlayersUI(Plugin plugin, Player player, AbstractArena arena, AbstractGameTeam gameTeam, ButtonAction backAction) { super(plugin, player, "", () -> { List<Player> players = new ArrayList<>(arena.getPlayers()); players.addAll(arena.getSpectators()); List<Player> preferencePlayers = arena.getTeamPreferences().get(gameTeam); if (preferencePlayers != null) { players.removeAll(preferencePlayers); } return players; }, () -> { List<Player> players = new ArrayList<>(gameTeam.getPlayers()); List<Player> preferencePlayers = arena.getTeamPreferences().get(gameTeam); if (preferencePlayers != null) { players.addAll(preferencePlayers); } return players; }); this.arena = arena; this.gameTeam = gameTeam; this.backAction = backAction; build(); } @Override protected void buildHeader() { addButton(new PlaceHolder(new ItemStackBuilder() .material(Material.WHITE_WOOL) .name(Utils.getColorFromDye(gameTeam.getColor()) + gameTeam.getName())), 4); } @Override protected GUIButton createLeftButton(Player player) { ItemStackBuilder item = new ItemStackBuilder().skullOwner(player.getName()).name(ChatColor.GREEN + player.getName()); if (arena.getPlayers().contains(player)) { AbstractGameTeam teamPreference = arena.getTeamPreference(player); if (teamPreference != null) { item.lore(CoreLang.GUI_PRIVATE_ARENA_CURRENT_TEAM.replace(getPlayer(), teamPreference.getName())); } else { item.lore(CoreLang.GUI_PRIVATE_ARENA_NO_CURRENT_TEAM.getMessage(getPlayer())); } } else { item.lore(CoreLang.GUI_PRIVATE_ARENA_CURRENT_SPEC.getMessage(getPlayer())); } item.lore("", CoreLang.GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_TEAM.replace(getPlayer(), gameTeam)); return new SimpleButton(item).action(() -> { AbstractGameTeam otherTeam = arena.getTeamPreference(player); if(otherTeam != null) { arena.getTeamPreferences().get(otherTeam).remove(player); } if (arena.getSpectators().contains(player)) { arena.changeToPlayer(player); } List<Player> players = arena.getTeamPreferences().computeIfAbsent(gameTeam, k -> new ArrayList<>()); players.add(player); arena.getTeamPreferences().putIfAbsent(gameTeam, players); player.sendMessage(CoreLang.GUI_USER_CHOOSE_TEAM_YOU_JOINED.replace(player, Utils.getColorFromDye(gameTeam.getColor()), gameTeam.getName())); refresh(); }); } @Override protected GUIButton createRightButton(Player player) { ItemStackBuilder item = new ItemStackBuilder().skullOwner(player.getName()).name(ChatColor.GREEN + player.getName()); item.lore(CoreLang.GUI_PRIVATE_ARENA_CURRENT_TEAM.replace(getPlayer(), gameTeam.getName()), "", CoreLang.GUI_PRIVATE_ARENA_CLICK_TO_REMOVE_TEAM.replace(getPlayer(), gameTeam)); return new SimpleButton(item).action(() -> { AbstractGameTeam otherTeam = arena.getTeamPreference(player); if(otherTeam != null) { arena.getTeamPreferences().get(otherTeam).remove(player); refresh(); } }); } @Override protected void buildFooter() { addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer())).action(backAction), getSize()-9); } @EventHandler public void onLeave(ArenaLeaveEvent event) { refresh(); } }
4,961
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArenaUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/PrivateArenaUI.java
package me.patothebest.gamecore.privatearenas.ui; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.privatearenas.PrivateArenasManager; import me.patothebest.gamecore.arena.AbstractGameTeam; import me.patothebest.gamecore.feature.features.other.CountdownFeature; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.button.AnvilButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButtonAction; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.player.PlayerManager; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.List; public class PrivateArenaUI extends GUIPage { private final PrivateArenasManager privateArenasManager; private final PrivateArena privateArena; private final PlayerManager playerManager; @AssistedInject private PrivateArenaUI(Plugin plugin, @Assisted Player player, PrivateArenasManager privateArenasManager, @Assisted PrivateArena privateArena, PlayerManager playerManager) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_TITLE, 36); this.privateArenasManager = privateArenasManager; this.privateArena = privateArena; this.playerManager = playerManager; build(); } @Override protected void buildPage() { CountdownFeature countdown = privateArena.getArena().getFeature(CountdownFeature.class); ItemStackBuilder head = new ItemStackBuilder().skullOwner(privateArena.getOwnerName()).name(CoreLang.GUI_PRIVATE_ARENA_HEAD.replace(getPlayer(), privateArena.getOwnerName())); ItemStackBuilder rename = new ItemStackBuilder().material(Material.NAME_TAG).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_RENAME); ItemStackBuilder teamsItem = new ItemStackBuilder().material(Material.LIGHT_BLUE_WOOL).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_MANAGE_TEAMS); ItemStackBuilder start = new ItemStackBuilder().material(Material.EMERALD_BLOCK).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_START_COUNTDOWN); ItemStackBuilder stop = new ItemStackBuilder().material(Material.REDSTONE_BLOCK).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_STOP_COUNTDOWN); ItemStackBuilder kickPlayers = new ItemStackBuilder().material(Material.DIAMOND_SWORD).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_KICK_PLAYERS); ItemStackBuilder changeMap = new ItemStackBuilder().material(Material.MAP).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_CHANGE_MAP); ItemStackBuilder giveCoHost = new ItemStackBuilder().material(Material.NETHER_STAR).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_ADD_CO_HOST); ItemStackBuilder removeCoHost = new ItemStackBuilder().material(Material.RED_DYE).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_REMOVE_CO_HOST); ItemStackBuilder addToWhiteList = new ItemStackBuilder().material(Material.WRITABLE_BOOK).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_ADD_PLAYERS_TO_WHITELIST); ItemStackBuilder removefromWhitelist = new ItemStackBuilder().material(Material.BOOK).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_REMOVE_PLAYERS_FROM_WHITELIST); ItemStackBuilder arenaOptions = new ItemStackBuilder().material(Material.COMPARATOR).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_OPTIONS); ItemStackBuilder close = new ItemStackBuilder().material(Material.BARRIER).name(getPlayer(), CoreLang.GUI_PRIVATE_ARENA_CLOSE); ButtonAction backAction = () -> { new PrivateArenaUI(plugin, player, privateArenasManager, privateArena, playerManager); }; addButton(new PlaceHolder(head), 4); addButton(new AnvilButton(rename).action(new AnvilButtonAction() { @Override public void onConfirm(String output) { privateArena.getArena().setDisplayName(output); backAction.onClick(); } @Override public void onCancel() { backAction.onClick(); } }).slot(AnvilSlot.INPUT_LEFT, new ItemStackBuilder().material(Material.NAME_TAG).name(privateArena.getArena().getDisplayName())), 11); addButton(new SimpleButton(teamsItem).action(() -> { List<AbstractGameTeam> teams = new ArrayList<>(privateArena.getArena().getTeams().values()); teams.add(SelectTeamUI.SPEC_DUMMY); new SelectTeamUI(plugin, player, privateArena.getArena(), teams, backAction); }), 15); addButton(new SimpleButton(start).action(countdown::startCountdown), 18); addButton(new SimpleButton(stop).action(() -> countdown.setRunning(false)), 27); addButton(new SimpleButton(kickPlayers).action(() -> { new KickPlayerUI(plugin, getPlayer(), privateArena, kickPlayers, backAction); }), 20); addButton(new SimpleButton(changeMap).action(() -> { new ChangeMapUI(plugin, player, privateArena, privateArenasManager, backAction); }), 29); addButton(new SimpleButton(giveCoHost).action(() -> { new GiveCoHostUI(plugin, playerManager, player, privateArena, giveCoHost, backAction); }), 22); addButton(new SimpleButton(removeCoHost).action(() -> { new RemoveCoHostUI(plugin, playerManager, player, privateArena, removeCoHost, backAction); }), 31); addButton(new SimpleButton(addToWhiteList).action(() -> { new AddPlayerToWhitelistUI(plugin, player, privateArena, addToWhiteList, backAction); }), 24); addButton(new SimpleButton(removefromWhitelist).action(() -> { new RemovePlayerFromWhitelistUI(plugin, player, privateArena, removefromWhitelist, backAction); }), 33); addButton(new SimpleButton(arenaOptions).action(() -> { new ArenaOptionsUI(plugin, player, backAction, privateArena); }), 26); addButton(new ConfirmButton(close, close, close).action(() -> { privateArenasManager.removePrivateArena(privateArena); }), 35); } }
6,645
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
RemoveCoHostUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/RemoveCoHostUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.player.IPlayer; import me.patothebest.gamecore.player.PlayerManager; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.stream.Collectors; public class RemoveCoHostUI extends StaticPaginatedUI<String> { private final PlayerManager playerManager; private final PrivateArena privateArena; private final ButtonAction backAction; private final ItemStack displayItem; RemoveCoHostUI(Plugin plugin, PlayerManager playerManager, Player player, PrivateArena privateArena, ItemStack displayItem, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_REMOVE_CO_HOST, () -> privateArena.getCoHosts().stream().filter(s -> !privateArena.getOwnerName().equalsIgnoreCase(s)).collect(Collectors.toList())); this.playerManager = playerManager; this.privateArena = privateArena; this.backAction = backAction; this.displayItem = displayItem; build(); } @Override protected GUIButton createButton(String coHost) { ItemStackBuilder removeCoHostItem = new ItemStackBuilder().skullOwner(coHost).name(CoreLang.GUI_PRIVATE_ARENA_DEMOTE_CO_HOST.replace(getPlayer(), coHost)); return new ConfirmButton(removeCoHostItem, displayItem, removeCoHostItem, () -> { privateArena.getCoHosts().remove(coHost); IPlayer coHostRemoved = playerManager.getPlayer(coHost); if (coHostRemoved != null) { if (coHostRemoved.getCurrentArena() == privateArena.getArena()) { if (!privateArena.getArena().isInGame() && !coHostRemoved.getPlayer().hasPermission(Permission.ADMIN.getBukkitPermission())) { coHostRemoved.getPlayer().getInventory().setItem(7, new ItemStackBuilder(Material.AIR)); coHostRemoved.getPlayer().closeInventory(); } } } CoreLang.GUI_PRIVATE_ARENA_CO_HOST_REMOVED.replaceAndSend(getPlayer(), coHost); new RemoveCoHostUI(plugin, playerManager, getPlayer(), privateArena, displayItem, backAction); }); } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); } }
3,000
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SelectTeamUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/SelectTeamUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.gui.inventory.page.DynamicPaginatedUI; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.AbstractGameTeam; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.util.Utils; import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.List; public class SelectTeamUI extends DynamicPaginatedUI<AbstractGameTeam> { static final AbstractGameTeam SPEC_DUMMY = new AbstractGameTeam(null, "Spectators", DyeColor.GRAY) {}; private final AbstractArena arena; private final ButtonAction backAction; private final ButtonAction hereAction; protected SelectTeamUI(Plugin plugin, Player player, AbstractArena arena, List<AbstractGameTeam> teams, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_SELECT_TEAM, () -> teams, Math.min(54, Utils.transformToInventorySize(teams.size()) + 9)); this.arena = arena; this.backAction = backAction; this.hereAction = () -> { new SelectTeamUI(plugin, player, arena, teams, backAction); }; build(); } @Override protected GUIButton createButton(AbstractGameTeam team) { ItemStackBuilder itemStackBuilder = new ItemStackBuilder().material(Material.YELLOW_WOOL).color(team.getColor()); if (team == SPEC_DUMMY) { itemStackBuilder.name(ChatColor.GRAY + CoreLang.SPECTATOR.getMessage(getPlayer())); return new SimpleButton(itemStackBuilder).action(() -> { new MoveSpectatorsUI(plugin, player, arena, hereAction); }); } else { itemStackBuilder.name(Utils.getColorFromDye(team.getColor()) + team.getName()); return new SimpleButton(itemStackBuilder).action(() -> { new MovePlayersUI(plugin, player, arena, team, hereAction); }); } } @Override public void buildPage() { super.buildPage(); addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer())).action(backAction), getSize()-9); } }
2,533
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GiveCoHostUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/GiveCoHostUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.player.IPlayer; import me.patothebest.gamecore.player.PlayerManager; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.stream.Collectors; public class GiveCoHostUI extends StaticPaginatedUI<Player> { private final PlayerManager playerManager; private final PrivateArena privateArena; private final ButtonAction backAction; private final ItemStack giveCoHost; GiveCoHostUI(Plugin plugin, PlayerManager playerManager, Player player, PrivateArena privateArena, ItemStack giveCoHost, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_ADD_CO_HOST, () -> privateArena.getArena().getPlayers().stream() .filter(player1 -> !privateArena.getCoHosts().contains(player1.getName())).collect(Collectors.toList())); this.playerManager = playerManager; this.privateArena = privateArena; this.backAction = backAction; this.giveCoHost = giveCoHost; build(); } @Override protected GUIButton createButton(Player coHost) { ItemStackBuilder makeCoHost = new ItemStackBuilder().skullOwner(coHost.getName()).name(CoreLang.GUI_PRIVATE_ARENA_GIVE_CO_HOST.replace(getPlayer(), coHost.getName())); return new ConfirmButton(makeCoHost, giveCoHost, makeCoHost, () -> { privateArena.getCoHosts().add(coHost.getName()); IPlayer coHostIPlayer = playerManager.getPlayer(player); if (coHostIPlayer.isInArena() && coHostIPlayer.getCurrentArena() == privateArena.getArena() && !privateArena.getArena().isInGame()) { coHost.getInventory().setItem(7, new ItemStackBuilder().material(Material.COMPARATOR).name(player, CoreLang.GUI_PRIVATE_ARENA_LOBBY_MENU)); } CoreLang.GUI_PRIVATE_ARENA_CO_HOST_MADE.replaceAndSend(getPlayer(), coHost.getName()); new GiveCoHostUI(plugin, playerManager, player, privateArena, giveCoHost, backAction); }); } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); } }
2,797
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
RemovePlayerFromWhitelistUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/RemovePlayerFromWhitelistUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.stream.Collectors; public class RemovePlayerFromWhitelistUI extends StaticPaginatedUI<String> { private final PrivateArena privateArena; private final ButtonAction backAction; private final ItemStack displayItem; RemovePlayerFromWhitelistUI(Plugin plugin, Player player, PrivateArena privateArena, ItemStack displayItem, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_REMOVE_PLAYERS_FROM_WHITELIST, () -> privateArena.getWhitelistedPlayers().stream() .filter(s -> !privateArena.getOwnerName().equalsIgnoreCase(s)).collect(Collectors.toList())); this.privateArena = privateArena; this.backAction = backAction; this.displayItem = displayItem; build(); } @Override protected GUIButton createButton(String whitelistedPlayer) { ItemStackBuilder removeCoHostItem = new ItemStackBuilder().skullOwner(whitelistedPlayer).name(CoreLang.GUI_PRIVATE_ARENA_REMOVE_PLAYER_FROM_WHITELIST.replace(getPlayer(), whitelistedPlayer)); return new ConfirmButton(removeCoHostItem, displayItem, removeCoHostItem, () -> { privateArena.getWhitelistedPlayers().remove(whitelistedPlayer); CoreLang.GUI_PRIVATE_ARENA_PLAYER_REMOVED_ROM_WHITELIST.replaceAndSend(getPlayer(), whitelistedPlayer); new RemovePlayerFromWhitelistUI(plugin, getPlayer(), privateArena, displayItem, backAction); }); } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); } }
2,267
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PrivateArenaUIFactory.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/PrivateArenaUIFactory.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.privatearenas.PrivateArena; import org.bukkit.entity.Player; public interface PrivateArenaUIFactory { PrivateArenaUI createPrivateArenaMenu(Player player, PrivateArena privateArena); }
274
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
MoveSpectatorsUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/MoveSpectatorsUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.gui.inventory.page.DualListPage; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.AbstractGameTeam; import me.patothebest.gamecore.event.player.ArenaLeaveEvent; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.plugin.Plugin; public class MoveSpectatorsUI extends DualListPage<Player> { private final AbstractArena arena; private final ButtonAction backAction; protected MoveSpectatorsUI(Plugin plugin, Player player, AbstractArena arena, ButtonAction backAction) { super(plugin, player, "", arena::getPlayers, arena::getSpectators); this.arena = arena; this.backAction = backAction; build(); } @Override protected void buildHeader() { addButton(new PlaceHolder(new ItemStackBuilder() .material(Material.WHITE_WOOL) .name(ChatColor.GRAY + CoreLang.SPECTATOR.getMessage(getPlayer()))), 4); } @Override protected GUIButton createLeftButton(Player player) { ItemStackBuilder item = new ItemStackBuilder().skullOwner(player.getName()).name(ChatColor.GREEN + player.getName()); AbstractGameTeam teamPreference = arena.getTeamPreference(player); if (teamPreference != null) { item.lore(CoreLang.GUI_PRIVATE_ARENA_CURRENT_TEAM.replace(getPlayer(), teamPreference.getName())); } else { item.lore(CoreLang.GUI_PRIVATE_ARENA_NO_CURRENT_TEAM.getMessage(getPlayer())); } item.lore("", CoreLang.GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_SPEC.getMessage(getPlayer())); return new SimpleButton(item).action(() -> { AbstractGameTeam otherTeam = arena.getTeamPreference(player); if(otherTeam != null) { arena.getTeamPreferences().get(otherTeam).remove(player); } if (!arena.getSpectators().contains(player)) { arena.changeToSpectator(player, false); } refresh(); }); } @Override protected GUIButton createRightButton(Player player) { ItemStackBuilder item = new ItemStackBuilder().skullOwner(player.getName()).name(ChatColor.GREEN + player.getName()); item.lore(CoreLang.GUI_PRIVATE_ARENA_CURRENT_SPEC.getMessage(player), "", CoreLang.GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_PLAYER.getMessage(getPlayer())); return new SimpleButton(item).action(() -> { if (arena.getSpectators().contains(player)) { arena.changeToPlayer(player); } refresh(); }); } @Override protected void buildFooter() { addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer())).action(backAction), getSize()-9); } @EventHandler public void onLeave(ArenaLeaveEvent event) { refresh(); } }
3,461
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KickPlayerUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/privatearenas/ui/KickPlayerUI.java
package me.patothebest.gamecore.privatearenas.ui; import me.patothebest.gamecore.gui.inventory.button.ConfirmButton; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.gui.inventory.page.StaticPaginatedUI; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.privatearenas.PrivateArena; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.BackButton; import me.patothebest.gamecore.gui.inventory.button.ButtonAction; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public class KickPlayerUI extends StaticPaginatedUI<Player> { private final PrivateArena privateArena; private final ButtonAction backAction; private final ItemStack displayItem; KickPlayerUI(Plugin plugin, Player player, PrivateArena privateArena, ItemStack displayItem, ButtonAction backAction) { super(plugin, player, CoreLang.GUI_PRIVATE_ARENA_KICK_PLAYERS, () -> privateArena.getArena().getPlayers()); this.privateArena = privateArena; this.displayItem = displayItem; this.backAction = backAction; build(); } @Override protected GUIButton createButton(Player kickedPlayer) { ItemStackBuilder kickPlayerItem = new ItemStackBuilder().skullOwner(kickedPlayer.getName()).name(CoreLang.GUI_PRIVATE_ARENA_KICK.replace(getPlayer(), kickedPlayer.getName())); if (privateArena.getCoHosts().contains(kickedPlayer.getName()) || privateArena.getOwner() == kickedPlayer) { kickPlayerItem.lore(CoreLang.GUI_PRIVATE_ARENA_CANT_KICK.getMessage(getPlayer())); return new SimpleButton(kickPlayerItem); } else { return new ConfirmButton(kickPlayerItem, displayItem, kickPlayerItem, () -> { privateArena.getArena().removePlayer(kickedPlayer); CoreLang.GUI_PRIVATE_ARENA_KICKED.replaceAndSend(getPlayer(), kickedPlayer.getName()); new KickPlayerUI(plugin, getPlayer(), privateArena, displayItem, backAction); }); } } @Override protected void buildFooter() { addButton(new BackButton(getPlayer(), backAction), 47); } }
2,352
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ActionBar.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/actionbar/ActionBar.java
package me.patothebest.gamecore.actionbar; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.util.Utils; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.entity.Player; import java.lang.reflect.Method; public class ActionBar { // -------------------------------------------- // // CONSTANTS // -------------------------------------------- // private static final boolean useChatSerializer = Utils.SERVER_VERSION.contains("v1_8_R1") || Utils.SERVER_VERSION.contains("v1_7"); private static final boolean useReflection = useChatSerializer || Utils.SERVER_VERSION.contains("v1_8_R2") || Utils.SERVER_VERSION.contains("v1_8_R3") || Utils.SERVER_VERSION.contains("v1_9_R1"); private static final Class<?> packetPlayOutChatClass = Utils.getNMSClass("PacketPlayOutChat"); private static final Class<?> chatSerializerClass = Utils.getNMSClassOrNull("ChatSerializer"); private static final Class<?> chatComponentTextClass = Utils.getNMSClass("ChatComponentText"); private static final Class<?> iChatBaseComponentClass = Utils.getNMSClass("IChatBaseComponent"); private static final Method serializeMethod = Utils.getMethodOrNull(chatSerializerClass, "a", String.class); // -------------------------------------------- // // PUBLIC METHOD // -------------------------------------------- // public static void sendActionBar(Player player, ILang message) { sendActionBar(player, message.getMessage(player)); } public static void sendActionBar(Player player, String message) { if (!useReflection) { player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message)); return; } try { Object packetPlayOutChat; // this will define if we use the 1.8 protocol version or the 1.8+ version if (useChatSerializer) { Object serializedText = iChatBaseComponentClass.cast(serializeMethod.invoke(chatSerializerClass, "{\"text\": \"" + message + "\"}")); packetPlayOutChat = packetPlayOutChatClass.getConstructor(iChatBaseComponentClass, Byte.TYPE).newInstance(serializedText, (byte)2); } else { Object chatBaseComponent = chatComponentTextClass.getConstructor(String.class).newInstance(message); packetPlayOutChat = packetPlayOutChatClass.getConstructor(iChatBaseComponentClass, Byte.TYPE).newInstance(chatBaseComponent, (byte)2); } // send the packet Utils.sendPacket(player, packetPlayOutChat); } catch (Exception ex) { // in case any errors, print them ex.printStackTrace(); } } }
2,805
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Activatable.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/Activatable.java
package me.patothebest.gamecore.injector; /** * The Interface Activatable. */ public interface Activatable { /** * Method called on plugin enable. */ default void onEnable() {} /** * Method called on plugin disable. */ default void onDisable() {} }
291
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
InstanceProvider.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/InstanceProvider.java
package me.patothebest.gamecore.injector; public interface InstanceProvider<T> { /** * Provides an instance of {@code T}. Must never return {@code null}. */ T newInstance(); }
197
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BukkitInjector.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/BukkitInjector.java
package me.patothebest.gamecore.injector; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Stage; import me.patothebest.gamecore.CorePlugin; /** * The class that creates the injector * * @param <T> the plugin */ public class BukkitInjector<T extends CorePlugin> { /** The injector. */ private final Injector injector; /** * Instantiates a new injector. * * @param abstractJavaPlugin the plugin */ public BukkitInjector(T abstractJavaPlugin) { this.injector = Guice.createInjector(Stage.PRODUCTION, new BukkitModule<>(abstractJavaPlugin)); } }
642
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BukkitModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/BukkitModule.java
package me.patothebest.gamecore.injector; import com.google.inject.AbstractModule; import me.patothebest.gamecore.CorePlugin; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; /** * A Guice module used by our plugins that can be * installed in guice * * @param <T> the generic type */ public class BukkitModule<T extends CorePlugin> extends AbstractModule { /** The plugin. */ private final T abstractJavaPlugin; /** * Instantiates a new bukkit module. * * @param abstractJavaPlugin the plugin */ public BukkitModule(T abstractJavaPlugin) { this.abstractJavaPlugin = abstractJavaPlugin; } /* (non-Javadoc) * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { bind(Plugin.class).toInstance(abstractJavaPlugin); bind(JavaPlugin.class).toInstance(abstractJavaPlugin); bind(CorePlugin.class).toInstance(abstractJavaPlugin); abstractJavaPlugin.configureCore(binder()); } }
1,050
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GuiceInjectorAdapter.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/GuiceInjectorAdapter.java
package me.patothebest.gamecore.injector; import com.google.inject.Injector; import javax.inject.Inject; import javax.inject.Provider; /** * An adpater for the injector from the command framework. */ public class GuiceInjectorAdapter implements me.patothebest.gamecore.command.Injector { /** The injector. */ private final Injector injector; /** * Instantiates a new guice injector adapter. * * @param injector the injector */ @Inject public GuiceInjectorAdapter(Injector injector) { this.injector = injector; } /* (non-Javadoc) * @see me.patothebest.core.command.Injector#getProviderOrNull(java.lang.Class) */ @Override public <T> Provider<? extends T> getProviderOrNull(Class<T> cls) { return injector.getProvider(cls); } /* (non-Javadoc) * @see me.patothebest.core.command.Injector#getInstance(java.lang.Class) */ @Override public Object getInstance(Class<?> cls) { return injector.getInstance(cls); } }
1,032
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AbstractBukkitModule.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/injector/AbstractBukkitModule.java
package me.patothebest.gamecore.injector; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.modules.Module; /** * The Class AbstractBukkitModule. * * @param <T> the plugin type */ public abstract class AbstractBukkitModule<T extends CorePlugin> extends AbstractModule { /** The plugin. */ protected final T plugin; /** * Instantiates a new abstract bukkit module. * * @param plugin the plugin */ public AbstractBukkitModule(T plugin) { this.plugin = plugin; } /** * Registers a module. * * @param moduleClazz the module class */ protected void registerModule(Class<? extends Module> moduleClazz) { binder().bind(moduleClazz).in(Singleton.class); plugin.registerModule(moduleClazz); } /** * Registers a module that is not a singleton. * * @param moduleClazz the module class */ protected void registerDynamicModule(Class<? extends Module> moduleClazz) { binder().bind(moduleClazz); plugin.registerModule(moduleClazz); } }
1,176
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Selection.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/selection/Selection.java
package me.patothebest.gamecore.selection; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.vector.Cuboid; import org.bukkit.Location; public class Selection { private Location pointA; private Location pointB; public Location getPointA() { return pointA; } public Selection setPointA(Location pointA) { this.pointA = pointA; return this; } public Location getPointB() { return pointB; } public Selection setPointB(Location pointB) { this.pointB = pointB; return this; } public boolean arePointsSet() { return pointA != null && pointB != null; } public Cuboid toCubiod(String name, AbstractArena arena) { return new Cuboid(name, pointA, pointB, arena); } }
819
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DefaultSelectionManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/selection/DefaultSelectionManager.java
package me.patothebest.gamecore.selection; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.modules.Module; import me.patothebest.gamecore.player.PlayerManager; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.util.HashMap; import java.util.Map; public class DefaultSelectionManager implements SelectionManager, Module { private final Map<String, Selection> selectionMap; public DefaultSelectionManager() { this.selectionMap = new HashMap<>(); } @SuppressWarnings("deprecation") @EventHandler public void onSelect(PlayerInteractEvent event){ if(!event.getPlayer().hasPermission(Permission.SETUP.getBukkitPermission()) || PlayerManager.get().getPlayer(event.getPlayer()).isPlaying()) { return; } if(event.getAction() == Action.RIGHT_CLICK_BLOCK) { if(event.getPlayer().getItemInHand() == null || event.getPlayer().getItemInHand().getType() != Material.BONE) { return; } Selection selection = getOrCreateSelection(event.getPlayer()); selection.setPointB(event.getClickedBlock().getLocation()); event.getPlayer().sendMessage(CoreLang.POINT2_SELECTED.replace(event.getPlayer(), event.getClickedBlock().getLocation().getBlockX() + ", " + event.getClickedBlock().getLocation().getBlockY() + ", " + event.getClickedBlock().getLocation().getBlockZ())); event.setCancelled(true); } if(event.getAction() == Action.LEFT_CLICK_BLOCK) { if(event.getPlayer().getItemInHand() == null || event.getPlayer().getItemInHand().getType() != Material.BONE) { return; } Selection selection = getOrCreateSelection(event.getPlayer()); selection.setPointA(event.getClickedBlock().getLocation()); event.getPlayer().sendMessage(CoreLang.POINT1_SELECTED.replace(event.getPlayer(), event.getClickedBlock().getLocation().getBlockX() + ", " + event.getClickedBlock().getLocation().getBlockY() + ", " + event.getClickedBlock().getLocation().getBlockZ())); event.setCancelled(true); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { selectionMap.remove(event.getPlayer().getName()); } private Selection getOrCreateSelection(Player player) { if(selectionMap.containsKey(player.getName())) { return selectionMap.get(player.getName()); } Selection selection = new Selection(); selectionMap.put(player.getName(), selection); return selection; } @Override public Selection getSelection(Player player) { return selectionMap.get(player.getName()); } }
2,996
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SelectionManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/selection/SelectionManager.java
package me.patothebest.gamecore.selection; import org.bukkit.entity.Player; import org.bukkit.event.Listener; public interface SelectionManager extends Listener { Selection getSelection(Player player); }
211
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ArenaLocation.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/vector/ArenaLocation.java
package me.patothebest.gamecore.vector; import me.patothebest.gamecore.arena.AbstractArena; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Utility; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.util.NumberConversions; import org.bukkit.util.Vector; import java.util.HashMap; import java.util.Map; /** * Represents a 3-dimensional position in an arena world */ public class ArenaLocation extends Location { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private AbstractArena arena; private String worldName; private double x; private double y; private double z; private float pitch; private float yaw; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // /** * Constructs a new Location with the given coordinates * * @param world The world in which this location resides * @param x The x-coordinate of this new location * @param y The y-coordinate of this new location * @param z The z-coordinate of this new location */ public ArenaLocation(World world, final double x, final double y, final double z) { this(null, world, x, y, z, 0, 0); } /** * Constructs a new Location with the given coordinates * * @param arena the arena * @param world The world in which this location resides * @param x The x-coordinate of this new location * @param y The y-coordinate of this new location * @param z The z-coordinate of this new location */ public ArenaLocation(final AbstractArena arena, World world, final double x, final double y, final double z) { this(arena, world, x, y, z, 0, 0); } /** * Constructs a new ArenaLocation with the given location * * @param location the locatio */ public ArenaLocation(Location location) { this(null, location.getWorld(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } /** * Constructs a new ArenaLocation with the given location * * @param arena the arena * @param location the locatio */ public ArenaLocation(final AbstractArena arena, Location location) { this(arena, location.getWorld(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } /** * Constructs a new Location with the given coordinates and direction * * @param world The world in which this location resides * @param x The x-coordinate of this new location * @param y The y-coordinate of this new location * @param z The z-coordinate of this new location * @param yaw The absolute rotation on the x-plane, in degrees * @param pitch The absolute rotation on the y-plane, in degrees */ public ArenaLocation(final World world, final double x, final double y, final double z, final float yaw, final float pitch) { this(null, world, x, y, z, yaw, pitch); } /** * Constructs a new Location with the given coordinates and direction * * @param arena the arena * @param world The world in which this location resides * @param x The x-coordinate of this new location * @param y The y-coordinate of this new location * @param z The z-coordinate of this new location * @param yaw The absolute rotation on the x-plane, in degrees * @param pitch The absolute rotation on the y-plane, in degrees */ public ArenaLocation(final AbstractArena arena, final World world, final double x, final double y, final double z, final float yaw, final float pitch) { super(world, x, y, z, yaw, pitch); this.arena = arena; this.worldName = world.getName(); this.x = x; this.y = y; this.z = z; this.pitch = pitch; this.yaw = yaw; this.add(arena.getOffset()); } // -------------------------------------------- // // METHODS // -------------------------------------------- // /** * Sets the {@link #getYaw() yaw} and {@link #getPitch() pitch} to point * in the direction of the vector. * * @param vector the direction vector * @return the same location */ public ArenaLocation setDirection(Vector vector) { /* * Sin = Opp / Hyp * Cos = Adj / Hyp * Tan = Opp / Adj * * x = -Opp * z = Adj */ final double _2PI = 2 * Math.PI; final double x = vector.getX(); final double z = vector.getZ(); if (x == 0 && z == 0) { pitch = vector.getY() > 0 ? -90 : 90; return this; } double theta = Math.atan2(-x, z); yaw = (float) Math.toDegrees((theta + _2PI) % _2PI); double x2 = NumberConversions.square(x); double z2 = NumberConversions.square(z); double xz = Math.sqrt(x2 + z2); pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz)); return this; } /** * Adds the location by another. * * @see Vector * @param vec The other location * @return the same location * @throws IllegalArgumentException for differing worlds */ public ArenaLocation add(Location vec) { if (vec == null || vec.getWorld() != getWorld()) { throw new IllegalArgumentException("Cannot add Locations of differing worlds"); } x += vec.getX(); y += vec.getY(); z += vec.getZ(); return this; } /** * Adds the location by a vector. * * @see Vector * @param vec Vector to use * @return the same location */ public ArenaLocation add(Vector vec) { this.x += vec.getX(); this.y += vec.getY(); this.z += vec.getZ(); return this; } /** * Adds the location by another. Not world-aware. * * @see Vector * @param x X coordinate * @param y Y coordinate * @param z Z coordinate * @return the same location */ public ArenaLocation add(double x, double y, double z) { this.x += x; this.y += y; this.z += z; return this; } /** * Subtracts the location by another. * * @see Vector * @param vec The other location * @return the same location * @throws IllegalArgumentException for differing worlds */ public ArenaLocation subtract(Location vec) { if (vec == null || vec.getWorld() != getWorld()) { throw new IllegalArgumentException("Cannot add Locations of differing worlds"); } x -= vec.getX(); y -= vec.getY(); z -= vec.getZ(); return this; } /** * Subtracts the location by a vector. * * @see Vector * @param vec The vector to use * @return the same location */ public ArenaLocation subtract(Vector vec) { this.x -= vec.getX(); this.y -= vec.getY(); this.z -= vec.getZ(); return this; } /** * Subtracts the location by another. Not world-aware and * orientation independent. * * @see Vector * @param x X coordinate * @param y Y coordinate * @param z Z coordinate * @return the same location */ public ArenaLocation subtract(double x, double y, double z) { this.x -= x; this.y -= y; this.z -= z; return this; } /** * Gets the magnitude of the location, defined as sqrt(x^2+y^2+z^2). The * value of this method is not cached and uses a costly square-root * function, so do not repeatedly call this method to get the location's * magnitude. NaN will be returned if the inner result of the sqrt() * function overflows, which will be caused if the length is too long. Not * world-aware and orientation independent. * * @see Vector * @return the magnitude */ public double length() { return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z)); } /** * Gets the magnitude of the location squared. Not world-aware and * orientation independent. * * @see Vector * @return the magnitude */ public double lengthSquared() { return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z); } /** * Get the distance between this location and another. The value of this * method is not cached and uses a costly square-root function, so do not * repeatedly call this method to get the location's magnitude. NaN will * be returned if the inner result of the sqrt() function overflows, which * will be caused if the distance is too long. * * @see Vector * @param o The other location * @return the distance * @throws IllegalArgumentException for differing worlds */ public double distance(Location o) { return Math.sqrt(distanceSquared(o)); } /** * Get the squared distance between this location and another. * * @see Vector * @param o The other location * @return the distance * @throws IllegalArgumentException for differing worlds */ public double distanceSquared(Location o) { if (o == null) { throw new IllegalArgumentException("Cannot measure distance to a null location"); } else if (o.getWorld() == null || getWorld() == null) { throw new IllegalArgumentException("Cannot measure distance to a null world"); } else if (o.getWorld() != getWorld()) { throw new IllegalArgumentException("Cannot measure distance between " + getWorld().getName() + " and " + o.getWorld().getName()); } return NumberConversions.square(x - o.getX()) + NumberConversions.square(y - o.getY()) + NumberConversions.square(z - o.getZ()); } /** * Performs scalar multiplication, multiplying all components with a * scalar. Not world-aware. * * @param m The factor * @see Vector * @return the same location */ public ArenaLocation multiply(double m) { x *= m; y *= m; z *= m; return this; } /** * Zero this location's components. Not world-aware. * * @see Vector * @return the same location */ public ArenaLocation zero() { x = 0; y = 0; z = 0; return this; } // -------------------------------------------- // // GETTERS AND SETTERS // -------------------------------------------- // /** * Sets the world that this location resides in * * @param world New world that this location resides in */ public void setWorld(World world) { this.worldName = world.getName(); } /** * Gets the world that this location resides in * * @return World that contains this location */ public World getWorld() { if(arena != null) { return arena.getWorld(); } return Bukkit.getWorld(worldName); } /** * Gets the chunk at the represented location * * @return Chunk at the represented location */ public Chunk getChunk() { return getWorld().getChunkAt(this); } /** * Gets the block at the represented location * * @return Block at the represented location */ public Block getBlock() { return getWorld().getBlockAt(this); } /** * Sets the x-coordinate of this location * * @param x X-coordinate */ public void setX(double x) { this.x = x; } /** * Gets the x-coordinate of this location * * @return x-coordinate */ public double getX() { return x; } /** * Gets the floored value of the X component, indicating the block that * this location is contained with. * * @return block X */ public int getBlockX() { return locToBlock(x); } /** * Sets the y-coordinate of this location * * @param y y-coordinate */ public void setY(double y) { this.y = y; } /** * Gets the y-coordinate of this location * * @return y-coordinate */ public double getY() { return y; } /** * Gets the floored value of the Y component, indicating the block that * this location is contained with. * * @return block y */ public int getBlockY() { return locToBlock(y); } /** * Sets the z-coordinate of this location * * @param z z-coordinate */ public void setZ(double z) { this.z = z; } /** * Gets the z-coordinate of this location * * @return z-coordinate */ public double getZ() { return z; } /** * Gets the floored value of the Z component, indicating the block that * this location is contained with. * * @return block z */ public int getBlockZ() { return locToBlock(z); } /** * Sets the yaw of this location, measured in degrees. * <ul> * <li>A yaw of 0 or 360 represents the positive z direction. * <li>A yaw of 180 represents the negative z direction. * <li>A yaw of 90 represents the negative x direction. * <li>A yaw of 270 represents the positive x direction. * </ul> * Increasing yaw values are the equivalent of turning to your * right-facing, increasing the scale of the next respective axis, and * decreasing the scale of the previous axis. * * @param yaw new rotation's yaw */ public void setYaw(float yaw) { this.yaw = yaw; } /** * Gets the yaw of this location, measured in degrees. * <ul> * <li>A yaw of 0 or 360 represents the positive z direction. * <li>A yaw of 180 represents the negative z direction. * <li>A yaw of 90 represents the negative x direction. * <li>A yaw of 270 represents the positive x direction. * </ul> * Increasing yaw values are the equivalent of turning to your * right-facing, increasing the scale of the next respective axis, and * decreasing the scale of the previous axis. * * @return the rotation's yaw */ public float getYaw() { return yaw; } /** * Sets the pitch of this location, measured in degrees. * <ul> * <li>A pitch of 0 represents level forward facing. * <li>A pitch of 90 represents downward facing, or negative y * direction. * <li>A pitch of -90 represents upward facing, or positive y direction. * </ul> * Increasing pitch values the equivalent of looking down. * * @param pitch new incline's pitch */ public void setPitch(float pitch) { this.pitch = pitch; } /** * Gets the pitch of this location, measured in degrees. * <ul> * <li>A pitch of 0 represents level forward facing. * <li>A pitch of 90 represents downward facing, or negative y * direction. * <li>A pitch of -90 represents upward facing, or positive y direction. * </ul> * Increasing pitch values the equivalent of looking down. * * @return the incline's pitch */ public float getPitch() { return pitch; } /** * Gets a unit-vector pointing in the direction that this Location is * facing. * * @return a vector pointing the direction of this location's {@link * #getPitch() pitch} and {@link #getYaw() yaw} */ public Vector getDirection() { Vector vector = new Vector(); double rotX = this.getYaw(); double rotY = this.getPitch(); vector.setY(-Math.sin(Math.toRadians(rotY))); double xz = Math.cos(Math.toRadians(rotY)); vector.setX(-xz * Math.sin(Math.toRadians(rotX))); vector.setZ(xz * Math.cos(Math.toRadians(rotX))); return vector; } /** * Returns the arena that is binded to this location * If there is no arena, it will return null * * @return the arena */ public AbstractArena getArena() { return arena; } /** * Sets the arena for this location * * @param arena the arena for this location */ public void setArena(AbstractArena arena) { this.arena = arena; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Location)) { return false; } final Location other = (Location) obj; if (!this.worldName.equalsIgnoreCase(other.getWorld().getName()) && (this.getWorld() == null || !this.getWorld().equals(other.getWorld()))) { return false; } if (Double.doubleToLongBits(this.x) != Double.doubleToLongBits(other.getX())) { return false; } if (Double.doubleToLongBits(this.y) != Double.doubleToLongBits(other.getY())) { return false; } if (Double.doubleToLongBits(this.z) != Double.doubleToLongBits(other.getZ())) { return false; } if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.getPitch())) { return false; } return Float.floatToIntBits(this.yaw) == Float.floatToIntBits(other.getYaw()); } @Override public int hashCode() { int hash = 3; hash = 19 * hash + (this.getWorld() != null ? this.getWorld().hashCode() : 0); hash = 19 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); hash = 19 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); hash = 19 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); hash = 19 * hash + Float.floatToIntBits(this.pitch); hash = 19 * hash + Float.floatToIntBits(this.yaw); return hash; } @Override public String toString() { return "Location{" + "arena=" + arena.getName() + ",world=" + getWorld() + ",x=" + x + ",y=" + y + ",z=" + z + ",pitch=" + pitch + ",yaw=" + yaw + '}'; } /** * Constructs a new {@link Vector} based on this Location * * @return New Vector containing the coordinates represented by this * Location */ public Vector toVector() { return new Vector(x, y, z); } @Override public Location clone() { return super.clone(); } /** * Safely converts a double (location coordinate) to an int (block * coordinate) * * @param loc Precise coordinate * @return Block coordinate */ public static int locToBlock(double loc) { return NumberConversions.floor(loc); } @Utility public Map<String, Object> serialize() { Map<String, Object> data = new HashMap<>(); data.put("world", this.worldName); data.put("x", this.x); data.put("y", this.y); data.put("z", this.z); data.put("yaw", this.yaw); data.put("pitch", this.pitch); return data; } /** * Required method for deserialization * * @param args map to deserialize * @return deserialized location * @throws IllegalArgumentException if the world don't exists * @see ConfigurationSerializable */ @Deprecated public static ArenaLocation deserialize(Map<String, Object> args) { World world = Bukkit.getWorld((String) args.get("world")); if (world == null) { throw new IllegalArgumentException("unknown world"); } return new ArenaLocation(world, NumberConversions.toDouble(args.get("x")), NumberConversions.toDouble(args.get("y")), NumberConversions.toDouble(args.get("z")), NumberConversions.toFloat(args.get("yaw")), NumberConversions.toFloat(args.get("pitch"))); } /** * Required method for deserialization * * @param args map to deserialize * @param arena the arena * @return deserialized location * @see ConfigurationSerializable */ public static ArenaLocation deserialize(Map<String, Object> args, AbstractArena arena) { return new ArenaLocation(arena, arena.getWorld(), NumberConversions.toDouble(args.get("x")), NumberConversions.toDouble(args.get("y")), NumberConversions.toDouble(args.get("z")), NumberConversions.toFloat(args.get("yaw")), NumberConversions.toFloat(args.get("pitch"))); } }
21,004
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Cuboid.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/vector/Cuboid.java
package me.patothebest.gamecore.vector; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.util.NameableObject; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This class is a region/cuboid from one location to another. It can be used for blocks protection and things like WorldEdit. * This class has been modified for GameCore * * @author desht (Original code), KingFaris10 (Editor of code), PatoTheBest (Editor of the edited code) */ public class Cuboid implements Iterable<Block>, Cloneable, ConfigurationSerializable, NameableObject { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private AbstractArena arena; private final String name; private final String worldName; private final int x1; private final int y1; private final int z1; private final int x2; private final int y2; private final int z2; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // /** * Construct a Cuboid given two Location objects which represent any two corners of the Cuboid. * Note: The 2 locations must be on the same world. * * @param l1 - One of the corners * @param l2 - The other corner */ public Cuboid(String name, Location l1, Location l2) { if(! l1.getWorld().equals(l2.getWorld())) throw new IllegalArgumentException("Locations must be on the same world"); this.name = name; this.worldName = l1.getWorld().getName(); this.x1 = Math.min(l1.getBlockX(), l2.getBlockX()); this.y1 = Math.min(l1.getBlockY(), l2.getBlockY()); this.z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); this.x2 = Math.max(l1.getBlockX(), l2.getBlockX()); this.y2 = Math.max(l1.getBlockY(), l2.getBlockY()); this.z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); } /** * Construct a Cuboid given two Location objects which represent any two corners of the Cuboid. * Note: The 2 locations must be on the same world. * * @param l1 - One of the corners * @param l2 - The other corner */ public Cuboid(String name, Location l1, Location l2, AbstractArena arena) { this(name, l1, l2); this.arena = arena; } /** * Construct a one-block Cuboid at the given Location of the Cuboid. * * @param l1 location of the Cuboid */ public Cuboid(String name, Location l1) { this(name, l1, l1); } /** * Copy constructor. * * @param other - The Cuboid to copy */ private Cuboid(Cuboid other) { this(other.getName(), other.getWorld().getName(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2); } /** * Construct a Cuboid in the given World and xyz co-ordinates * * @param world - The Cuboid's world * @param x1 - X co-ordinate of corner 1 * @param y1 - Y co-ordinate of corner 1 * @param z1 - Z co-ordinate of corner 1 * @param x2 - X co-ordinate of corner 2 * @param y2 - Y co-ordinate of corner 2 * @param z2 - Z co-ordinate of corner 2 */ public Cuboid(String name, World world, int x1, int y1, int z1, int x2, int y2, int z2) { this.name = name; this.worldName = world.getName(); this.x1 = Math.min(x1, x2); this.x2 = Math.max(x1, x2); this.y1 = Math.min(y1, y2); this.y2 = Math.max(y1, y2); this.z1 = Math.min(z1, z2); this.z2 = Math.max(z1, z2); } /** * Construct a Cuboid in the given world name and xyz co-ordinates. * * @param worldName - The Cuboid's world name * @param x1 - X co-ordinate of corner 1 * @param y1 - Y co-ordinate of corner 1 * @param z1 - Z co-ordinate of corner 1 * @param x2 - X co-ordinate of corner 2 * @param y2 - Y co-ordinate of corner 2 * @param z2 - Z co-ordinate of corner 2 */ private Cuboid(String name, String worldName, int x1, int y1, int z1, int x2, int y2, int z2) { this.name = name; this.worldName = worldName; this.x1 = Math.min(x1, x2); this.x2 = Math.max(x1, x2); this.y1 = Math.min(y1, y2); this.y2 = Math.max(y1, y2); this.z1 = Math.min(z1, z2); this.z2 = Math.max(z1, z2); } /** * Construct a Cuboid using a map with the following keys: worldName, x1, x2, y1, y2, z1, z2 * * @param map - The map of keys. */ public Cuboid(Map<String, Object> map, AbstractArena abstractArena) { this.name = (String) map.get("name"); int offsetX = abstractArena.getOffset().getBlockX(); int offsetY = abstractArena.getOffset().getBlockY(); int offsetZ = abstractArena.getOffset().getBlockZ(); this.x1 = (Integer) map.get("x1") + offsetX; this.x2 = (Integer) map.get("x2") + offsetX; this.y1 = (Integer) map.get("y1") + offsetY; this.y2 = (Integer) map.get("y2") + offsetY; this.z1 = (Integer) map.get("z1") + offsetZ; this.z2 = (Integer) map.get("z2") + offsetZ; this.arena = abstractArena; this.worldName = abstractArena.getWorldName(); } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<>(); map.put("name", this.name); if (arena == null) { map.put("worldName", this.getWorld().getName()); } map.put("x1", this.x1); map.put("y1", this.y1); map.put("z1", this.z1); map.put("x2", this.x2); map.put("y2", this.y2); map.put("z2", this.z2); return map; } // -------------------------------------------- // // GETTERS AND SETTERS // -------------------------------------------- // /** * Returns the cuboid name used to easily identify one cuboid from another * * @return the cuboid name */ @Override public String getName() { return name; } /** * Get the Location of the lower northeast corner of the Cuboid (minimum XYZ co-ordinates). * * @return Location of the lower northeast corner */ public Location getLowerNE() { return new Location(this.getWorld(), this.x1, this.y1, this.z1); } /** * Get the Location of the upper southwest corner of the Cuboid (maximum XYZ co-ordinates). * * @return Location of the upper southwest corner */ public Location getUpperSW() { return new Location(this.getWorld(), this.x2, this.y2, this.z2); } /** * Get the blocks in the Cuboid. * * @return The blocks in the Cuboid */ public List<Block> getBlocks() { Iterator<Block> blockI = this.iterator(); List<Block> copy = new ArrayList<>(); while(blockI.hasNext()) copy.add(blockI.next()); return copy; } /** * Get the the centre of the Cuboid. * * @return Location at the centre of the Cuboid */ public Location getCenter() { int x1 = this.getUpperX() + 1; int y1 = this.getUpperY() + 1; int z1 = this.getUpperZ() + 1; return new Location(this.getWorld(), this.getLowerX() + (x1 - this.getLowerX()) / 2.0, this.getLowerY() + (y1 - this.getLowerY()) / 2.0, this.getLowerZ() + (z1 - this.getLowerZ()) / 2.0); } /** * Get the Cuboid's world. * * @return The World object representing this Cuboid's world * @throws IllegalStateException if the world is not loaded */ private World getWorld() { if(arena != null) { return arena.getWorld(); } World world = Bukkit.getWorld(this.worldName); if(world == null) throw new IllegalStateException("World '" + this.worldName + "' is not loaded"); return world; } /** * Get the size of this Cuboid along the X axis * * @return Size of Cuboid along the X axis */ public int getSizeX() { return (this.x2 - this.x1) + 1; } /** * Get the size of this Cuboid along the Y axis * * @return Size of Cuboid along the Y axis */ public int getSizeY() { return (this.y2 - this.y1) + 1; } /** * Get the size of this Cuboid along the Z axis * * @return Size of Cuboid along the Z axis */ public int getSizeZ() { return (this.z2 - this.z1) + 1; } /** * Get the minimum X co-ordinate of this Cuboid * * @return the minimum X co-ordinate */ private int getLowerX() { return this.x1; } /** * Get the minimum Y co-ordinate of this Cuboid * * @return the minimum Y co-ordinate */ private int getLowerY() { return this.y1; } /** * Get the minimum Z co-ordinate of this Cuboid * * @return the minimum Z co-ordinate */ private int getLowerZ() { return this.z1; } /** * Get the maximum X co-ordinate of this Cuboid * * @return the maximum X co-ordinate */ private int getUpperX() { return this.x2; } /** * Get the maximum Y co-ordinate of this Cuboid * * @return the maximum Y co-ordinate */ private int getUpperY() { return this.y2; } /** * Get the maximum Z co-ordinate of this Cuboid * * @return the maximum Z co-ordinate */ private int getUpperZ() { return this.z2; } /** * Return true if the point at (x,y,z) is contained within this Cuboid. * * @param x - The X co-ordinate * @param y - The Y co-ordinate * @param z - The Z co-ordinate * @return true if the given point is within this Cuboid, false otherwise */ private boolean contains(int x, int y, int z) { return x >= this.x1 && x <= this.x2 && y >= this.y1 && y <= this.y2 && z >= this.z1 && z <= this.z2; } /** * Check if the given Block is contained within this Cuboid. * * @param b - The Block to validateLicense for * @return true if the Block is within this Cuboid, false otherwise */ public boolean contains(Block b) { return this.contains(b.getLocation()); } /** * Check if the given Location is contained within this Cuboid. * * @param l - The Location to validateLicense for * @return true if the Location is within this Cuboid, false otherwise */ public boolean contains(Location l) { return getWorld().getName().equals(l.getWorld().getName()) && this.contains(l.getBlockX(), l.getBlockY(), l.getBlockZ()); } /** * Get a list of the chunks which are fully or partially contained in this cuboid. * * @return A list of Chunk objects */ public List<Chunk> getChunks() { List<Chunk> res = new ArrayList<>(); World w = this.getWorld(); int x1 = this.getLowerX() & ~ 0xf; int x2 = this.getUpperX() & ~ 0xf; int z1 = this.getLowerZ() & ~ 0xf; int z2 = this.getUpperZ() & ~ 0xf; for(int x = x1; x <= x2; x += 16) { for(int z = z1; z <= z2; z += 16) { res.add(w.getChunkAt(x >> 4, z >> 4)); } } return res; } public List<Location> getChunkLocations() { List<Location> res = new ArrayList<>(); World w = this.getWorld(); int x1 = this.getLowerX() & ~ 0xf; int x2 = this.getUpperX() & ~ 0xf; int z1 = this.getLowerZ() & ~ 0xf; int z2 = this.getUpperZ() & ~ 0xf; for(int x = x1; x <= x2; x += 16) { for(int z = z1; z <= z2; z += 16) { res.add(new Location(w, x >> 4, 0, z >> 4)); } } return res; } public Iterator<Block> iterator() { return new CuboidIterator(this.getWorld(), this.x1, this.y1, this.z1, this.x2, this.y2, this.z2); } public void show(Player player) { drawStructure(player, false); } public void hide(Player player) { drawStructure(player, true); } private void drawStructure(Player player, boolean original) { drawLine(player, original, x1, y1, z1, x2, y1, z1); drawLine(player, original, x1, y1, z1, x1, y2, z1); drawLine(player, original, x1, y1, z1, x1, y1, z2); drawLine(player, original, x1, y2, z1, x2, y2, z1); drawLine(player, original, x1, y2, z1, x1, y2, z2); drawLine2(player, original, x2, y2, z2, x1, y2, z2); drawLine2(player, original, x2, y2, z2, x2, y1, z2); drawLine2(player, original, x2, y2, z2, x2, y2, z1); drawLine2(player, original, x2, y1, z2, x1, y1, z2); drawLine2(player, original, x2, y1, z2, x2, y1, z1); drawLine(player, original, x1, y1, z2, x1, y2, z2); drawLine(player, original, x2, y1, z1, x2, y2, z1); } private void drawLine(Player player, boolean original, int startx, int starty, int startz, int endx, int endy, int endz) { for(int x = startx; x <= endx; x++) { for(int y = starty; y <= endy; y++) { for(int z = startz; z <= endz; z++) { if(original) { Block block = new Location(getWorld(), x, y, z).getBlock(); player.sendBlockChange(block.getLocation(), block.getType(), block.getData()); } else { player.sendBlockChange(new Location(getWorld(), x, y, z), Material.GLOWSTONE, (byte) 0); } } } } } private void drawLine2(Player player, boolean original, int startx, int starty, int startz, int endx, int endy, int endz) { for(int x = startx; x >= endx; x--) { for(int y = starty; y >= endy; y--) { for(int z = startz; z >= endz; z--) { if(original) { Block block = new Location(getWorld(), x, y, z).getBlock(); player.sendBlockChange(block.getLocation(), block.getType(), block.getData()); } else { player.sendBlockChange(new Location(getWorld(), x, y, z), Material.GLOWSTONE, (byte) 0); } } } } } @Override public Cuboid clone() { try { super.clone(); } catch(CloneNotSupportedException e) { e.printStackTrace(); } return new Cuboid(this); } @Override public String toString() { return "Cuboid: " + this.getWorld().getName() + "," + this.x1 + "," + this.y1 + "," + this.z1 + "=>" + this.x2 + "," + this.y2 + "," + this.z2; } public String toString(CommandSender sender, int number) { return CoreLang.CUBOID_TO_STRING.replace(sender, number, name, this.x1 + "," + this.y1 + "," + this.z1 + "=>" + this.x2 + "," + this.y2 + "," + this.z2); } public Cuboid setArena(AbstractArena arena) { this.arena = arena; return this; } }
15,734
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CuboidIterator.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/vector/CuboidIterator.java
package me.patothebest.gamecore.vector; import org.bukkit.World; import org.bukkit.block.Block; import java.util.Iterator; class CuboidIterator implements Iterator<Block> { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final World w; private final int baseX; private final int baseY; private final int baseZ; private final int sizeX; private final int sizeY; private final int sizeZ; private int x, y, z; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public CuboidIterator(World w, int x1, int y1, int z1, int x2, int y2, int z2) { this.w = w; this.baseX = x1; this.baseY = y1; this.baseZ = z1; this.sizeX = Math.abs(x2 - x1) + 1; this.sizeY = Math.abs(y2 - y1) + 1; this.sizeZ = Math.abs(z2 - z1) + 1; this.x = this.y = this.z = 0; } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public boolean hasNext() { return this.x < this.sizeX && this.y < this.sizeY && this.z < this.sizeZ; } @Override public Block next() { Block b = this.w.getBlockAt(this.baseX + this.x, this.baseY + this.y, this.baseZ + this.z); if (++x >= this.sizeX) { this.x = 0; if (++this.y >= this.sizeY) { this.y = 0; ++this.z; } } return b; } @Override public void remove() { } }
1,663
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BungeeArena.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/bungee/BungeeArena.java
package me.patothebest.gamecore.bungee; import com.google.inject.Injector; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.AbstractGameTeam; import org.bukkit.DyeColor; import java.util.Map; public class BungeeArena extends AbstractArena { public BungeeArena(String name, String worldName, Injector injector) { super(name, worldName, injector); } @Override public void initializePhase() { throw new UnsupportedOperationException("Not supported for bungee arena"); } @Override public void checkWin() { throw new UnsupportedOperationException("Not supported for bungee arena"); } @Override public AbstractGameTeam createTeam(String name, DyeColor color) { throw new UnsupportedOperationException("Not supported for bungee arena"); } @Override public AbstractGameTeam createTeam(Map<String, Object> data) { throw new UnsupportedOperationException("Not supported for bungee arena"); } @Override public int getMinimumRequiredPlayers() { return 0; } }
1,115
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ConfirmCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/commands/ConfirmCommand.java
package me.patothebest.gamecore.commands; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.inject.Singleton; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.command.BaseCommand; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.modules.ParentCommandModule; import me.patothebest.gamecore.util.Callback; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import java.util.concurrent.TimeUnit; @ChildOf(BaseCommand.class) @Singleton public class ConfirmCommand implements ParentCommandModule { private final Cache<CommandSender, Callback<CommandSender>> actionCache = CacheBuilder .newBuilder() .expireAfterAccess(30, TimeUnit.SECONDS) .build(); @Command( aliases = {"confirm"}, min = 0, max = 1, langDescription = @LangDescription( element = "CONFIRM_DESC", langClass = CoreLang.class ) ) public void confirm(CommandContext args, CommandSender sender) throws CommandException { Callback<CommandSender> callback = actionCache.getIfPresent(sender); CommandUtils.validateNotNull(callback, CoreLang.NO_CONFIRMATION); callback.call(sender); } public void addConfiration(CommandSender sender, Callback<CommandSender> callback) { actionCache.put(sender, callback); CoreLang.CONFIRM.sendMessage(sender); } }
1,776
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DebugCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/commands/DebugCommand.java
package me.patothebest.gamecore.commands; import com.google.inject.Inject; import com.google.inject.Provider; import me.patothebest.gamecore.combat.CombatEntry; import me.patothebest.gamecore.command.ChatColor; import me.patothebest.gamecore.command.HiddenCommand; import me.patothebest.gamecore.cosmetics.cage.CageStructure; import me.patothebest.gamecore.cosmetics.cage.model.CageModel; import me.patothebest.gamecore.cosmetics.projectiletrails.ProjectileManager; import me.patothebest.gamecore.cosmetics.shop.ShopFactory; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.scheduler.PluginScheduler; import me.patothebest.gamecore.selection.Selection; import me.patothebest.gamecore.selection.SelectionManager; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.ArenaManager; import me.patothebest.gamecore.combat.CombatDeathEvent; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ListenerModule; import me.patothebest.gamecore.nms.NMS; import me.patothebest.gamecore.player.PlayerManager; import me.patothebest.gamecore.timings.TimingsManager; import me.patothebest.gamecore.util.CancellationDetector; import me.patothebest.gamecore.util.CommandUtils; import me.patothebest.gamecore.vector.Cuboid; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.scheduler.BukkitTask; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; @ModuleName("Debug Command") public class DebugCommand implements ActivableModule, ListenerModule { private final CancellationDetector<BlockBreakEvent> blockBreak = new CancellationDetector<>(BlockBreakEvent.class); private final CancellationDetector<BlockPlaceEvent> blockPlace = new CancellationDetector<>(BlockPlaceEvent.class); private final CancellationDetector<PlayerCommandPreprocessEvent> command = new CancellationDetector<>(PlayerCommandPreprocessEvent.class); private final CancellationDetector<PlayerInteractEvent> interactEvent = new CancellationDetector<>(PlayerInteractEvent.class); private final List<Player> debugPlayers = new ArrayList<>(); private final PluginScheduler pluginScheduler; private final Provider<SelectionManager> selectionManagerProvider; private final Provider<NMS> nms; private final ShopFactory shopFactory; private final ProjectileManager arrowManager; private final PlayerManager playerManager; private final ArenaManager arenaManager; private final CommandsManager<CommandSender> commandsManager; @Inject private DebugCommand(PluginScheduler pluginScheduler, Provider<SelectionManager> selectionManagerProvider, Provider<NMS> nms, ShopFactory shopFactory, ProjectileManager arrowManager, PlayerManager playerManager, ArenaManager arenaManager, CommandsManager<CommandSender> commandsManager) { this.pluginScheduler = pluginScheduler; this.selectionManagerProvider = selectionManagerProvider; this.nms = nms; this.shopFactory = shopFactory; this.arrowManager = arrowManager; this.playerManager = playerManager; this.arenaManager = arenaManager; this.commandsManager = commandsManager; } @Override public void onEnable() { blockBreak.addListener((plugin, event, listener) -> { if (debugPlayers.contains(event.getPlayer())) { CoreLang.EVENT_STATE_CHANGED.replaceAndSend(event.getPlayer(), event.getClass().getSimpleName(), (event.isCancelled() ? ChatColor.RED + "cancelled" : ChatColor.GREEN + "not cancelled"), listener.getClass().getName() + "(" + plugin.getDescription().getFullName() + ")"); } }); blockPlace.addListener((plugin, event, listener) -> { if (debugPlayers.contains(event.getPlayer())) { CoreLang.EVENT_STATE_CHANGED.replaceAndSend(event.getPlayer(), event.getClass().getSimpleName(), (event.isCancelled() ? ChatColor.RED + "cancelled" : ChatColor.GREEN + "not cancelled"), listener.getClass().getName() + "(" + plugin.getDescription().getFullName() + ")"); } }); command.addListener((plugin, event, listener) -> { if (debugPlayers.contains(event.getPlayer())) { CoreLang.EVENT_STATE_CHANGED.replaceAndSend(event.getPlayer(), event.getClass().getSimpleName(), (event.isCancelled() ? ChatColor.RED + "cancelled" : ChatColor.GREEN + "not cancelled"), listener.getClass().getName() + "(" + plugin.getDescription().getFullName() + ")"); } }); interactEvent.addListener((plugin, event, listener) -> { if (debugPlayers.contains(event.getPlayer())) { CoreLang.EVENT_STATE_CHANGED.replaceAndSend(event.getPlayer(), event.getClass().getSimpleName(), (event.isCancelled() ? ChatColor.RED + "cancelled" : ChatColor.GREEN + "not cancelled"), listener.getClass().getName() + "(" + plugin.getDescription().getFullName() + ")"); } }); } @EventHandler public void onQuit(PlayerQuitEvent event) { debugPlayers.remove(event.getPlayer()); } @EventHandler public void onPhaseChange(ArenaPhaseChangeEvent event) { for (Player player : debugPlayers) { player.sendMessage(CoreLang.PREFIX.getMessage(player) + "PhaseChange from: " + event.getOldPhase().getClass() + " to " + event.getNewPhase().getClass()); } } @EventHandler public void onDeath(CombatDeathEvent event) { if (!debugPlayers.contains(event.getPlayer())) { return; } event.getPlayer().sendMessage("Death cause: " + event.getDeathCause().name()); event.getPlayer().sendMessage("Killer: " + event.getKiller()); event.getPlayer().sendMessage("Item: " + event.getItemKilledWith()); event.getPlayer().sendMessage("Entries: "); for (CombatEntry combatEvent : event.getCombatEvents()) { event.getPlayer().sendMessage(combatEvent.getTick() + " - " + combatEvent.getDamageCause().name() + " => " + combatEvent.getDeathCause().name() + ": " + combatEvent.getDamage() + " (" + (Arrays.toString(combatEvent.getDamageOptions())) + getName(combatEvent.getKiller()) + getPlayerName(combatEvent.getPlayerKiller()) + ")"); } } private String getPlayerName(WeakReference<Player> entityWeakReference) { return entityWeakReference == null ? null : entityWeakReference.get() == null ? null : entityWeakReference.get().getName(); } private String getName(WeakReference<Entity> entityWeakReference) { return entityWeakReference == null ? null : entityWeakReference.get() == null ? null : entityWeakReference.get().getName(); } @Command( aliases = {"debug"}, max = 0, langDescription = @LangDescription( element = "DEBUG_MODE", langClass = CoreLang.class ) ) @CommandPermissions(permission = Permission.ADMIN) public void debugBlock(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if (debugPlayers.contains(player)) { debugPlayers.remove(player); player.sendMessage(CoreLang.DEBUG_MODE_TOGGLE.replace(player, CoreLang.GUI_DISABLED.getMessage(player))); } else { debugPlayers.add(player); player.sendMessage(CoreLang.DEBUG_MODE_TOGGLE.replace(player, CoreLang.GUI_ENABLED.getMessage(player))); } } private BukkitTask bukkitTask; @Command( aliases = {"testcage"}, langDescription = @LangDescription( langClass = CoreLang.class, element = "" ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public List<String> test(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); CageModel cageModel = new CageModel(nms.get(), CageStructure.INDIVIDUAL, player.getLocation()); cageModel.spawn(); bukkitTask = pluginScheduler.runTaskTimer(() -> { if (!player.isOnline()) { cageModel.destroy(); bukkitTask.cancel(); return; } cageModel.updateRotation(player.getLocation()); }, 10L, 1L); return null; } @Command( aliases = {"testshop"}, langDescription = @LangDescription( langClass = CoreLang.class, element = "" ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public List<String> test2(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); shopFactory.createShopMenu(player, arrowManager); return null; } @Command( aliases = {"timings"}, langDescription = @LangDescription( langClass = CoreLang.class, element = "" ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public List<String> timings(CommandContext args, CommandSender sender) throws CommandException { TimingsManager.debug = !TimingsManager.debug; return null; } @Command( aliases = {"nextphase"}, usage = "", langDescription = @LangDescription( element = "", langClass = CoreLang.class ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public List<String> nextPhase(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); AbstractArena currentArena = playerManager.getPlayer(player).getCurrentArena(); if (currentArena == null) { return null; } currentArena.nextPhase(); return null; } @Command( aliases = {"checkblocks"}, usage = "[-b(roadcast)]", flags = "b", langDescription = @LangDescription( element = "", langClass = CoreLang.class ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public void checkblocks(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); Selection selection = selectionManagerProvider.get().getSelection(player); CommandUtils.validateTrue(selection != null && selection.arePointsSet(), CoreLang.SELECT_AN_AREA); Cuboid cuboid = selection.toCubiod("temp", null); List<ChunkSnapshot> chunkSnapshots = new ArrayList<>(); for (Chunk chunk : cuboid.getChunks()) { chunkSnapshots.add(chunk.getChunkSnapshot()); } pluginScheduler.runTaskAsynchronously(() -> { int blocksToScan = chunkSnapshots.size() * 16 * 16 * 256; int blocksScanned = 0; double interval = blocksToScan / 100.0; long lastSent = 0; player.sendMessage("Scanning area..."); Map<Material, Integer> materialIntegerMap = new HashMap<>(); for (ChunkSnapshot chunkSnapshot : chunkSnapshots) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 256; y++) { org.bukkit.Material blockType = chunkSnapshot.getBlockType(x, y, z); Material material = Material.matchMaterial(blockType); materialIntegerMap.put(material, materialIntegerMap.getOrDefault(material, 0) + 1); blocksScanned++; if (blocksScanned % interval < 1) { double progress = (double) blocksScanned / blocksToScan; if(System.currentTimeMillis() - 50 >= lastSent) { Utils.displayProgress("Scanning area...", progress, Math.ceil(progress * 100.0) + "%", player); lastSent = System.currentTimeMillis(); } } } } } } Map<Integer, List<Map.Entry<Material, Integer>>> mats = new HashMap<>(); for (Map.Entry<Material, Integer> materialIntegerEntry : materialIntegerMap.entrySet()) { int version = materialIntegerEntry.getKey().getMaterialVersion(); if (!mats.containsKey(version)) { mats.put(version, new ArrayList<>()); } mats.get(version).add(materialIntegerEntry); } CommandSender commandSender = args.hasFlag('b') ? Bukkit.getConsoleSender() : player; mats.forEach((integer, entries) -> { StringBuilder materials = new StringBuilder(); int version = integer == 0 ? 8 : integer; materials.append(ChatColor.GREEN); materials.append("1.").append(version).append(" ") .append(ChatColor.YELLOW).append("(").append(entries.size()).append(") :") .append(ChatColor.WHITE); for (int i = 0; i < entries.size(); i++) { if (i != 0) { materials.append(", "); } materials.append(Utils.capitalizeFirstLetter(entries.get(i).getKey().name())); } commandSender.sendMessage(materials.toString()); }); Utils.displayProgress("Scanning area...", 1, 100.0 + "%", player); }); } @Command( aliases = {"printcommands"}, flags = "b", langDescription = @LangDescription( element = "", langClass = CoreLang.class ) ) @HiddenCommand @CommandPermissions(permission = Permission.ADMIN) public void printCommands(CommandContext args, CommandSender sender) throws CommandException { printCommands(commandsManager.getMethods().get(null), "/", new CopyOnWriteArrayList<>()); } private void printCommands(Map<String, Method> methods, String path, List<Method> commands) { methods.forEach((commandName, executor) -> { if (commands.contains(executor)) { return; } commands.add(executor); System.out.println(path + " " + commandName); if (executor != null && commandsManager.getMethods().containsKey(executor)) { printCommands(commandsManager.getMethods().get(executor), path + " " + commandName, commands); } }); } }
16,720
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ArenaSetupCommands.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/commands/setup/ArenaSetupCommands.java
package me.patothebest.gamecore.commands.setup; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.selection.Selection; import me.patothebest.gamecore.selection.SelectionManager; import me.patothebest.gamecore.arena.AbstractArena; import me.patothebest.gamecore.arena.ArenaManager; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.commands.ConfirmCommand; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import javax.inject.Inject; import javax.inject.Provider; import java.util.List; public class ArenaSetupCommands { private final ArenaManager arenaManager; private final Provider<SelectionManager> selectionManagerProvider; private final ConfirmCommand confirmCommand; @Inject private ArenaSetupCommands(ArenaManager arenaManager, Provider<SelectionManager> selectionManagerProvider, ConfirmCommand confirmCommand) { this.arenaManager = arenaManager; this.selectionManagerProvider = selectionManagerProvider; this.confirmCommand = confirmCommand; } @Command( aliases = {"enablearena", "enable"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "ENABLE_ARENA", langClass = CoreLang.class ) ) public List<String> enableArena(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); if(!arena.canArenaBeEnabled(player)) { return null; } // enable the arena arena.enableArena(); player.sendMessage(CoreLang.ARENA_ENABLED.getMessage(player)); arena.save(); return null; } @Command( aliases = {"disablearena", "disable"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "", langClass = CoreLang.class ) ) public List<String> disableArena(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getEnabledArena(args, 0, arenaManager); // disable the arena arena.disableArena(); player.sendMessage(CoreLang.ARENA_DISABLED.getMessage(player)); arena.save(); return null; } @Command( aliases = {"setmaxplayers", "maxplayers"}, usage = "<arena> <amount>", min = 2, max = 2, langDescription = @LangDescription( element = "SET_MAX_PLAYERS", langClass = CoreLang.class ) ) public List<String> setMaxPlayers(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); // change the max player amount arena.setMaxPlayers(args.getInteger(1)); player.sendMessage(CoreLang.MAX_PLAYERS_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"setminplayers", "minplayers"}, usage = "<arena> <amount>", min = 2, max = 2, langDescription = @LangDescription( element = "SET_MIN_PLAYERS", langClass = CoreLang.class ) ) public List<String> setMinPlayers(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); // change the max player amount arena.setMinPlayers(args.getInteger(1)); player.sendMessage(CoreLang.MIN_PLAYERS_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"setarenaarea", "setarea"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "SET_ARENA_AREA", langClass = CoreLang.class ) ) public List<String> setArenaArea(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); Selection selection = selectionManagerProvider.get().getSelection(player); CommandUtils.validateTrue(selection != null && selection.arePointsSet(), CoreLang.SELECT_AN_AREA); // set the arena area arena.setArea(selection.toCubiod(arena.getName(), arena)); player.sendMessage(CoreLang.ARENA_AREA_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"setlobbyarea"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "SET_LOBBY_AREA", langClass = CoreLang.class ) ) public List<String> setLobbyArea(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); Selection selection = selectionManagerProvider.get().getSelection(player); CommandUtils.validateTrue(selection != null && selection.arePointsSet(), CoreLang.SELECT_AN_AREA); // set the arena area arena.setLobbyArea(selection.toCubiod(arena.getName(), arena)); player.sendMessage(CoreLang.ARENA_LOBBY_AREA_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"showarena", "showarenaarea"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "SHOW_ARENA_AREA", langClass = CoreLang.class ) ) public List<String> showArenaArea(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); if(arena.getArea() == null) { player.sendMessage(CoreLang.NO_AREA_SET.getMessage(player)); } else { arena.getArea().show(player); player.sendMessage(CoreLang.AREA_SHOWN.getMessage(player)); } return null; } @Command( aliases = {"hidearena", "hidearenaarea"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "HIDE_ARENA_AREA", langClass = CoreLang.class ) ) public List<String> hideArenaArea(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); arena.getArea().hide(player); player.sendMessage(CoreLang.AREA_HIDE.getMessage(player)); return null; } @Command( aliases = {"setlobby", "setlobbylocation"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "SET_LOBBY_LOCATION", langClass = CoreLang.class ) ) public List<String> setLobbyLocation(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); // set the lobby location of the arena arena.setLobbyLocation(player.getLocation()); player.sendMessage(CoreLang.LOBBY_LOCATION_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"setspec", "setspectator"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "SET_SPECTATOR_LOCATION", langClass = CoreLang.class ) ) public List<String> setSpectatorLocation(CommandContext args, CommandSender sender) throws CommandException { Player player = CommandUtils.getPlayer(sender); if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getDisabledArena(args, 0, arenaManager); // set the lobby location of the arena arena.setSpectatorLocation(player.getLocation()); player.sendMessage(CoreLang.SPECTATOR_LOCATION_SET.getMessage(player)); arena.save(); return null; } @Command( aliases = {"teleport", "tp"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "TELEPORT_TO_ARENA", langClass = CoreLang.class ) ) public List<String> teleport(CommandContext args, CommandSender sender) throws CommandException { if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } Player player = CommandUtils.getPlayer(sender); AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); player.teleport(arena.getWorld().getSpawnLocation()); player.sendMessage(CoreLang.TELEPORTED_TO_ARENA.getMessage(player)); return null; } @Command( aliases = {"check", "revise", "isready", "ready"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "TELEPORT_TO_ARENA", langClass = CoreLang.class ) ) public List<String> check(CommandContext args, CommandSender sender) throws CommandException { if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); if (arena.canArenaBeEnabled(sender)) { CoreLang.READY_ARENA.sendMessage(sender); } return null; } @Command( aliases = {"delete", "remove"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "DELETE_ARENA", langClass = CoreLang.class ) ) public List<String> delete(CommandContext args, CommandSender sender) throws CommandException { if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); confirmCommand.addConfiration(sender, (commandSender) -> { arena.delete(); arenaManager.getArenas().remove(arena.getName()); CoreLang.ARENA_DELETED.sendMessage(commandSender); }); return null; } @Command( aliases = {"clear"}, usage = "<arena>", min = 1, max = 1, langDescription = @LangDescription( element = "CLEAR_ARENA", langClass = CoreLang.class ) ) public List<String> clear(CommandContext args, CommandSender sender) throws CommandException { if(args.getSuggestionContext() != null) { if(args.getSuggestionContext().getIndex() == 0) { return CommandUtils.complete(args.getString(0), arenaManager); } return null; } AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager); confirmCommand.addConfiration(sender, (commandSender) -> { arena.getArenaFile().delete(); arena.destroy(); arenaManager.createArena(arena.getName()); CoreLang.ARENA_CLEARED.sendMessage(commandSender); }); return null; } }
15,584
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z