diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index f9412d0..9c59af1 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -1,6 +1,8 @@ name: Java CI -on: [push] +on: + push: + pull_request: jobs: build: @@ -8,12 +10,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v6 + - name: Set up JDK 25 + uses: actions/setup-java@v5 with: - java-version: 1.8 - - name: Grant execute permission for gradlew - run: chmod +x gradlew + distribution: temurin + java-version: '25' + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 - name: Build with Gradle run: ./gradlew build diff --git a/build.gradle b/build.gradle index 7e979da..9407685 100644 --- a/build.gradle +++ b/build.gradle @@ -1,30 +1,31 @@ plugins { - id "org.sonarqube" version "2.6" + id 'java' + id 'idea' } -apply plugin: 'java' -apply plugin: 'idea' -archivesBaseName = 'minicat' version = '1.0-SNAPSHOT' +base { + archivesName = 'minicat' +} + repositories { mavenCentral() - //mavenLocal() Enable to compile with BielAPI preinstalled on mavenlocal - /* maven{ - //Repository url is ok, but server seems to be (temporarily, 02/01/17) serving wrong content - //url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' - }*/ + mavenLocal() maven { - url "https://hub.spigotmc.org/nexus/content/repositories/snapshots" + url = uri('https://repo.papermc.io/repository/maven-public/') } maven { - url = "https://oss.sonatype.org/content/repositories/snapshots/" + url = uri('https://jitpack.io') } } -jar { - +java { + toolchain { + languageVersion = JavaLanguageVersion.of(25) + } } + def defaultEncoding = 'UTF-8' compileJava{ options.encoding = defaultEncoding @@ -33,18 +34,21 @@ compileTestJava{ options.encoding = defaultEncoding } dependencies { - compile group: 'com.google.guava', name: 'guava', version: '19.0' - compile 'org.apache.commons:commons-io:1.3.2' - //Enable if you have BielAPI installed on maven local - //compile 'BielAPI:BielAPI:0.0.8-SNAPSHOT' - compile fileTree(dir: 'lib', include: '*.jar') - //Enable to use automatic download, when avaliable - //compile 'org.spigotmc:spigot-api:1.10-R0.1-SNAPSHOT' -// compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.15' - - compileOnly "org.spigotmc:spigot-api:1.16.4-R0.1-SNAPSHOT" -// compileOnly "org.spigotmc:spigot:1.16.4-R0.1-SNAPSHOT" - testCompileOnly "org.spigotmc:spigot-api:1.16.4-R0.1-SNAPSHOT" + compileOnly 'com.google.guava:guava:33.6.0-jre' + compileOnly 'commons-io:commons-io:2.21.0' + compileOnly 'commons-lang:commons-lang:2.6' + compileOnly 'com.mysql:mysql-connector-j:9.6.0' + compileOnly 'BielAPI:BielAPI:0.0.10-SNAPSHOT' + compileOnly fileTree(dir: 'lib', include: '*.jar', exclude: [ + 'BielAPI-*.jar', + 'NametagEdit*.jar', + 'spigot-*.jar' + ]) + compileOnly 'io.papermc.paper:paper-api:26.2.build.92-stable' + compileOnly('com.github.decentsoftware-eu.decentholograms:plugin:2.10.1') { + transitive = false + } + testCompileOnly 'io.papermc.paper:paper-api:26.2.build.92-stable' } @@ -55,4 +59,4 @@ task deploy(type: Copy){ } into 'F:\\Servers MC\\Lobby - 1.9\\plugins' } -deploy.dependsOn assemble \ No newline at end of file +deploy.dependsOn assemble diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 6dcdf36..7c56585 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3975c4a --- /dev/null +++ b/settings.gradle @@ -0,0 +1,5 @@ +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' +} + +rootProject.name = 'minicat' diff --git a/src/main/java/com/biel/lobby/Com.java b/src/main/java/com/biel/lobby/Com.java index 5427bc3..af42ea9 100644 --- a/src/main/java/com/biel/lobby/Com.java +++ b/src/main/java/com/biel/lobby/Com.java @@ -6,10 +6,6 @@ import java.util.UUID; import java.util.stream.Stream; -import com.gmail.filoghost.holographicdisplays.api.Hologram; -import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; -import com.gmail.filoghost.holographicdisplays.api.VisibilityManager; -import com.nametagedit.plugin.NametagEdit; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -17,12 +13,14 @@ import com.biel.lobby.utilities.CBUtils; import com.biel.lobby.utilities.ColorConverter; +import com.biel.lobby.utilities.HologramFacade; import com.biel.lobby.utilities.Options; +import com.biel.lobby.utilities.PaperMessages; +import com.biel.lobby.utilities.PlayerTagState; import com.biel.lobby.utilities.ScoreBoardUpdater; import com.biel.lobby.utilities.Utils; import com.biel.lobby.utilities.data.DataAPI; import com.biel.lobby.utilities.data.PlayerData; -import com.connorlinfoot.titleapi.TitleAPI; public class Com { //HIO @@ -71,22 +69,20 @@ public static void teleportPlayerToLobby(Player p){ } - private static HashMap playerHologramMap = new HashMap(); + private static HashMap playerHologramMap = new HashMap(); private static void showRanking(Player player) { - Hologram hologram; + HologramFacade.Handle hologram; if(playerHologramMap.containsKey(player.getUniqueId())) { hologram = playerHologramMap.get(player.getUniqueId()); hologram.clearLines(); } else { Location hologramLocation = new Location(getLobbyWorld(), -283, 72.5, 26); - hologram = HologramsAPI.createHologram(getPlugin(), hologramLocation); + hologram = HologramFacade.create(hologramLocation); playerHologramMap.put(player.getUniqueId(), hologram); } - VisibilityManager visibilityManager = hologram.getVisibilityManager(); - visibilityManager.showTo(player); - visibilityManager.setVisibleByDefault(false); + hologram.showOnlyTo(player); hologram.appendTextLine(ChatColor.AQUA + "MINICAT RANKING"); hologram.appendTextLine(""); @@ -135,10 +131,10 @@ public static void setHeadColor(Player ply, ChatColor color){ setHeadColor(ply, ColorConverter.chatToRaw(color)); } public static void setHeadColor(Player ply, String color){ - NametagEdit.getApi().setPrefix(ply, color); + PlayerTagState.setPrefix(ply, color); } public static void setSuffix(Player ply, String suffix){ - NametagEdit.getApi().setSuffix(ply, suffix); + PlayerTagState.setSuffix(ply, suffix); } public static void displayRanking(Player p){ if(Com.getDataAPI().isInDatalessMode()){ @@ -266,12 +262,13 @@ public static void playMinicatAnimation(Player p){ f.add(ChatColor.WHITE + "" + bold + "MINICAT"); int i = 0; for (String s : f){ - Bukkit.getScheduler().runTaskLater(getPlugin(), () -> TitleAPI.sendTitle(p,0,6,0,s,Integer.toString(Bukkit.getOnlinePlayers().size())), 4 * i + 14 + (CBUtils.getPing(p) * 20 / 1000)); + Bukkit.getScheduler().runTaskLater(getPlugin(), () -> PaperMessages.showTitle(p, 0, 6, 0, s, + Integer.toString(Bukkit.getOnlinePlayers().size())), 4 * i + 14 + (CBUtils.getPing(p) * 20 / 1000)); i++; } } public static Material getSkullIconMaterial(Player p){ - Material m = Material.LEGACY_SKULL_ITEM; + Material m = Material.PLAYER_HEAD; if(Stream.of("amiguet", "pilota", "ball", "").anyMatch(s -> (p.getName().equalsIgnoreCase(s) || p.getName().contains(s)))) m = Material.SLIME_BALL; return m; diff --git a/src/main/java/com/biel/lobby/GestorMapes.java b/src/main/java/com/biel/lobby/GestorMapes.java index ef1f1f3..cbb61e7 100644 --- a/src/main/java/com/biel/lobby/GestorMapes.java +++ b/src/main/java/com/biel/lobby/GestorMapes.java @@ -8,14 +8,14 @@ import java.util.List; import java.util.stream.Collectors; -import com.connorlinfoot.bountifulapi.BountifulAPI; +import com.biel.lobby.utilities.PaperMessages; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.material.Wool; import com.biel.BielAPI.Utils.IconMenu; import com.biel.BielAPI.Utils.Pair; @@ -26,6 +26,8 @@ public class GestorMapes implements Listener{ + public enum InstanceRemovalResult { REMOVED, NOT_FOUND, HAS_PLAYERS, EDIT_MODE, UNLOAD_FAILED } + public enum InstanceJoinResult { JOINED, NOT_FOUND, UNAVAILABLE } public lobby plugin; ArrayList> auto_ratings; ArrayList Mapes = new ArrayList<>(); @@ -36,7 +38,7 @@ public GestorMapes() { //Mapes.add(new ContenidorJoc(ObsidianDefenders.class, "Obsidian defenders", Material.OBSIDIAN, DevelopmentState.NotWorking)); Mapes.add(new ContenidorJoc(Spleef.class, "Spleef", Material.SNOW, DevelopmentState.Release)); - Mapes.add(new ContenidorJoc(RainbowClay.class, "Rainbow Clay", Material.LEGACY_HARD_CLAY, DevelopmentState.Beta)); + Mapes.add(new ContenidorJoc(RainbowClay.class, "Rainbow Clay", Material.RED_TERRACOTTA, DevelopmentState.Beta)); Mapes.add(new ContenidorJoc(Torres.class, "Torres de defensa", Material.ARROW, DevelopmentState.Beta)); Mapes.add(new ContenidorJoc(Quakecraft.class, "Quakecraft", Material.STONE_HOE, DevelopmentState.Beta)); Mapes.add(new ContenidorJoc(Dominion.class, "Dominion", Material.DIAMOND, DevelopmentState.Beta)); @@ -65,7 +67,9 @@ public GestorMapes() { Mapes.add(new ContenidorJoc(PilotaSplash.class, "Pilota Splash", Material.SLIME_BALL, DevelopmentState.Alpha)); //Mapes.add(new ContenidorJoc(TempleQuest.class, "Temple Quest", Material.QUARTZ_BLOCK, DevelopmentState.InDevelopment)); Mapes.add(new ContenidorJoc(OneInTheChamber.class, "OneInTheChamber", Material.BOW, DevelopmentState.Alpha)); - Mapes.add(new ContenidorJoc(BedWars.class, "Bed Wars", Material.RED_BED, DevelopmentState.InDevelopment)); + // No Mapes/BedWars template exists in either recovered server tree. + // Keep the implementation source, but do not advertise an instance that cannot be created. + // Mapes.add(new ContenidorJoc(BedWars.class, "Bed Wars", Material.RED_BED, DevelopmentState.InDevelopment)); } public void queryAutoRatings() { auto_ratings = Com.getDataAPI().getAutoRating(); @@ -107,6 +111,33 @@ public ArrayList getAllInstances(){ } return all; } + public List getAllGameInstances(){ + return getAllInstances().stream() + .filter(Joc.class::isInstance) + .map(Joc.class::cast) + .collect(Collectors.toList()); + } + public InstanceRemovalResult removeGameInstance(String worldName){ + for (ContenidorMapa container : Mapes){ + if (!(container instanceof ContenidorJoc)) continue; + ContenidorJoc gameContainer = (ContenidorJoc) container; + for (Joc game : new ArrayList<>(gameContainer.Instàncies)){ + if (game.getMapName().equalsIgnoreCase(worldName)){ + return gameContainer.removeMap(game); + } + } + } + return InstanceRemovalResult.NOT_FOUND; + } + public InstanceJoinResult joinGameInstance(Player player, String worldName){ + for (Joc game : getAllGameInstances()){ + if (!game.getMapName().equalsIgnoreCase(worldName)) continue; + if (!game.canJoin(player)) return InstanceJoinResult.UNAVAILABLE; + game.Join(player); + return InstanceJoinResult.JOINED; + } + return InstanceJoinResult.NOT_FOUND; + } public Mapa getMapWherePlayerIs(Player p){ if (lobby.isOnLobby(p)){return null;} for(Mapa m : getAllInstances()){ @@ -117,6 +148,14 @@ public Mapa getMapWherePlayerIs(Player p){ //Bukkit.broadcastMessage("Jugador desaparegut"); return null; } + public Joc createGameInstance(String gameName, Integer mapId){ + for (ContenidorMapa container : Mapes){ + if (container instanceof ContenidorJoc && container.ClassMapa.getSimpleName().equalsIgnoreCase(gameName)){ + return ((ContenidorJoc) container).addMap(mapId); + } + } + return null; + } public abstract class ContenidorMapa implements Listener{ public lobby plugin; @@ -307,25 +346,36 @@ public void onPlayerChangedWorld(PlayerChangedWorldEvent evt) { if (map != null) { checkNecessary(map); - } + } + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent evt) { + Joc map = getInstànciaFromWorld(evt.getPlayer().getWorld()); + if (map == null) return; + Bukkit.getScheduler().runTask(plugin, () -> checkNecessary(map)); } void checkNecessary(Joc map){ - if (map.getWorld() == null){ Bukkit.broadcastMessage("WORLD: null");return;} + if (!Instàncies.contains(map) || map.getWorld() == null) return; if(map.getEditMode())return; if (map.getWorld().getPlayers().size() == 0){ - //map.JocFinalitzat(); - map.clearExternals(); - map.deleteVirtualWorld(); - Instàncies.remove(map); - map.destroyEventBus(); - System.gc(); - //map = null; - //Bukkit.broadcastMessage("Mapa esborrat!"); + removeMap(map); } } + InstanceRemovalResult removeMap(Joc map){ + if (!Instàncies.contains(map)) return InstanceRemovalResult.NOT_FOUND; + if (map.getWorld() == null) return InstanceRemovalResult.UNLOAD_FAILED; + if (!map.getWorld().getPlayers().isEmpty()) return InstanceRemovalResult.HAS_PLAYERS; + if (map.getEditMode()) return InstanceRemovalResult.EDIT_MODE; + if (!map.deleteVirtualWorld()) return InstanceRemovalResult.UNLOAD_FAILED; + map.clearAllExternals(); + Instàncies.remove(map); + map.destroyEventBus(); + return InstanceRemovalResult.REMOVED; + } public DyeColor getGameColor(Joc joc){ switch(joc.getGameState()){ case InGame: @@ -388,31 +438,36 @@ public void ObrirMenu(Player ply){ if(this.getMapCount() == 0) { String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No hi ha mapes disponibles"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); ply.playSound(ply.getLocation(), Sound.ENTITY_VILLAGER_NO, 100.0F, 1.0F); return; } for(Joc mapa : Instàncies){ - Wool wool = new Wool(getGameColor(mapa)); - ItemStack stack = wool.toItemStack(); - stack.setAmount(mapa.getPlayers().size()); + ItemStack stack = new ItemStack(getWoolMaterial(getGameColor(mapa))); + stack.setAmount(Math.max(1, mapa.getPlayers().size())); String tStr = new SimpleDateFormat("mm:ss").format(new Date(mapa.tempsTranscorregut()));//Integer.toString(mapa.segonsTranscorreguts()); double gameProgressETA = mapa.getGameProgressETA(); String progressStr = ChatColor.AQUA + "Progrés: " + Math.round(gameProgressETA * 1000) / 10 + "% ETA"; - menu.setOption(Instàncies.indexOf(mapa), stack, mapa.getGameName(),ChatColor.WHITE + mapa.NomWorld, ChatColor.WHITE + mapa.getGameState().name(), ChatColor.GREEN + "Jugadors: " + Integer.toString(mapa.getPlayers().size()), ChatColor.YELLOW + "Espectadors:" + mapa.getSpectators().size(), "Temps: " + tStr, progressStr); + menu.setOption(Instàncies.indexOf(mapa), stack, + ChatColor.GREEN + "ENTRAR: " + mapa.NomWorld, + ChatColor.WHITE + mapa.getGameName(), + ChatColor.WHITE + mapa.getGameState().name(), + ChatColor.GREEN + "Jugadors: " + Integer.toString(mapa.getPlayers().size()), + ChatColor.YELLOW + "Espectadors: " + mapa.getSpectators().size(), + "Temps: " + tStr, progressStr); } MapMode mapMode = tempInstance.getMapMode(); if (!AlgunMapaDisponible() || mapMode == MapMode.MULTIPLE){ - if(mapMode == MapMode.SINGLE)menu.setOption(26, new ItemStack(Material.EMERALD, 1), ChatColor.GREEN + "Afegeix", ChatColor.WHITE + "Crea una nova instància"); + if(mapMode == MapMode.SINGLE)menu.setOption(26, new ItemStack(Material.EMERALD, 1), + ChatColor.GREEN + "Afegeix", ChatColor.WHITE + "Crea una nova instància"); if(mapMode == MapMode.MULTIPLE){ ArrayList multiWorldList = tempInstance.getMultiWorldList(); for (int i = 0; i < multiWorldList.size(); i++) { String name = multiWorldList.get(i); menu.setOption(26 - i, new ItemStack(Material.EMERALD, 1), - ChatColor.GREEN + name, ChatColor.WHITE - + "Crear una nova instància"); + ChatColor.GREEN + name, ChatColor.WHITE + "Crear una nova instància"); } } } @@ -441,9 +496,8 @@ public void openAllGamesMenu(Player ply){ }); List games = getGames(); for(Joc mapa : games){ - Wool wool = new Wool(DyeColor.BLACK); - ItemStack stack = wool.toItemStack(); - stack.setAmount(mapa.getPlayers().size()); + ItemStack stack = new ItemStack(Material.BLACK_WOOL); + stack.setAmount(Math.max(1, mapa.getPlayers().size())); String tStr = new SimpleDateFormat("mm:ss").format(new Date(mapa.tempsTranscorregut()));//Integer.toString(mapa.segonsTranscorreguts()); menu.setOption(games.indexOf(mapa), stack, mapa.getGameName(),ChatColor.WHITE + mapa.getGameName() + " (" + mapa.NomWorld + ")", ChatColor.WHITE + mapa.getGameState().name(), ChatColor.GREEN + "Jugadors: " + Integer.toString(mapa.getPlayers().size()), ChatColor.YELLOW + "Espectadors:" + mapa.getSpectators().size(), "Temps: " + tStr); } @@ -465,4 +519,7 @@ public void openAllGamesMenu(Player ply){ public List getGames() { return getAllInstances().stream().filter(m -> m instanceof Joc).map(m -> (Joc)m).collect(Collectors.toList()); } + private Material getWoolMaterial(DyeColor color) { + return Material.valueOf(color.name() + "_WOOL"); + } } diff --git a/src/main/java/com/biel/lobby/LoginListener.java b/src/main/java/com/biel/lobby/LoginListener.java index 6d261a4..7201c13 100644 --- a/src/main/java/com/biel/lobby/LoginListener.java +++ b/src/main/java/com/biel/lobby/LoginListener.java @@ -1,6 +1,5 @@ package com.biel.lobby; -import com.nametagedit.plugin.NametagEdit; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -15,10 +14,12 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.event.weather.WeatherChangeEvent; import com.biel.lobby.utilities.Utils; +import com.biel.lobby.utilities.PlayerTagState; public class LoginListener implements Listener { public lobby plugin; @@ -41,6 +42,10 @@ public void onPlayerJoin(PlayerJoinEvent event) { } @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + PlayerTagState.remove(event.getPlayer()); + } + @EventHandler public void onFoodChange(FoodLevelChangeEvent e) { e.setCancelled(true); } @@ -90,10 +95,8 @@ public void onPing(ServerListPingEvent evt) { String lastMotd = Com.getRankingString(num); evt.setMotd(lastMotd); } catch (Exception e) { - - System.out.println("Error en carrgear el rànquing: " + e.toString()); + plugin.getLogger().log(java.util.logging.Level.WARNING, "Error carregant el rànquing", e); evt.setMotd(ChatColor.GREEN + "Carregant rànquing..."); - e.printStackTrace(); } } @@ -122,45 +125,46 @@ public void onPlayerChatEvent(AsyncPlayerChatEvent evt) { evt.setMessage(msg); - if( - msg.contains("inves") || - msg.contains("polla") || - msg.contains("gilip") || - msg.contains("tont") || - msg.contains("retr") || - msg.contains("retard") - ) { - - if(Com.isOnLobby(evt.getPlayer())){ - if(Utils.Possibilitat(60)) evt.setMessage("quin server més guai!!"); - if(Utils.Possibilitat(60)) evt.setMessage("com mola el server!"); - if(Utils.Possibilitat(10)) evt.setMessage("sou els millors!!"); - } else { - evt.setMessage("bona partida! ;)"); - if(Utils.Possibilitat(40)) evt.setMessage("bona partida!! :D"); - } - - if(Utils.Possibilitat(5)) evt.setMessage("ehem.. anava a dir... millor callo xD"); - if(Utils.Possibilitat(8)) evt.setMessage("ja començo a perdre els papers, no em feu gaire cas jaja"); - if(Utils.Possibilitat(3)) evt.setMessage("lluiscab we love u"); - - } + evt.setCancelled(true); + String filteredMessage = msg; + Bukkit.getScheduler().runTask(plugin, () -> broadcastChat(ply, filteredMessage)); + } - Mapa mapa = plugin.gest.getMapWherePlayerIs(evt.getPlayer()); - String zone = lobby.isOnLobby(ply) - ? ChatColor.GOLD + "[" + ChatColor.AQUA + "Lobby" + ChatColor.GOLD + "] " + ChatColor.GRAY - : mapa.getMapDisplayName() + ChatColor.RESET; + private void broadcastChat(Player player, String filteredMessage) { + if (!player.isOnline()) return; - String playerName = ( - lobby.isOnLobby(ply) - ? ChatColor.GRAY - : NametagEdit.getApi().getNametag(ply).getPrefix() - ) + ply.getDisplayName(); + boolean onLobby = lobby.isOnLobby(player); + String message = filteredMessage; + if (containsFilteredWord(message)) { + if (onLobby) { + if (Utils.Possibilitat(60)) message = "quin server més guai!!"; + if (Utils.Possibilitat(60)) message = "com mola el server!"; + if (Utils.Possibilitat(10)) message = "sou els millors!!"; + } else { + message = "bona partida! ;)"; + if (Utils.Possibilitat(40)) message = "bona partida!! :D"; + } + if (Utils.Possibilitat(5)) message = "ehem.. anava a dir... millor callo xD"; + if (Utils.Possibilitat(8)) message = "ja començo a perdre els papers, no em feu gaire cas jaja"; + if (Utils.Possibilitat(3)) message = "lluiscab we love u"; + } - Bukkit.broadcastMessage(zone + ChatColor.GRAY + playerName + ChatColor.GRAY + ": " + evt.getMessage()); - evt.setCancelled(true); + Mapa map = plugin.gest.getMapWherePlayerIs(player); + String zone = onLobby + ? ChatColor.GOLD + "[" + ChatColor.AQUA + "Lobby" + ChatColor.GOLD + "] " + ChatColor.GRAY + : map != null ? map.getMapDisplayName() + ChatColor.RESET : ChatColor.DARK_GRAY + "[Sense zona] "; + String playerName = (onLobby ? ChatColor.GRAY : PlayerTagState.getPrefix(player)) + player.getDisplayName(); + Bukkit.broadcastMessage(zone + ChatColor.GRAY + playerName + ChatColor.GRAY + ": " + message); + } + private boolean containsFilteredWord(String message) { + return message.contains("inves") + || message.contains("polla") + || message.contains("gilip") + || message.contains("tont") + || message.contains("retr") + || message.contains("retard"); } @EventHandler @@ -191,4 +195,4 @@ public void onEntityDamageEvent(EntityDamageEvent evt) { } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/lobby.java b/src/main/java/com/biel/lobby/lobby.java index 2ec0711..40f037c 100644 --- a/src/main/java/com/biel/lobby/lobby.java +++ b/src/main/java/com/biel/lobby/lobby.java @@ -17,6 +17,7 @@ import com.biel.lobby.mapes.Joc; import com.biel.lobby.mapes.MapaResetejable; import com.biel.lobby.utilities.GestorPropietats; +import com.biel.lobby.utilities.HologramFacade; import com.biel.lobby.utilities.Options; import com.biel.lobby.utilities.Utils; import com.biel.lobby.utilities.data.DataAPI; @@ -33,6 +34,7 @@ public void onEnable(){ new LoginListener(); getLobbyWorld().setAutoSave(true); + MapaResetejable.cleanupStaleRuntimeWorlds(); gest = new GestorMapes(); dataAPI = new DataAPI(); @@ -43,8 +45,91 @@ public void onDisable() { // TODO Insert logic to be performed when the plugin is disabled } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ + if(cmd.getName().equalsIgnoreCase("prova")){ + if(sender instanceof Player && !sender.isOp()){ + sender.sendMessage(ChatColor.RED + "Aquesta ordre requereix permisos d'operador."); + return true; + } + if(args.length == 1 && args[0].equalsIgnoreCase("llista")){ + if (gest.getAllGameInstances().isEmpty()) { + sender.sendMessage("No hi ha instàncies de joc actives."); + } else { + sender.sendMessage(ChatColor.GOLD + "Instàncies de joc actives:"); + for (Joc game : gest.getAllGameInstances()) { + sender.sendMessage("- " + game.getGameName() + " / " + game.getMapName() + + " (jugadors=" + game.getPlayers().size() + ", edició=" + game.getEditMode() + ")"); + } + } + return true; + } + if(args.length >= 2 && args[0].equalsIgnoreCase("elimina")){ + String worldName = String.join(" ", java.util.Arrays.copyOfRange(args, 1, args.length)); + GestorMapes.InstanceRemovalResult result = gest.removeGameInstance(worldName); + switch (result) { + case REMOVED: + sender.sendMessage(ChatColor.GREEN + "Instància descarregada; els fitxers temporals s'eliminaran en 10 segons."); + break; + case NOT_FOUND: + sender.sendMessage(ChatColor.RED + "No hi ha cap instància registrada amb aquest nom de món."); + break; + case HAS_PLAYERS: + sender.sendMessage(ChatColor.RED + "No es pot eliminar una instància amb jugadors."); + break; + case EDIT_MODE: + sender.sendMessage(ChatColor.RED + "No es pot eliminar una instància en mode d'edició."); + break; + case UNLOAD_FAILED: + sender.sendMessage(ChatColor.RED + "Paper no ha pogut descarregar el món; no s'ha eliminat la instància."); + break; + } + return true; + } + if(args.length < 1 || args.length > 2){ + sender.sendMessage("Ús: /prova [variant] | /prova llista | /prova elimina "); + return true; + } + Integer mapId = null; + if(args.length == 2){ + try { + mapId = Integer.valueOf(args[1]); + } catch (NumberFormatException exception) { + sender.sendMessage(ChatColor.RED + "La variant ha de ser un número."); + return true; + } + } + Joc createdGame = gest.createGameInstance(args[0], mapId); + if(createdGame == null){ + sender.sendMessage(ChatColor.RED + "No s'ha pogut crear el joc " + args[0] + "."); + } else { + sender.sendMessage(ChatColor.GREEN + "Instància creada: " + createdGame.getGameName() + " / " + createdGame.getMapName()); + } + return true; + } + if (!(sender instanceof Player)) { + sender.sendMessage("Aquesta ordre només es pot executar com a jugador."); + return true; + } Player ply = (Player) sender; + if(cmd.getName().equalsIgnoreCase("minicatjoin")){ + if(args.length == 0){ + ply.sendMessage(ChatColor.RED + "Falta el nom de la instància."); + return true; + } + String worldName = String.join(" ", args); + GestorMapes.InstanceJoinResult result = gest.joinGameInstance(ply, worldName); + switch (result) { + case JOINED: + break; + case NOT_FOUND: + ply.sendMessage(ChatColor.RED + "Aquesta instància ja no existeix."); + break; + case UNAVAILABLE: + ply.sendMessage(ChatColor.RED + "Aquesta instància ja no admet jugadors."); + break; + } + return true; + } if(cmd.getName().equalsIgnoreCase("m")){ gest.ObrirMenuMapes(ply); @@ -182,4 +267,4 @@ public static Boolean isOnLobby(Player ply){ public boolean isInRankedMode(){ return ranked; } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/mapes/Joc.java b/src/main/java/com/biel/lobby/mapes/Joc.java index ee0d389..ae414bd 100644 --- a/src/main/java/com/biel/lobby/mapes/Joc.java +++ b/src/main/java/com/biel/lobby/mapes/Joc.java @@ -44,6 +44,7 @@ import com.biel.lobby.Com; import com.biel.lobby.lobby; import com.biel.lobby.utilities.CBUtils; +import com.biel.lobby.utilities.PaperMessages; import com.biel.lobby.utilities.Utils; import com.biel.lobby.utilities.data.MatchData; import com.biel.lobby.utilities.data.PlayerData; @@ -53,12 +54,8 @@ import com.biel.lobby.utilities.events.statuseffects.AuraRendererStatusEffect; import com.biel.lobby.utilities.events.statuseffects.StatusEffect ; -import com.connorlinfoot.bountifulapi.BountifulAPI; - -import org.inventivetalent.menubuilder.chat.ChatListener; -import org.inventivetalent.menubuilder.chat.ChatMenuBuilder; -import org.inventivetalent.menubuilder.chat.LineBuilder; -import net.md_5.bungee.api.chat.TextComponent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; public abstract class Joc extends MapaResetejable { protected Boolean JocIniciat = false; @@ -82,21 +79,14 @@ public abstract class Joc extends MapaResetejable { private Long ultraHeartbeatCount = 0L; private int heartbeatId = -1; private Long announceCount = 0L; - private ArrayList handledBukkitSchedulerTasks = new ArrayList<>(); + private ArrayList handledBukkitSchedulerTasks = new ArrayList<>(); + private ArrayList handledLifecycleSchedulerTasks = new ArrayList<>(); public Joc() { super(); //Bukkit.broadcastMessage("Class Joc Constructor"); } @Override - protected void finalize() throws Throwable { - // TODO Auto-generated method stub - clearExternals(); - - super.finalize(); - //System.out.println("La instància de " + getGameName() + " s'ha destruït"); - } - @Override public void initialize() { super.initialize(); world.setPVP(false); @@ -108,18 +98,19 @@ public void initialize() { scheduleAnnouncer(); } public void setDefaultGameRules(){ - world.setGameRuleValue("doDaylightCycle", "false"); - world.setGameRuleValue("doFireTick", "false"); - world.setGameRuleValue("doMobSpawning", "false"); - world.setGameRuleValue("doMobLoot", "false"); + world.setGameRule(GameRules.ADVANCE_TIME, false); + world.setGameRule(GameRule.DO_FIRE_TICK, false); + world.setGameRule(GameRules.SPAWN_MOBS, false); + world.setGameRule(GameRules.MOB_DROPS, false); if (!getResetPlayerOnRespawn()){ - world.setGameRuleValue("keepInventory", "true"); + world.setGameRule(GameRules.KEEP_INVENTORY, true); } setCustomGameRules(); } protected abstract void setCustomGameRules(); public void JocIniciat(){ if (JocIniciat){Bukkit.broadcastMessage("S'ha intentat iniciar una partida que ja estava iniciada. Operació anul·lada!"); return;} + if (!canStartGame()) return; Bukkit.broadcastMessage(getGameDisplayName() + "S'ha iniciat la partida!"); JocIniciat = true; //--- @@ -138,7 +129,10 @@ public void JocIniciat(){ sendGameInfo(); //sendGlobalMessage("W:" + getWorld().getName()); - } + } + protected boolean canStartGame(){ + return true; + } public boolean JocEnMarxa(){ return JocIniciat && !JocFinalitzat; @@ -151,6 +145,10 @@ public void clearExternals(){ cancelAllTasks(); s.clear(); } + public void clearAllExternals(){ + clearExternals(); + handledLifecycleSchedulerTasks.forEach(tId -> Bukkit.getScheduler().cancelTask(tId)); + } public void clearExternals(Player p){ } @@ -160,6 +158,31 @@ private void cancelAllTasks(){ public void handleTask(int tId){ handledBukkitSchedulerTasks.add(tId); } + public void handleLifecycleTask(int taskId){ + handledLifecycleSchedulerTasks.add(taskId); + } + public int scheduleGameplayTask(Runnable task, long delayTicks){ + int taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), task, delayTicks); + handleTask(taskId); + return taskId; + } + public int scheduleGameplayRepeatingTask(Runnable task, long delayTicks, long periodTicks){ + int taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(Com.getPlugin(), task, delayTicks, periodTicks); + handleTask(taskId); + return taskId; + } + public int scheduleTrackedBlockRemoval(Block block, long delayTicks, boolean dropItems){ + if (world == null || block.getWorld() != world) return -1; + Material expectedMaterial = block.getType(); + return scheduleGameplayTask(() -> { + if (world == null || block.getWorld() != world || block.getType() != expectedMaterial) return; + if (dropItems) { + block.breakNaturally(); + } else { + block.setType(Material.AIR); + } + }, delayTicks); + } private Long establirTempsInicial() { return startTimeMillis = System.currentTimeMillis(); } @@ -214,13 +237,21 @@ public void winGame(ArrayList wList){ //TODO updateEloOrdered(wList); } protected boolean onlyPlayersFromSameIP(){ - String n = null; + String firstAddress = null; for(Player p : getPlayers()){ - String hostName = p.getAddress().getHostName(); - if(n == null) n = hostName; - if(n.equals(hostName))return false; + java.net.InetSocketAddress socketAddress = p.getAddress(); + if (socketAddress == null) return false; + java.net.InetAddress resolvedAddress = socketAddress.getAddress(); + String numericAddress = resolvedAddress != null + ? resolvedAddress.getHostAddress() + : socketAddress.getHostString(); + if(firstAddress == null) { + firstAddress = numericAddress; + } else if(!firstAddress.equals(numericAddress)) { + return false; + } } - return true; + return firstAddress != null; } protected boolean canBeRanked(){ return(segonsTranscorreguts() > (onlyPlayersFromSameIP() ? 60 * 15 : 20) && getEloK() != 0 && Com.getPlugin().isInRankedMode() && !unfairFlag); @@ -335,10 +366,11 @@ public boolean hasHostPrivilleges(Player p){ } @Override public void Join(Player ply) { - // TODO Auto-generated method stub - if(canJoin(ply)){ - if(getPlayers().size() == 0)setHost(ply); + if (!canJoin(ply)) { + ply.sendMessage(ChatColor.RED + "No et pots unir a aquesta instància en el seu estat actual."); + return; } + if(getPlayers().size() == 0)setHost(ply); super.Join(ply); } @@ -371,8 +403,9 @@ protected void donarItemsInicials(Player ply) { giveFixedPlaceItems(ply); giveRemainingUnlockers(ply); donarEfectesInicials(ply); - if (getStartingItems(ply) != null){ - Utils.donarItemsPlayer(ply, getStartingItems(ply)); + ArrayList startingItems = getStartingItems(ply); + if (startingItems != null){ + Utils.donarItemsPlayer(ply, startingItems); } } public void giveRemainingUnlockers(Player ply) { @@ -569,11 +602,11 @@ protected void onPlayerDamageByPlayer(EntityDamageByEntityEvent evt, if (isSnowLauncherEnabled) { //TODO decide based on flag evt.setCancelled(true); damaged.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 1, 0)); - damaged.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 1, 0)); + damaged.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 1, 0)); //damaged.setVelocity(new Vector(0, 0.1, 0)); damager.teleport(damaged.getEyeLocation().add(0, 0.5, 0), TeleportCause.PLUGIN); GUtils.healDamageable(damager, 0.4D); - damager.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 2, 1)); + damager.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 20 * 2, 1)); } } } @@ -585,7 +618,7 @@ protected void onPlayerDamageByPlayer(EntityDamageByEntityEvent evt, evt.setCancelled(true); - BountifulAPI.sendActionBar(damager, ChatColor.GRAY + "El jugador " + damaged.getName() + " és invulnerable.", 150); + PaperMessages.sendActionBar(damager, ChatColor.GRAY + "El jugador " + damaged.getName() + " és invulnerable.", 150); getWorld().playSound(damager.getLocation(), Sound.ENCHANT_THORNS_HIT, 1.2F, 0.88F); getWorld().playEffect(damaged.getEyeLocation(), Effect.FIREWORK_SHOOT, DyeColor.BLUE.getDyeData()); @@ -641,7 +674,10 @@ void establirSpawnPrincipal(){ } public void planificarReseteig(int delay){ sendGlobalMessage(ChatColor.BLUE + "Esborrant el mapa en " + Double.toString(delay/20) + "s"); - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(lobby.getPlugin(), () -> allOnTheLobby(), delay); + int resetTaskId = Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(lobby.getPlugin(), () -> { + if (world != null) allOnTheLobby(); + }, delay); + handleLifecycleTask(resetTaskId); } @Override @@ -905,23 +941,13 @@ public void inviteToGame(Player player){ // String join = "\n\n " + ChatColor.GREEN + ChatColor.UNDERLINE + host + ChatColor.RESET + ChatColor.GREEN + " t'ha convidat a " + getGameName(); // String join2 = "\n " + ChatColor.GOLD + ChatColor.UNDERLINE + "Clica aquí per entrar al joc\n\n"; - TextComponent clickToJoinMsg = new TextComponent(" Fes clic aquí per a entrar a la partida"); - - player.sendMessage(ChatColor.GREEN + "\n\n " + ChatColor.ITALIC + host + ChatColor.RESET + "" + ChatColor.GREEN + " t'ha convidat a " + getGameName() + ""); - new ChatMenuBuilder().withLine( - new LineBuilder().append( - new ChatListener() { - public void onClick(Player player) { - // player.sendMessage("You clicked me!"); - Join(player); - } - - }, - clickToJoinMsg - - ) - ).show(player); + Component clickToJoinMsg = PaperMessages.legacy(ChatColor.GOLD + " Fes clic aquí per a entrar a la partida") + // RUN_COMMAND is handled by both vanilla clients and protocol bots. Paper's + // server-side callback click action can be acknowledged by a non-vanilla + // client without ever invoking the callback. + .clickEvent(ClickEvent.runCommand("/minicatjoin " + getMapName())); + player.sendMessage(clickToJoinMsg); player.sendMessage("\n"); player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 100, 0); @@ -1120,6 +1146,10 @@ protected Player getPlayer() { if(name == null)return null; return Bukkit.getPlayer(name); } + private boolean hasActivePlayer() { + Player player = getPlayer(); + return player != null && player.isOnline() && world != null && player.getWorld() == world; + } public int getValue() { return value; } @@ -1260,9 +1290,9 @@ public void updateSpeedSlowPotionEffects(){ getPlayer().removePotionEffect(PotionEffectType.SPEED); } if (SL > 0) { - getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 1, SL - 1, true, true)); + getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 1, SL - 1, true, true)); }else{ - getPlayer().removePotionEffect(PotionEffectType.SLOW); + getPlayer().removePotionEffect(PotionEffectType.SLOWNESS); } } public ArrayList getStatusEffects() { @@ -1336,7 +1366,6 @@ public T getStatusEffect(String name){ } public void updatePlayerActionBar(){ if (getPlayer() == null)return; - // ActionBarAPI.sendActionBar(getPlayer(), getStatusEffectsText()); } public int getAdditionalSkills() { return additionalSkills; @@ -1360,7 +1389,9 @@ public int getUnselectedSkillAmount(){ return (r < 0 ? 0 : r); } public Block getBlockWherePlayerStands(){ - BlockIterator i = new BlockIterator(getWorld(), getPlayer().getLocation().toVector(), new Vector(0, -1, 0), 1D, 30); + Player player = getPlayer(); + if (player == null || !player.isOnline() || world == null || player.getWorld() != world) return null; + BlockIterator i = new BlockIterator(getWorld(), player.getLocation().toVector(), new Vector(0, -1, 0), 1D, 30); for (;i.hasNext();) { Block b = i.next(); if(!b.isEmpty())return b; @@ -1389,7 +1420,7 @@ private void scheduleHeartbeat(){ public void ultraHeartbeat(){ ultraHeartbeatCount++; for(PlayerInfo i : InfoStorage){ - i.ultraTick(); + if (i.hasActivePlayer()) i.ultraTick(); } s.tickPool(); } @@ -1400,7 +1431,7 @@ public void heartbeat(){ heartbeatCount++; //if (!JocIniciat){startSystemTick();} for(PlayerInfo i : InfoStorage){ - i.tick(); + if (i.hasActivePlayer()) i.tick(); } lobbyProgressAnoouncerTick(); registerTimestamps(false); @@ -1452,4 +1483,4 @@ protected Color getDeterministicColorForPlayer(Player p, boolean alternate){ Color color2 = GUtils.getContrastColor(color1); return alternate ? color2 : color1; } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/mapes/JocEquips.java b/src/main/java/com/biel/lobby/mapes/JocEquips.java index fc7a796..b42c5ec 100644 --- a/src/main/java/com/biel/lobby/mapes/JocEquips.java +++ b/src/main/java/com/biel/lobby/mapes/JocEquips.java @@ -28,7 +28,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; -import org.bukkit.material.Wool; import org.bukkit.util.Vector; import com.biel.BielAPI.Utils.IconMenu; @@ -66,11 +65,6 @@ protected void customJocFinalitzat() { } @Override protected void customJocIniciat() { - if(generationMode == TeamGenerationMode.DEFAULT)ferEquipsEquilibrats(); - if(generationMode == TeamGenerationMode.CUSTOM && getPlayersOutOfTeam().size() != 0){ - sendGlobalMessage("Mode selecció d'equips personalitzats, siusplau, seleccioneu els vostres equips abans de començar la partida."); - anunciarEquips(null); - } anunciarEquips(null); fixarSpawns(); //establirColorsNoms(); @@ -78,6 +72,20 @@ protected void customJocIniciat() { updateScoreBoards(); } + @Override + protected boolean canStartGame() { + if (generationMode == TeamGenerationMode.DEFAULT) { + ferEquipsEquilibrats(); + } + if (!getPlayersOutOfTeam().isEmpty()) { + String unassignedPlayers = getPlayersOutOfTeam().stream() + .map(Player::getName) + .collect(Collectors.joining(", ")); + sendGlobalMessage(ChatColor.RED + "No es pot iniciar: selecciona un equip per a " + unassignedPlayers + "."); + return false; + } + return super.canStartGame(); + } public void winGame(Equip e){ //TODO if(won)return; if(e == null){ @@ -111,7 +119,8 @@ protected void raisePlayersToSpectatorZone(){ } } private void delayedUpdateHeadColors() { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), () -> updateHeadColors(), 20); + int taskId = Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), () -> updateHeadColors(), 20); + handleTask(taskId); } protected void establirColorsNoms(){ for (Equip e : Equips){ @@ -229,7 +238,7 @@ public void establirEquipJugador(Player ply, Equip eq){ } @SuppressWarnings("unchecked") public T obtenirEquip(Player ply, Class type){ - if (ply == null){System.out.println("Null player");return null;} + if (ply == null){Com.getPlugin().getLogger().warning("No es pot obtenir l'equip d'un jugador nul");return null;} String name = ply.getName(); for (Equip e : Equips){ @@ -257,6 +266,7 @@ public T obtenirEquipEnemic(Player ply, Class type){ } @SuppressWarnings("unchecked") public T obtenirEquipEnemic(T e){ + if (e == null) return null; if (Equips.size() == 2){ for (Equip eq : Equips){ if (!eq.equals(e)){ @@ -270,16 +280,21 @@ public T obtenirEquipEnemic(T e){ } @Override public Boolean areAllies(Player ply, Player ply2){ - return obtenirEquip(ply).getPlayers().contains(ply2); + Equip team = obtenirEquip(ply); + return team != null && obtenirEquip(ply2) == team; } @Override public Boolean areEnemies(Player ply, Player ply2){ - return !areAllies(ply, ply2); + Equip firstTeam = obtenirEquip(ply); + Equip secondTeam = obtenirEquip(ply2); + return firstTeam != null && secondTeam != null && firstTeam != secondTeam; } @Override public ArrayList getEnemies(Player p) { + Equip team = obtenirEquip(p); + if (team == null) return new ArrayList<>(); ArrayList enemies = getViewers(); - enemies.removeAll(obtenirEquip(p).getPlayers()); + enemies.removeAll(team.getPlayers()); return enemies; //Futurs espectadors } public void fixarSpawn(Player ply){ @@ -365,24 +380,18 @@ public Double getTeamSize(){ return (getPlayers().size() / (double) Equips.size()); } public void ferEquipsAleatoris(boolean reassignar){ - if(Equips.size() == 0)return; - //if(reassignar){resetTeams();} + if(Equips.isEmpty())return; + if (reassignar) { + initTeams(); + } ArrayList players = new ArrayList<>(getPlayers()); Collections.shuffle(players); - int next_team = 0; - int cycles = 0; - int max_cycles = Equips.size() * 4; for (Player p : players) { - if(cycles > max_cycles){return;} - cycles++; if(!reassignar && obtenirEquip(p) != null)continue; - if (next_team > Equips.size() - 1) { - next_team = 0; - } - Equip eq = Equips.get(next_team); - if(eq.getPlayers().size() >= Math.ceil(getTeamSize()))continue; - establirEquipJugador(p, eq); - next_team++; + Equip smallestTeam = Equips.stream() + .min((left, right) -> Integer.compare(left.getPlayers().size(), right.getPlayers().size())) + .orElseThrow(); + establirEquipJugador(p, smallestTeam); } generationMode = TeamGenerationMode.RANDOM; } @@ -467,8 +476,7 @@ void openTemSelectionMenu(final Player ply, final Player objPly, String title){ }); for(Equip eq : Equips){ - Wool wool = new Wool(eq.getColor()); - ItemStack stack = wool.toItemStack(); + ItemStack stack = new ItemStack(Material.valueOf(eq.getColor().name() + "_WOOL")); //stack.setAmount(eq.getPlayers().size()); menu.setOption(Equips.indexOf(eq), stack, eq.getChatColor() + "Equip " + eq.getAdjectiu()); } @@ -558,18 +566,20 @@ protected ArrayList getStartingItems(Player ply) { items.add(Utils.createColoredTeamArmor(Material.LEATHER_BOOTS, e)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); items.add(arc); items.add(new ItemStack(Material.ARROW, 64)); items.add(new ItemStack(Material.OAK_LOG, 64)); - items.add(new ItemStack(Material.LEGACY_GRILLED_PORK, 32)); + items.add(new ItemStack(Material.COOKED_PORKCHOP, 32)); return items; } @Override public void giveFixedPlaceItems(Player ply) { - // TODO Auto-generated method stub super.giveFixedPlaceItems(ply); - if(isRecallEnabled() && getPlayerInfo(ply).getUnselectedSkillAmount() == 0)obtenirEquip(ply).giveRecallButton(ply); + Equip team = obtenirEquip(ply); + if (isRecallEnabled() && team != null && getPlayerInfo(ply).getUnselectedSkillAmount() == 0) { + team.giveRecallButton(ply); + } } protected boolean isRecallEnabled(){ return false; @@ -659,12 +669,7 @@ void addPlayer(Player ply){ Players.add(ply.getName()); } void removePlayer(Player ply){ - for (String str : Players){ - String plystr = ply.getName(); - if(str.equals(plystr)){ - Players.remove(str); - } - } + Players.removeIf(playerName -> playerName.equals(ply.getName())); } //------- public Location getTeamSpawnLocation(){ @@ -680,7 +685,7 @@ public void teleportToTeamSpawn(Player ply){ } public void giveRecallButton(Player ply){ ItemStack dBlk = new ItemStack(Material.DIAMOND_BLOCK); - dBlk.addUnsafeEnchantment(Enchantment.LOOT_BONUS_BLOCKS, 10); + dBlk.addUnsafeEnchantment(Enchantment.FORTUNE, 10); ItemButton button = new ItemButton(Utils.setItemNameAndLore(dBlk, ChatColor.GREEN + "Recall", ChatColor.WHITE + "Torna el jugador a la base."), ply, event -> RecallUtils.startRecallTeleport(event.getPlayer(), getTeamSpawnLocation())); PlayerInventory inventory = ply.getInventory(); inventory.setItem(8, button.getItemStack()); @@ -807,4 +812,4 @@ protected void onPlayerDeathByPlayer(org.bukkit.event.entity.PlayerDeathEvent ev //TODO add random death causes } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/mapes/JocObjectius.java b/src/main/java/com/biel/lobby/mapes/JocObjectius.java index b81c17b..645193a 100644 --- a/src/main/java/com/biel/lobby/mapes/JocObjectius.java +++ b/src/main/java/com/biel/lobby/mapes/JocObjectius.java @@ -311,11 +311,9 @@ protected void onBlockPlace(BlockPlaceEvent evt, Block blk) { } public class ObjectiuBlockChange extends Objectiu{ Material m; - byte data; - public ObjectiuBlockChange(String nom, Location l, Material m, byte data) { - super(nom, l, data); + public ObjectiuBlockChange(String nom, Location l, Material m) { + super(nom, l, m); this.m = m; - this.data = data; } public boolean isInsideProtectionRadius(Location l){ double dist = l.distance(location); @@ -342,13 +340,11 @@ protected void onBlockPlace(BlockPlaceEvent evt, Block blk) { } } - @SuppressWarnings("deprecation") public Boolean onChange(BlockPlaceEvent evt, Player p, Block blk){ if(canBeCompleted(p)){ boolean sameType = m == blk.getType(); - boolean sameData = data == blk.getData(); boolean sameLocation = blk.getLocation().equals(location); - if(sameType && sameData && sameLocation){ + if(sameType && sameLocation){ complete(p); //location.getBlock().setType(Material.GLASS); return true; @@ -365,10 +361,9 @@ public Boolean onChange(BlockPlaceEvent evt, Player p, Block blk){ } } public class ObjectiuWoolPlace extends ObjectiuBlockChange{ - @SuppressWarnings("deprecation") DyeColor color; public ObjectiuWoolPlace(String nom, Location l, DyeColor color) { - super(nom, l, Material.WHITE_WOOL, color.getWoolData()); + super(nom, l, Material.valueOf(color.name() + "_WOOL")); this.color = color; } @Override diff --git a/src/main/java/com/biel/lobby/mapes/JocTeamDominion.java b/src/main/java/com/biel/lobby/mapes/JocTeamDominion.java index f0b408e..57babed 100644 --- a/src/main/java/com/biel/lobby/mapes/JocTeamDominion.java +++ b/src/main/java/com/biel/lobby/mapes/JocTeamDominion.java @@ -17,8 +17,7 @@ import com.biel.lobby.Com; import com.biel.lobby.utilities.ScoreBoardUpdater; import com.biel.lobby.utilities.Utils; -import com.gmail.filoghost.holographicdisplays.api.Hologram; -import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.biel.lobby.utilities.HologramFacade; public abstract class JocTeamDominion extends JocEquips { public ArrayList ControlPoints = new ArrayList<>(); @@ -188,7 +187,7 @@ protected abstract class ControlPoint{ int ownerTeam = -1; int dominatingTeamID = -1; int dominationPower = 0; - Hologram h; + HologramFacade.Handle h; boolean captured = false; int tendency = 0; float basePointReward = 3F; @@ -228,7 +227,7 @@ public void init(){ } public void createHolgram(){ if (h != null){return;} - h = HologramsAPI.createHologram(Com.getPlugin(), getHologramLocation()); + h = HologramFacade.create(getHologramLocation()); } public void updateHologram(){ if (h == null){return;} @@ -498,37 +497,39 @@ public abstract class ControlPointRenderer{ } public abstract class DyeColorControlPointRenderer extends ControlPointRenderer{ - @SuppressWarnings("deprecation") @Override public void renderEnvironment(PhysicalControlPoint p) { - // TODO Auto-generated method stub for (Block b : p.getEnvironmentBlocks()){ - if(b.getType() == Material.WHITE_WOOL || b.getType() == Material.LEGACY_STAINED_CLAY || b.getType() == Material.LEGACY_STAINED_GLASS || b.getType() == Material.LEGACY_STAINED_GLASS_PANE){ -// b.setData(getDyeColorForBlock(p, b)); -// TODO Update to data - } + Material coloredMaterial = getColoredMaterial(b.getType(), getDyeColorForBlock(p, b)); + if (coloredMaterial != null) b.setType(coloredMaterial, false); } } - public abstract byte getDyeColorForBlock(PhysicalControlPoint p, Block b); + private Material getColoredMaterial(Material currentMaterial, DyeColor color) { + String materialName = currentMaterial.name(); + for (String suffix : new String[]{"_WOOL", "_TERRACOTTA", "_STAINED_GLASS", "_STAINED_GLASS_PANE"}) { + if (materialName.endsWith(suffix)) return Material.valueOf(color.name() + suffix); + } + return null; + } + public abstract DyeColor getDyeColorForBlock(PhysicalControlPoint p, Block b); } public class PieControlPointRenderer extends DyeColorControlPointRenderer{ @Override - public byte getDyeColorForBlock(PhysicalControlPoint p, Block b) { + public DyeColor getDyeColorForBlock(PhysicalControlPoint p, Block b) { // TODO Auto-generated method stub Slice sliceForBlock = getSliceForBlock(p, b); if (sliceForBlock != null) { return sliceForBlock.color; } - return 0; + return DyeColor.WHITE; } - @SuppressWarnings("deprecation") public ArrayList getSlices(PhysicalControlPoint p){ ArrayList slices = new ArrayList<>(); Equip ownerTeam = p.getOwnerTeam(); DyeColor color = DyeColor.WHITE; if (ownerTeam != null) {color = ownerTeam.getColor();} - slices.add(new Slice(p.getPercent(), color.getWoolData())); - slices.add(new Slice(100 - p.getPercent(), DyeColor.WHITE.getWoolData())); + slices.add(new Slice(p.getPercent(), color)); + slices.add(new Slice(100 - p.getPercent(), DyeColor.WHITE)); return slices; } public Slice getSliceForBlock(PhysicalControlPoint p, Block b){ @@ -556,9 +557,9 @@ public Slice getSliceForBlock(PhysicalControlPoint p, Block b){ } class Slice { double value; - byte color; + DyeColor color; - public Slice(double value, byte color) { + public Slice(double value, DyeColor color) { this.value = value; this.color = color; } @@ -566,9 +567,8 @@ public Slice(double value, byte color) { } public class BubbleControlPointRenderer extends DyeColorControlPointRenderer{ - byte neutralColor = 0; @Override - public byte getDyeColorForBlock(PhysicalControlPoint p, Block b) { + public DyeColor getDyeColorForBlock(PhysicalControlPoint p, Block b) { float multiplier = p.getPercent() / 100.0F; DyeColor color = DyeColor.CYAN; double intRadius = p.getEquivalentRadius() * Math.sqrt(multiplier); @@ -579,7 +579,7 @@ public byte getDyeColorForBlock(PhysicalControlPoint p, Block b) { Equip ownerTeam = p.getOwnerTeam(); if (ownerTeam != null) {color = ownerTeam.getColor();} } - return color.getWoolData(); + return color; } } diff --git a/src/main/java/com/biel/lobby/mapes/MapaResetejable.java b/src/main/java/com/biel/lobby/mapes/MapaResetejable.java index b8bc3e5..a6f134b 100644 --- a/src/main/java/com/biel/lobby/mapes/MapaResetejable.java +++ b/src/main/java/com/biel/lobby/mapes/MapaResetejable.java @@ -4,6 +4,7 @@ import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; +import java.util.Locale; import org.apache.commons.io.FileUtils; import org.bukkit.Bukkit; @@ -19,6 +20,7 @@ public abstract class MapaResetejable extends Mapa { static String FolderLiveWorlds = "LiveWorlds"; + static String FolderLiveMetadata = "LiveMetadata"; static String FolderMaps = "mapes"; static String FolderCopies = "copies"; private int multiMapId; @@ -31,6 +33,37 @@ public MapaResetejable() { public void initialize() { createVirtualWorld(); } + public static void cleanupStaleRuntimeWorlds() { + File metadataRoot = new File(FolderLiveMetadata); + File[] metadataDirectories = metadataRoot.listFiles(File::isDirectory); + if (metadataDirectories == null) return; + + File worldContainer = Bukkit.getWorldContainer(); + File dimensionsRoot = new File(new File(new File(worldContainer, "world"), "dimensions"), "minecraft"); + for (File metadataDirectory : metadataDirectories) { + String worldName = metadataDirectory.getName(); + if (!worldName.matches("[A-Za-z][A-Za-z0-9_-]*\\d+")) { + Com.getPlugin().getLogger().warning("Skipping unexpected live metadata directory: " + worldName); + continue; + } + if (Bukkit.getWorld(worldName) != null) { + Com.getPlugin().getLogger().warning("Skipping loaded runtime world during startup cleanup: " + worldName); + continue; + } + + File legacyWorldDirectory = new File(worldContainer, worldName); + File paperWorldDirectory = new File(dimensionsRoot, worldName.toLowerCase(Locale.ROOT)); + try { + FileUtils.deleteDirectory(legacyWorldDirectory); + FileUtils.deleteDirectory(paperWorldDirectory); + FileUtils.deleteDirectory(metadataDirectory); + Com.getPlugin().getLogger().info("Removed stale runtime world: " + worldName); + } catch (IOException exception) { + Com.getPlugin().getLogger().log(java.util.logging.Level.SEVERE, + "Could not remove stale runtime world " + worldName, exception); + } + } + } String getLiveWorldAvaliableName(String where){ String nouNom = ""; int LastNum = 1; @@ -65,21 +98,30 @@ String getLiveWorldAvaliableName(String where){ void createVirtualWorld(){ if (getGameName().equals("")){return;} if (isWorldLoaded() == true){return;} - NomWorld = getLiveWorldAvaliableName(FolderLiveWorlds); + NomWorld = getLiveWorldAvaliableName(FolderLiveMetadata); //Copy world File worldOrigin = getWorldOriginMappedFile(); File worldLive = getLiveWorldFile(); + File metadataDirectory = getLiveMetadataFile(); try { copyDirectory(worldOrigin, worldLive); + if (!metadataDirectory.exists() && !metadataDirectory.mkdirs()) { + throw new IOException("Could not create live metadata directory " + metadataDirectory); + } + File sourceProperties = new File(worldOrigin, "pMapaActual.txt"); + if (sourceProperties.isFile()) { + FileUtils.copyFile(sourceProperties, new File(metadataDirectory, "pMapaActual.txt")); + } File uid = new File(worldLive.getPath() + "/" + "uid.dat"); uid.delete(); } catch (IOException e) { - // TODO Auto-generated catch block - Bukkit.broadcastMessage("El mon no s'ha pogut copiar"); - e.printStackTrace(); + throw new IllegalStateException("El mon no s'ha pogut copiar: " + getGameName(), e); } //----- world = Bukkit.createWorld(new WorldCreator(getLiveWorldFolder())); + if (world == null) { + throw new IllegalStateException("Paper no ha pogut carregar el mon " + getLiveWorldFolder()); + } updateWorldToRegisteredHandler(); } private void updateWorldToRegisteredHandler() { @@ -143,30 +185,34 @@ public static ArrayList getAllMapNames(){ return result; } private String getLiveWorldFolder() { - return FolderLiveWorlds + "/" + NomWorld; + return NomWorld; } public static void deleteLiveWorldsFolder(){ try { FileUtils.deleteDirectory(new File(FolderLiveWorlds)); } catch (IOException e) { - System.out.println("Error borrando los liveworlds"); + Com.getPlugin().getLogger().log(java.util.logging.Level.WARNING, "Error esborrant els mons temporals", e); } } - public void deleteVirtualWorld(){ - Bukkit.unloadWorld(world, false); + public boolean deleteVirtualWorld(){ + if (world == null) return false; + File worldLive = world.getWorldFolder(); + File metadataDirectory = getLiveMetadataFile(); + if (!Bukkit.unloadWorld(world, false)) return false; + world = null; Com.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), () -> { - File worldLive = getLiveWorldFile(); deleteFolder(worldLive); + deleteFolder(metadataDirectory); Bukkit.broadcastMessage("Mapa esborrat! - " + NomWorld); }, 200L); - + return true; } public void save(){ if (EditMode){ world.save(); //Copy world File worldOrigin = getWorldOriginMappedFile(); - File worldLive = getLiveWorldFile(); + File worldLive = world.getWorldFolder(); String copyName = getLiveWorldAvaliableName(FolderCopies); File worldCopy = new File(FolderCopies + "/" + copyName); try { @@ -174,6 +220,10 @@ public void save(){ copyDirectory(worldOrigin, worldCopy); //Save copyDirectory(worldLive, worldOrigin); + File liveProperties = new File(getLiveMetadataFile(), "pMapaActual.txt"); + if (liveProperties.isFile()) { + FileUtils.copyFile(liveProperties, new File(worldOrigin, "pMapaActual.txt")); + } Bukkit.broadcastMessage(ChatColor.GOLD + "Mapa guardat (" + NomWorld + "), copia de seguretat (" + copyName + ")"); } catch (IOException e) { // TODO Auto-generated catch block @@ -187,6 +237,9 @@ public void save(){ private File getLiveWorldFile() { return new File(getLiveWorldFolder()); } + private File getLiveMetadataFile() { + return new File(FolderLiveMetadata, NomWorld); + } private File getMapOriginFile() { return new File(FolderMaps + "/" + getGameName()); } @@ -212,17 +265,17 @@ public void setEditMode(Boolean editMode) { sendGlobalMessage("Mode edició = " + Boolean.toString(editMode)); } public GestorPropietats pMapaActual(){ - return new GestorPropietats(getLiveWorldFolder() + "/" + "pMapaActual.txt"); + return new GestorPropietats(new File(getLiveMetadataFile(), "pMapaActual.txt").getPath()); } public GestorPropietats pTemp(){ - return new GestorPropietats(getLiveWorldFolder() + "/" + "pTemp.txt"); + return new GestorPropietats(new File(getLiveMetadataFile(), "pTemp.txt").getPath()); } public GestorPropietats pPlayer(Player ply){ - File playersFolder = new File(getLiveWorldFolder() + "/" + "pPlayers"); + File playersFolder = new File(getLiveMetadataFile(), "pPlayers"); if (!playersFolder.exists()) { playersFolder.mkdir(); } - return new GestorPropietats(getLiveWorldFolder() + "/" + "pPlayers" + "/" + ply.getName() + ".txt"); + return new GestorPropietats(new File(playersFolder, ply.getName() + ".txt").getPath()); } @Override protected synchronized void gameEvent(Event event) { diff --git a/src/main/java/com/biel/lobby/mapes/jocs/ArenaAllvAll.java b/src/main/java/com/biel/lobby/mapes/jocs/ArenaAllvAll.java index 52156d3..d1bd38f 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/ArenaAllvAll.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/ArenaAllvAll.java @@ -9,7 +9,6 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.Potion; import org.bukkit.potion.PotionType; import com.biel.lobby.mapes.JocScoreRace; @@ -33,12 +32,8 @@ protected ArrayList getStartingItems(Player ply) { ArrayList items = new ArrayList<>(); items.add(new ItemStack(Material.WOODEN_SWORD, 1)); items.add(new ItemStack(Material.BOW, 1)); - Potion p1 = new Potion(PotionType.INSTANT_DAMAGE); - p1.setSplash(true); - items.add(p1.toItemStack(1)); - Potion p2 = new Potion(PotionType.SLOWNESS); - p2.setSplash(true); - items.add(p2.toItemStack(2)); + items.add(Utils.createPotion(PotionType.HARMING, 1, true)); + items.add(Utils.createPotion(PotionType.SLOWNESS, 2, true)); items.add(new ItemStack(Material.ARROW, 5)); items.add(new ItemStack(Material.CHAINMAIL_HELMET, 1)); items.add(new ItemStack(Material.CHAINMAIL_CHESTPLATE, 1)); @@ -77,25 +72,17 @@ protected void onPlayerDeathByPlayer(PlayerDeathEvent evt, Player killed, super.onPlayerDeathByPlayer(evt, killed, killer); incrementScore(killer); if (getSpree(killer) == 1){ - Potion p1 = new Potion(PotionType.SPEED); - p1.setSplash(true); - killer.getInventory().addItem(p1.toItemStack(1)); + killer.getInventory().addItem(Utils.createPotion(PotionType.SWIFTNESS, 1, true)); } if (getSpree(killer) == 2){ - Potion p1 = new Potion(PotionType.POISON); - p1.setSplash(true); - killer.getInventory().addItem(p1.toItemStack(1)); + killer.getInventory().addItem(Utils.createPotion(PotionType.POISON, 1, true)); getPlayerInfo(killer).addAdditionalSkill(); } if (getSpree(killer) == 3){ - Potion p1 = new Potion(PotionType.REGEN); - p1.setSplash(true); - killer.getInventory().addItem(p1.toItemStack(1)); + killer.getInventory().addItem(Utils.createPotion(PotionType.REGENERATION, 1, true)); } if (getSpree(killer) >= 4){ - Potion p1 = new Potion(Utils.getRandomPotionType()); - p1.setSplash(true); - killer.getInventory().addItem(p1.toItemStack(1)); + killer.getInventory().addItem(Utils.createPotion(Utils.getRandomPotionType(), 1, true)); } evt.getDrops().clear(); evt.setDeathMessage(killer.getName() + " ha matat a " + killed.getName() + " [+1]"); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/BaseLunar.java b/src/main/java/com/biel/lobby/mapes/jocs/BaseLunar.java index bca5976..fa9462f 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/BaseLunar.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/BaseLunar.java @@ -17,7 +17,6 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.Potion; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; @@ -37,17 +36,13 @@ protected int getFinishScore() { protected ArrayList getStartingItems(Player ply) { ArrayList items = new ArrayList<>(); ItemStack esp = new ItemStack(Material.WOODEN_SWORD, 1); // A stack of diamonds - esp.addUnsafeEnchantment(Enchantment.DURABILITY, 10); + esp.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); esp.addUnsafeEnchantment(Enchantment.KNOCKBACK, 1); items.add(esp); items.add(new ItemStack(Material.WOODEN_SWORD, 1)); items.add(new ItemStack(Material.BOW, 1)); - Potion p1 = new Potion(PotionType.INSTANT_DAMAGE); - p1.setSplash(true); - items.add(p1.toItemStack(1)); - Potion p2 = new Potion(PotionType.INSTANT_HEAL); - p2.setSplash(true); - items.add(p2.toItemStack(1)); + items.add(Utils.createPotion(PotionType.HARMING, 1, true)); + items.add(Utils.createPotion(PotionType.HEALING, 1, true)); items.add(new ItemStack(Material.ARROW, 50)); items.add(getSnowLauncher(10)); //Glass @@ -73,7 +68,7 @@ protected void donarEfectesInicials(Player ply) { // TODO Auto-generated method stub super.donarEfectesInicials(ply); ply.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 3, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 3, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, Integer.MAX_VALUE, 3, true), true); } @Override diff --git a/src/main/java/com/biel/lobby/mapes/jocs/BoletumDTC.java b/src/main/java/com/biel/lobby/mapes/jocs/BoletumDTC.java index 8b42341..029c606 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/BoletumDTC.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/BoletumDTC.java @@ -61,8 +61,8 @@ protected ArrayList getStartingItems(Player ply) { Equip e = obtenirEquip(ply); items.add(new ItemStack(Material.STONE_SWORD, 1)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); - arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); + arc.addUnsafeEnchantment(Enchantment.INFINITY, 1); items.add(arc); items.add(new ItemStack(Material.DIAMOND_PICKAXE, 1)); items.add(new ItemStack(Material.IRON_AXE)); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/Dominion.java b/src/main/java/com/biel/lobby/mapes/jocs/Dominion.java index 7e0a82d..a6f1758 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/Dominion.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/Dominion.java @@ -43,7 +43,7 @@ protected ArrayList getDesiredControlPoints() { try { name = pointNames[i]; } catch (Exception e) { - System.out.print("Falta especificar un nom de punt de control"); + com.biel.lobby.Com.getPlugin().getLogger().warning("Falta especificar un nom de punt de control"); name = "No_definit"; } double radius; @@ -90,8 +90,8 @@ protected ArrayList getStartingItems(Player ply) { Equip e = obtenirEquip(ply); items.add(new ItemStack(Material.STONE_SWORD, 1)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); - arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); + arc.addUnsafeEnchantment(Enchantment.INFINITY, 1); items.add(arc); items.add(new ItemStack(Material.CHAINMAIL_HELMET, 1)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_HELMET, e)); @@ -106,9 +106,9 @@ protected void donarEfectesInicials(Player ply) { // TODO Auto-generated method stub super.donarEfectesInicials(ply); ply.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, 20 * 10, 4, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 3, 1, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20 * 5, 0, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 19, 1, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 3, 1, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 20 * 5, 0, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 20 * 19, 1, true), true); } @Override public String getGameName() { diff --git a/src/main/java/com/biel/lobby/mapes/jocs/InkWars.java b/src/main/java/com/biel/lobby/mapes/jocs/InkWars.java index a00414e..52d0d21 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/InkWars.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/InkWars.java @@ -278,11 +278,11 @@ protected void processHighInkBlocks(){ entry.getValue().setSecond(entry.getValue().getSecond() - (1.0/20.0)); //Every 20s -1 if(entry.getValue().getSecond() <= 0){ //Finally decay - iter.remove(); + iter.remove(); Block b = entry.getKey(); - if (getTeamOwningBlock(b) != null) { -// b.setData(getTeamOwningBlock(b).getColor().getWoolData()); - // TODO UPDATE + EquipInkWars owner = getTeamOwningBlock(b); + if (owner != null) { + b.setType(getPaintMaterial(b.getType(), owner.getColor()), false); } }else{ //Expansion physics @@ -313,9 +313,10 @@ protected void processHighInkBlocks(){ public EquipInkWars getTeamOwningBlock(Block b){ if(b == null)return null; if(!isPaintable(b))return null; + DyeColor blockColor = getPaintColor(b.getType()); for(Equip e : Equips){ EquipInkWars eq = (EquipInkWars) e; - if(eq.getColor().getWoolData() == b.getData() || eq.getStrongColor().getWoolData() == b.getData())return eq; + if(eq.getColor() == blockColor || eq.getStrongColor() == blockColor)return eq; } return null; } @@ -328,28 +329,44 @@ public void openWeaponSelectionMenu(Player p){ event.setWillClose(true); Player ply = event.getPlayer(); int i = event.getPosition(); - if(i == 0)getPlayerInfo(ply).setActiveWeapon(new RollerInkWeapon(ply)); - if(i == 1)getPlayerInfo(ply).setActiveWeapon(new BrushInkWeapon(ply)); - if(i == 2)getPlayerInfo(ply).setActiveWeapon(new MachinegunInkWeapon(ply)); - if(i == 3)getPlayerInfo(ply).setActiveWeapon(new EnderInkWeapon(ply)); + InkWeapon selectedWeapon = null; + if(i == 0)selectedWeapon = new RollerInkWeapon(ply); + if(i == 1)selectedWeapon = new BrushInkWeapon(ply); + if(i == 2)selectedWeapon = new MachinegunInkWeapon(ply); + if(i == 3)selectedWeapon = new EnderInkWeapon(ply); + if (selectedWeapon == null) return; + getPlayerInfo(ply).setActiveWeapon(selectedWeapon); + selectedWeapon.showInstructions(); sendTeamMessage(obtenirEquip(event.getPlayer()), event.getPlayer().getName() + " has selected " + event.getMenu().getOptionNames()[i]); }); int weaponLevel = getPlayerInfo(p).getWeaponLevel(); String string = Integer.toString(weaponLevel); String lvlString = ChatColor.GOLD + "" + ChatColor.BOLD + " [Level " + string + "]"; - menu.setOption(0, new ItemStack(Material.STICK, 1), ChatColor.GREEN + "" + ChatColor.BOLD + "Roller" + lvlString); - menu.setOption(1, new ItemStack(Material.TORCH, 1), ChatColor.YELLOW + "" + ChatColor.BOLD + "Brush" + lvlString); - menu.setOption(2, new ItemStack(Material.SNOWBALL, 1), ChatColor.BLUE + "" + ChatColor.BOLD + "Machinegun" + lvlString); - menu.setOption(3, new ItemStack(Material.ENDER_PEARL, 1), ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD + "Ender" + lvlString); + menu.setOption(0, new ItemStack(Material.STICK, 1), ChatColor.GREEN + "" + ChatColor.BOLD + "Roller" + lvlString, ChatColor.WHITE + "Paint a wide trail by moving."); + menu.setOption(1, new ItemStack(Material.TORCH, 1), ChatColor.YELLOW + "" + ChatColor.BOLD + "Brush" + lvlString, ChatColor.WHITE + "Paint a fast, narrow trail by moving."); + menu.setOption(2, new ItemStack(Material.SNOWBALL, 1), ChatColor.BLUE + "" + ChatColor.BOLD + "Machinegun" + lvlString, ChatColor.WHITE + "Throw ink balls to paint impact zones."); + menu.setOption(3, new ItemStack(Material.ENDER_PEARL, 1), ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD + "Ender" + lvlString, ChatColor.WHITE + "Pearl control, shield, swap, and a melee baton."); menu.open(p); } public boolean isPaintable(Block b){ - ArrayList p = new ArrayList<>(); - p.add(Material.WHITE_WOOL);p.add(Material.LEGACY_STAINED_CLAY);p.add(Material.LEGACY_STAINED_GLASS);p.add(Material.LEGACY_STAINED_GLASS_PANE); - // p.add(Material.STONE);p.add(Material.STONE);p.add(Material.STONE_B) - Material t = b.getType(); - return (p.contains(t)); + return getPaintColor(b.getType()) != null; + } + private DyeColor getPaintColor(Material material){ + String materialName = material.name(); + for (DyeColor color : DyeColor.values()) { + for (String suffix : new String[]{"_WOOL", "_TERRACOTTA", "_STAINED_GLASS", "_STAINED_GLASS_PANE"}) { + if (materialName.equals(color.name() + suffix)) return color; + } + } + return null; + } + private Material getPaintMaterial(Material currentMaterial, DyeColor color){ + String materialName = currentMaterial.name(); + for (String suffix : new String[]{"_WOOL", "_TERRACOTTA", "_STAINED_GLASS", "_STAINED_GLASS_PANE"}) { + if (materialName.endsWith(suffix)) return Material.valueOf(color.name() + suffix); + } + return Material.valueOf(color.name() + "_TERRACOTTA"); } public boolean isPaintableUnsafely(Block b){ Material t = b.getType(); @@ -409,6 +426,14 @@ public void giveTool(){ getPlayer().playSound(getPlayer().getEyeLocation(), Sound.BLOCK_PISTON_EXTEND, 1F, 1F); } public abstract ItemStack getToolMaterial(); + public String[] getInstructions(){ + return new String[0]; + } + public void showInstructions(){ + for (String line : getInstructions()) { + sendPlayerMessage(getPlayer(), ChatColor.LIGHT_PURPLE + "[Weapon] " + ChatColor.WHITE + line); + } + } public void reloadTick(){ if(getLoadMaterial() == null)return; if(getPlayer().getInventory().contains(getLoadMaterial().getType(), getMaxLoad()))return; @@ -462,8 +487,8 @@ public void paintBlock(Block b, double inkAmount){ //Register if(oldOwnerTeam != newOwnerTeam)getPlayerInfo(getPlayer()).registerBlockPaint(oldOwnerTeam); //Paint - if(forcedly)b.setType(Material.LEGACY_STAINED_CLAY); -// b.setData(sc.getWoolData(), false); + Material paintBase = forcedly ? Material.WHITE_TERRACOTTA : b.getType(); + b.setType(getPaintMaterial(paintBase, sc), false); double pInk = 0; if(highInkBlocks.containsKey(b)){ pInk = highInkBlocks.get(b).getSecond(); @@ -476,7 +501,10 @@ public void paintBlock(Block b, double inkAmount){ protected void paintRadius(Location c, double r, double inkAmount){ for(Block b : Utils.getCuboidAround(c, (int) Math.round(r)).getBlocks()) { double distance = c.distance(b.getLocation()); - if(distance <= r)paintBlock(b, inkAmount * Math.sqrt(1.0/distance)); //Area=pi*r^2 so r=sqrt(A/pi) + if (distance <= r) { + double cappedDistance = Math.max(distance, 0.25); + paintBlock(b, inkAmount * Math.sqrt(1.0 / cappedDistance)); //Area=pi*r^2 so r=sqrt(A/pi) + } } } } @@ -510,20 +538,20 @@ public void registerProjectile(Projectile proj) { protected void onProjectileHit(ProjectileHitEvent evt, Projectile proj) { super.onProjectileHit(evt, proj); - if(onHoldProjectileList.contains(proj)){ - Location loc = proj.getLocation(); - BlockIterator iterator = new BlockIterator(getWorld(), loc.toVector(), proj.getVelocity().normalize(), 0, 4); - Block hitBlock = null; - Block preHitBlock = null; - while(iterator.hasNext()) { - preHitBlock = hitBlock; - hitBlock = iterator.next(); - if(hitBlock.getType().getId()!=0) //Check all non-solid blockid's here. - {break;} - } - if (hitBlock != null && preHitBlock != null) { - onWeaponHit(evt, proj, hitBlock, preHitBlock); + if(onHoldProjectileList.remove(proj)){ + Block hitBlock = evt.getHitBlock(); + Block paintCenterBlock; + if (hitBlock != null) { + paintCenterBlock = evt.getHitBlockFace() == null + ? hitBlock : hitBlock.getRelative(evt.getHitBlockFace()); + } else if (evt.getHitEntity() != null) { + hitBlock = evt.getHitEntity().getLocation().getBlock(); + paintCenterBlock = hitBlock; + } else { + hitBlock = proj.getLocation().getBlock(); + paintCenterBlock = hitBlock; } + onWeaponHit(evt, proj, hitBlock, paintCenterBlock); } } public abstract void onWeaponHit(ProjectileHitEvent evt, Projectile proj, Block hitBlock, Block preHitBlock); @@ -552,7 +580,11 @@ public void onWeaponHit(ProjectileHitEvent evt, Projectile proj, Block hitBlock, paintRadius(preHitBlock.getLocation(), 1.1 + Math.sqrt(getWeaponLevel() * 0.75), 4 + getWeaponLevel() / 2.0); for(Player p : Utils.getNearbyPlayers(preHitBlock.getLocation(), 1 + getWeaponLevel())){ if(areEnemies(p, getPlayer())){ - p.damage(2 + (6.5 + (getWeaponLevel() / 2.2)) / (p.getLocation().distance(preHitBlock.getLocation()) * (preHitBlock.getLocation().distance(getPlayer().getEyeLocation()) / 3)), getPlayer()); + double targetDistance = Math.max(p.getLocation().distance(preHitBlock.getLocation()), 0.25); + double shotDistance = Math.max(preHitBlock.getLocation().distance(getPlayer().getEyeLocation()), 0.25); + double splashDamage = 2 + (6.5 + (getWeaponLevel() / 2.2)) + / (targetDistance * (shotDistance / 3)); + p.damage(splashDamage, getPlayer()); } } } @@ -562,6 +594,10 @@ public ItemStack getLoadMaterial() { return Utils.setItemName(new ItemStack(Material.SNOWBALL, 1), obtenirEquip(getPlayer()).getChatColor() + "Ink ball"); } @Override + public String[] getInstructions() { + return new String[]{"Throw snowballs to paint and damage around their impact.", "Reload faster while standing in your base or on your team's color."}; + } + @Override public ItemStack getToolMaterial() { return null; //No tool } @@ -608,12 +644,16 @@ public void onWeaponHit(ProjectileHitEvent evt, Projectile proj, Block hitBlock, public ItemStack getToolMaterial() { ItemStack i = new ItemStack(Material.BLAZE_ROD, 1); i.addUnsafeEnchantment(Enchantment.KNOCKBACK, 1); - return i; + return Utils.setItemNameAndLore(i, ChatColor.GOLD + "Warp baton", ChatColor.WHITE + "Melee hit: 4 damage and knockback.", ChatColor.GRAY + "Consumed on hit; recharges after 5 seconds."); } @Override public ItemStack getLoadMaterial() { - return Utils.setItemNameAndLore(new ItemStack(Material.ENDER_PEARL, 1), ChatColor.BLUE + "Magic ball", ChatColor.WHITE + "Makes enemies paint for you if it impacts on their face"); + return Utils.setItemNameAndLore(new ItemStack(Material.ENDER_PEARL, 1), ChatColor.LIGHT_PURPLE + "Control pearl", ChatColor.WHITE + "Impact: paint a large zone and gain a 6s shield.", ChatColor.WHITE + "Hit enemy: their movement paints for your team for 6s.", ChatColor.WHITE + "Hit the marked enemy again: swap positions.", ChatColor.GRAY + "Reloads faster on your color or inside your base."); + } + @Override + public String[] getInstructions() { + return new String[]{"Throw a pearl at terrain to paint a large zone and gain a 6-second shield.", "Hit an enemy to make their movement paint for your team for 6 seconds; hit that marked enemy again to swap positions.", "Use the Warp baton for a knockback melee hit; it is consumed and returns after 5 seconds.", "Pearls reload faster in your base or while standing on your team's color."}; } @Override protected void onPlayerDamageByPlayer(EntityDamageByEntityEvent evt, diff --git a/src/main/java/com/biel/lobby/mapes/jocs/KingSkeletonChallenge.java b/src/main/java/com/biel/lobby/mapes/jocs/KingSkeletonChallenge.java index 2fd9bed..8a3e879 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/KingSkeletonChallenge.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/KingSkeletonChallenge.java @@ -34,7 +34,7 @@ public class KingSkeletonChallenge extends JocCooperatiu { protected ArrayList getStartingItems(Player ply) { ArrayList items = new ArrayList<>(); ItemStack itemStack3 = new ItemStack(Material.DIAMOND_SWORD); - itemStack3.addEnchantment(Enchantment.DAMAGE_ALL, 2); + itemStack3.addEnchantment(Enchantment.SHARPNESS, 2); items.add(itemStack3); items.add(new ItemStack(Material.DIAMOND_HELMET)); items.add(new ItemStack(Material.DIAMOND_CHESTPLATE)); @@ -148,7 +148,7 @@ public void onDamage(EntityDamageByEntityEvent evt, Skeleton sk){ spawnMobsOnTree(c, EntityType.BLAZE, 4 + bonus); break; case BONUS: - spawnMobsOnTree(c, EntityType.THROWN_EXP_BOTTLE, 7 + bonus); + spawnMobsOnTree(c, EntityType.EXPERIENCE_BOTTLE, 7 + bonus); break; case MAGMA_CUBE: spawnMobsOnTree(c, EntityType.MAGMA_CUBE, 3 + bonus); @@ -184,7 +184,7 @@ public void onDamage(EntityDamageByEntityEvent evt, Skeleton sk){ //Teleport //Apply slowness - sk.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 12, 4)); + sk.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 12, 4)); } } public void teleportToEscape(Skeleton sk){ @@ -213,7 +213,6 @@ public SpellType getNextSpell(){ if (Utils.Possibilitat(2)){return SpellType.ZOMBIE;} return result; } - @SuppressWarnings("deprecation") public ItemStack getSpellItemStack(SpellType type){ switch(type){ case BLAZE: @@ -225,15 +224,15 @@ public ItemStack getSpellItemStack(SpellType type){ case MINEFIELD: return new ItemStack(Material.TNT); case SKELETON: - return new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 0, (byte) 0); + return new ItemStack(Material.SKELETON_SKULL); case SLIME: return new ItemStack(Material.SLIME_BALL); case WITCH: - return new ItemStack(Material.LEGACY_BREWING_STAND_ITEM); + return new ItemStack(Material.BREWING_STAND); case WITHER: - return new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 0, (byte) 1); + return new ItemStack(Material.WITHER_SKELETON_SKULL); case ZOMBIE: - return new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 0, (byte) 2); + return new ItemStack(Material.ZOMBIE_HEAD); default: return new ItemStack(Material.BEDROCK); @@ -261,7 +260,7 @@ public ArrayList getValidCircleLocations(Location center, Double radiu Location randomLoc = locs.get(Utils.NombreEntre(0, locs.size() - 1)); Block block = randomLoc.getBlock(); Material type = block.getType(); - if ((type == Material.GRASS || type == Material.LEGACY_REDSTONE_LAMP_ON) && block.getRelative(BlockFace.UP).isEmpty()){ + if ((type == Material.SHORT_GRASS || type == Material.REDSTONE_LAMP) && block.getRelative(BlockFace.UP).isEmpty()){ finalLocs.add(randomLoc); } //Bukkit.broadcastMessage("msg: " + Integer.toString(num) + " - - " + Integer.toString(locs.size()) + ": " + Integer.toString(finalLocs.size())); @@ -296,8 +295,8 @@ public void dropLoot(Location center){ d.add(new ItemStack(Material.ENDER_PEARL, Utils.NombreEntre(8, 16))); //d.add(SpecialItemsUtils.getRandomSpecialItem(2)); ItemStack itemStack3 = new ItemStack(Material.GOLDEN_HELMET); - itemStack3.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 9); - itemStack3.addUnsafeEnchantment(Enchantment.DURABILITY, 9); + itemStack3.addUnsafeEnchantment(Enchantment.PROTECTION, 9); + itemStack3.addUnsafeEnchantment(Enchantment.UNBREAKING, 9); d.add(itemStack3); center.getBlock().setType(Material.GOLD_BLOCK); Location cl = center.add(0, 1, 0); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/ObsidianDefenders.java b/src/main/java/com/biel/lobby/mapes/jocs/ObsidianDefenders.java index 36f2e9a..82dd7d8 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/ObsidianDefenders.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/ObsidianDefenders.java @@ -8,7 +8,6 @@ import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.SkullType; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.block.Block; @@ -86,7 +85,7 @@ protected ArrayList getStartingItems(Player ply) { items.add(Utils.createColoredTeamArmor(Material.LEATHER_BOOTS, e)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); // ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - // arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); + // arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); // items.add(arc); items.add(new ItemStack(Material.ARROW, 1)); //items.add(new Potion(PotionType.INSTANT_DAMAGE, 1).toItemStack(2)); @@ -194,14 +193,14 @@ protected void onEntityDamageByEntity(EntityDamageByEntityEvent evt, continue; } block.setType(Material.ICE); - Utils.BreakBlockLater(block, 20 * 4, false); + scheduleTrackedBlockRemoval(block, 20 * 4, false); } damaged.teleport(damaged.getLocation().getBlock().getLocation().add(new Vector(0.5,0,0.5))); Block gblock = damaged.getLocation().add(0, 2, 0).getBlock(); if (gblock.getType() == Material.AIR){ gblock.setType(Material.GOLD_BLOCK); - Utils.BreakBlockLater(gblock, 20 * 4, false); + scheduleTrackedBlockRemoval(gblock, 20 * 4, false); } pPlayer(damager).EstablirPropietat("StrongBowHitCount", 1); @@ -509,7 +508,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player plyr) { if(p.isDead() || !p.isOnline()){ continue; } - ItemStack steveItem = new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short)SkullType.PLAYER.ordinal()); + ItemStack steveItem = new ItemStack(Material.PLAYER_HEAD); inv1.addItem(Utils.setItemName(steveItem, p.getName())); } @@ -521,7 +520,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player plyr) { if (stack.getType() == Material.NETHER_STAR){ for(Player p : obtenirEquipEnemic(plyr).getPlayers()){ p.setHealth(1); - p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 20, 4, false), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 20, 4, false), true); } for(Player p : obtenirEquip(plyr).getPlayers()){ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20 * 20, 3, false), true); @@ -548,7 +547,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player plyr) { } if (stack.getType() == Material.STRING){ for(Player p : obtenirEquipEnemic(plyr).getPlayers()){ - p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 15 * 20, 2, false), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 15 * 20, 2, false), true); } plyr.sendMessage("Has alentit a l'equip enemic un 40% durant 15 segons."); inv.removeItem(new ItemStack(stack.getType())); @@ -562,7 +561,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player plyr) { } if (evt.getItem().getType() == Material.PAPER){ for(Player p : obtenirEquipEnemic(plyr).getPlayers()){ - p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 25 * 20, 5, false), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 25 * 20, 5, false), true); } plyr.sendMessage("Has esverat a l'equip enemic durant 25 segons."); inv.removeItem(new ItemStack(stack.getType())); @@ -639,10 +638,10 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player plyr) { // // Zombie slime = (Zombie)world.spawnEntity(base, EntityType.ZOMBIE); // slime.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 400 * 20, 4, false), true); - // slime.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 400 * 20, 1, false), true); - // slime.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 400 * 20, 1, false), true); + // slime.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 400 * 20, 1, false), true); + // slime.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 400 * 20, 1, false), true); // slime.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 20 * 20, 1, false), true); - // slime.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 400 * 20, 1, false), true); + // slime.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 400 * 20, 1, false), true); // // //ControllableMob mob = ControllableMobs.assign(slime); // //mob.getActions() @@ -784,7 +783,7 @@ static ItemStack Icona(lobby plugin, ObsidianDefenders j, Player plyr, AbilityTy disp = true; break; case COMANDANT: - mat = Material.LEGACY_COMMAND; + mat = Material.COMMAND_BLOCK; Titol = "Comandant"; Desc = "Augmenta el mal dels aliats propers un"; Desc2 = "12% i comença amb items addicionals"; @@ -940,7 +939,7 @@ protected void onProjectileHit(ProjectileHitEvent evt, Projectile proj) { explo = explo + 1F; explo = explo + (explo * 1.012F); } - if (inv.contains(Material.LEGACY_GOLD_SWORD) == true){ + if (inv.contains(Material.GOLDEN_SWORD)){ explo = explo + (explo * 0.20F); } if(Ability.hasAbility(plugin, this, player, AbilityType.PIROTÈCNIC)){ diff --git a/src/main/java/com/biel/lobby/mapes/jocs/OneInTheChamber.java b/src/main/java/com/biel/lobby/mapes/jocs/OneInTheChamber.java index 482a1bd..3c44a79 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/OneInTheChamber.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/OneInTheChamber.java @@ -12,7 +12,6 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.Potion; import org.bukkit.potion.PotionType; import com.biel.lobby.mapes.JocScoreRace; @@ -67,10 +66,7 @@ protected ArrayList getStartingItems(Player ply){ items.add(GUtils.createColoredArmor(Material.LEATHER_CHESTPLATE, color1)); items.add(GUtils.createColoredArmor(Material.LEATHER_LEGGINGS, color2)); items.add(GUtils.createColoredArmor(Material.LEATHER_BOOTS, color1)); - @SuppressWarnings("deprecation") - Potion p1 = new Potion(PotionType.INSTANT_DAMAGE); - p1.setSplash(true); - items.add(p1.toItemStack(1)); + items.add(Utils.createPotion(PotionType.HARMING, 1, true)); return items; } diff --git a/src/main/java/com/biel/lobby/mapes/jocs/Parkour.java b/src/main/java/com/biel/lobby/mapes/jocs/Parkour.java index 8847a14..03adf41 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/Parkour.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/Parkour.java @@ -38,9 +38,8 @@ import com.biel.lobby.mapes.jocs.Parkour.ParkourProvider.ParkourBubble.Checkpoint; import com.biel.lobby.utilities.Cuboid; import com.biel.lobby.utilities.Utils; -import com.connorlinfoot.titleapi.TitleAPI; -import com.gmail.filoghost.holographicdisplays.api.Hologram; -import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.biel.lobby.utilities.PaperMessages; +import com.biel.lobby.utilities.HologramFacade; public class Parkour extends JocScoreCombo{ @@ -239,7 +238,7 @@ public class BubbleHandler{ // Currentblock = provider !!! - Check other bubbles ArrayList positions = new ArrayList<>(); ArrayList checkpointHandlers = new ArrayList<>(); Score score; - Hologram h; + HologramFacade.Handle h; public BubbleHandler(int providerBubbleIndex) { super(); this.providerBubbleIndex = providerBubbleIndex; @@ -267,7 +266,7 @@ private Location getHologramLocation() { } public void createHolgram(){ if (h != null){return;} - h = HologramsAPI.createHologram(Com.getPlugin(), getHologramLocation()); + h = HologramFacade.create(getHologramLocation()); } public void updateHologram(){ if (h == null){return;} @@ -279,7 +278,8 @@ public void build(){ createHolgram(); } public void showScore (Score score){ - TitleAPI.sendTitle(getPlayer(),1,4,2,score.getFormattedString(),ChatColor.DARK_AQUA + "x" + getCombo(getPlayer())); + PaperMessages.showTitle(getPlayer(), 1, 4, 2, score.getFormattedString(), + ChatColor.DARK_AQUA + "x" + getCombo(getPlayer())); } public void advance(Score score){ ParkourPlayerInfo i = getPlayerInfo(getPlayer()); @@ -372,8 +372,8 @@ public void registerFail(Player p) { getPlayer().playSound(getPlayer().getEyeLocation(), Sound.ENTITY_HORSE_ARMOR, 1F, 1.1F); advance(Score.FAIL); - p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 25, 129)); - p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 25, 129)); + p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 25, 129)); + p.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 25, 129)); } //CHECKPOINT HANDLER @@ -381,7 +381,7 @@ public class CheckpointHandler{ int checkpointIndex; boolean completed; boolean wasPlayerInsideRange = false; - Hologram ho; + HologramFacade.Handle ho; public CheckpointHandler(int checkpointIndex) { super(); this.checkpointIndex = checkpointIndex; @@ -449,7 +449,7 @@ private Location getHologramLocation() { } public void createHolgram(){ if (ho != null){return;} - ho = HologramsAPI.createHologram(Com.getPlugin(), getHologramLocation()); + ho = HologramFacade.create(getHologramLocation()); } public void updateHologram(){ if (ho == null){createHolgram();} @@ -671,7 +671,7 @@ public void generate() { blocks.add(lc);materials.add((t == 1 ? Material.PACKED_ICE : Material.QUARTZ_BLOCK)); Vector dlc = lc.clone().add(d); Material mat = Material.QUARTZ_BLOCK; - if(t == 1)if(GUtils.Possibilitat(30))mat = Material.LEGACY_IRON_FENCE; + if(t == 1)if(GUtils.Possibilitat(30))mat = Material.IRON_BARS; if(t == 2)if(GUtils.Possibilitat(60))mat = Material.PACKED_ICE; blocks.add(dlc);materials.add(mat); checkpoints.add(new Checkpoint(dlc)); @@ -697,7 +697,7 @@ public void generate() { checkpoints.add(new Checkpoint(getZero())); for(int i = 1; i < 15; i++){ if (Utils.Possibilitat(80)){ - blocks.add(getForward().multiply(i));materials.add(Material.LEGACY_STAINED_GLASS_PANE); + blocks.add(getForward().multiply(i));materials.add(Material.WHITE_STAINED_GLASS_PANE); if (i % 3 == 0) checkpoints.add(new Checkpoint(getForward().multiply(i))); } } @@ -745,8 +745,8 @@ public void generate() { blocks.add(getForward().multiply(2 * i));materials.add(Material.QUARTZ_BLOCK); blocks.add(getForward().multiply(2 * i + 1).add(getRight().multiply(2)));materials.add(Material.QUARTZ_BLOCK); if(i < n - 1){ - blocks.add(getForward().multiply(2 * i + 1).add(getUp()));materials.add(Material.FENCE); - blocks.add(getForward().multiply(2 * i + 2).add(getRight().multiply(2)).add(getUp()));materials.add(Material.FENCE); + blocks.add(getForward().multiply(2 * i + 1).add(getUp()));materials.add(Material.OAK_FENCE); + blocks.add(getForward().multiply(2 * i + 2).add(getRight().multiply(2)).add(getUp()));materials.add(Material.OAK_FENCE); } } blocks.stream().filter(b -> materialGetter.apply(b) == Material.QUARTZ_BLOCK).forEach(b -> checkpoints.add(new Checkpoint(b, 0.9))); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/PilotaSplash.java b/src/main/java/com/biel/lobby/mapes/jocs/PilotaSplash.java index 0a7b355..8b51bfe 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/PilotaSplash.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/PilotaSplash.java @@ -46,7 +46,7 @@ protected void donarEfectesInicials(Player ply) { // TODO Auto-generated method stub super.donarEfectesInicials(ply); //ply.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 0, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 4, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, Integer.MAX_VALUE, 4, true), true); } @Override diff --git a/src/main/java/com/biel/lobby/mapes/jocs/Quakecraft.java b/src/main/java/com/biel/lobby/mapes/jocs/Quakecraft.java index 2d9208f..4afeee7 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/Quakecraft.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/Quakecraft.java @@ -74,7 +74,7 @@ protected void customJocIniciat() { @Override protected ArrayList getStartingItems(Player ply) { ArrayList items = new ArrayList<>(); - items.add(new ItemStack(Material.LEGACY_WOOD_HOE, 1)); + items.add(new ItemStack(Material.WOODEN_HOE, 1)); return items; } @Override @@ -87,7 +87,7 @@ protected void donarEfectesInicials(Player ply) { // TODO Auto-generated method stub super.donarEfectesInicials(ply); ply.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 1, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, Integer.MAX_VALUE, 1, true), true); } @Override @@ -119,7 +119,7 @@ ItemStack getRailgun(Player ply){ ItemStack item = new ItemStack(Material.DIAMOND_HOE); if(t >= 1000){return Utils.setItemNameAndLore(item, ChatColor.AQUA + "Railgun", l);} if(t > 550){return Utils.setItemNameAndLore(item, ChatColor.AQUA + "Ultimate Railgun", l);} - item.addEnchantment(Enchantment.ARROW_DAMAGE, 4); + item.addEnchantment(Enchantment.POWER, 4); if(t <= 550){return Utils.setItemNameAndLore(item, ChatColor.AQUA +"SUPER Railgun", l);} return new ItemStack(Material.OAK_PLANKS); } @@ -266,10 +266,10 @@ void railgunHitPlace(Player shooter, Projectile proj){ } private Color getColorRailgun(Player ply){ Material t = getRailgun(ply).getType(); - if(t == Material.LEGACY_WOOD_HOE){return Color.RED;} + if(t == Material.WOODEN_HOE){return Color.RED;} if(t == Material.STONE_HOE){return Color.GREEN;} if(t == Material.IRON_HOE){return Color.SILVER;} - if(t == Material.LEGACY_GOLD_HOE){return Color.YELLOW;} + if(t == Material.GOLDEN_HOE){return Color.YELLOW;} if(t == Material.DIAMOND_HOE){return Color.AQUA;} return Color.BLACK; } @@ -289,7 +289,7 @@ private void playRailgunEffect(Player p, Location l, boolean hit, boolean specia FireworkEffect r = b.build(); Player pArr[] = new Player[getPlayers().size()]; getPlayers().toArray(pArr); - Firework firework = (Firework) getWorld().spawnEntity(l, EntityType.FIREWORK); + Firework firework = (Firework) getWorld().spawnEntity(l, EntityType.FIREWORK_ROCKET); FireworkMeta fireworkMeta = firework.getFireworkMeta(); fireworkMeta.addEffect(r); fireworkMeta.setPower(1); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/RainbowClay.java b/src/main/java/com/biel/lobby/mapes/jocs/RainbowClay.java index 3ed1a5a..2979cd3 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/RainbowClay.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/RainbowClay.java @@ -30,7 +30,7 @@ import com.biel.lobby.mapes.JocObjectius; import com.biel.lobby.utilities.Cuboid; import com.biel.lobby.utilities.Utils; -import com.connorlinfoot.bountifulapi.BountifulAPI; +import com.biel.lobby.utilities.PaperMessages; public class RainbowClay extends JocObjectius { public RainbowClay() { @@ -134,7 +134,7 @@ protected ArrayList getStartingItems(Player ply) { items.add(new ItemStack(Material.IRON_SWORD, 1)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); items.add(arc); double balancingMultiplier = getBalancingMultiplier(e); @@ -152,7 +152,7 @@ protected ArrayList getStartingItems(Player ply) { ItemStack pickaxe = new ItemStack(Material.DIAMOND_PICKAXE, 1); if (balancingMultiplier > 1) - pickaxe.addUnsafeEnchantment(Enchantment.DIG_SPEED, (balancingMultiplier > 1.20 ? 2 : 1)); + pickaxe.addUnsafeEnchantment(Enchantment.EFFICIENCY, (balancingMultiplier > 1.20 ? 2 : 1)); items.add(pickaxe); int arrows = (int) (50 * balancingMultiplier); @@ -172,11 +172,9 @@ protected ArrayList getStartingItems(Player ply) { block_amount = 64; } if (obtenirEquip(ply).getId() == 0) { - - items.add(new ItemStack(Material.LEGACY_STAINED_CLAY, block_amount, (short) 14)); + items.add(new ItemStack(Material.RED_TERRACOTTA, block_amount)); } else { - - items.add(new ItemStack(Material.LEGACY_STAINED_CLAY, block_amount, (short) 10)); + items.add(new ItemStack(Material.PURPLE_TERRACOTTA, block_amount)); } items.add(new ItemStack(Material.COBWEB, 1)); @@ -193,10 +191,10 @@ protected void donarEfectesInicials(Player ply) { double m = getBalancingMultiplier(obtenirEquip(ply)); ply.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, (int) (30 * 10 * (m - 0.5)), 5, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 3, 1, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20 * 30, 0, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20 * 5, 3, true), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, (int) (20 * 19 * m), 1, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 3, 1, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.HASTE, 20 * 30, 0, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 20 * 5, 3, true), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, (int) (20 * 19 * m), 1, true), true); } @@ -214,7 +212,7 @@ protected void onBlockPlace(BlockPlaceEvent evt, Block blk) { if (blk.getType() == Material.OBSIDIAN) { String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots utilitzar aquest bloc"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); evt.setCancelled(true); return; } @@ -224,7 +222,7 @@ protected void onBlockPlace(BlockPlaceEvent evt, Block blk) { evt.setCancelled(true); String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots modificar la llana"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); } } @@ -247,18 +245,18 @@ protected void onBlockBreak(BlockBreakEvent evt, Block blk) { evt.setCancelled(true); String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots modificar la llana"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); } if (centre.contains(blk) && blk.getType() == Material.CHEST) { evt.setCancelled(true); String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots destruir els cofres del centre"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); } - if (blk.getType() == Material.LEGACY_STAINED_CLAY && blk.getData() == 11) { + if (blk.getType() == Material.BLUE_TERRACOTTA) { evt.setCancelled(true); } @@ -279,7 +277,7 @@ protected void onBlockBreak(BlockBreakEvent evt, Block blk) { ply.playSound(ply.getLocation(), Sound.BLOCK_CHEST_LOCKED, 100.0F, 0.0F); evt.setCancelled(true); String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots destruir els cofres enemics"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); } @@ -312,7 +310,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player p) { if (base.contains(blk)) { String msg = ChatColor.RED + "" + ChatColor.ITALIC + "No pots interactuar amb els cofres enemics"; - BountifulAPI.sendActionBar(ply, msg, 150); + PaperMessages.sendActionBar(ply, msg, 150); ply.playSound(ply.getLocation(), Sound.BLOCK_CHEST_LOCKED, 100.0F, 0.0F); evt.setCancelled(true); } @@ -408,8 +406,7 @@ protected void onBlockHitByProjectile(ProjectileHitEvent evt, Block b, Projectil super.onBlockHitByProjectile(evt, b, proj); // sendGlobalMessage("Pilotassa"); Material t = b.getType(); - if (t == Material.GLASS || t == Material.LEGACY_STAINED_GLASS || t == Material.LEGACY_STAINED_GLASS_PANE - || t == Material.LEGACY_THIN_GLASS || t == Material.GLOWSTONE) { + if (isBreakableGlass(t)) { b.setType(Material.AIR); getWorld().playSound(b.getLocation(), Sound.BLOCK_GLASS_BREAK, 15F, 1.2F); proj.remove(); @@ -418,21 +415,29 @@ protected void onBlockHitByProjectile(ProjectileHitEvent evt, Block b, Projectil continue; Block relative = b.getRelative(f); t = relative.getType(); - if (t == Material.GLASS || t == Material.LEGACY_STAINED_GLASS || t == Material.LEGACY_STAINED_GLASS_PANE - || t == Material.LEGACY_THIN_GLASS || t == Material.GLOWSTONE) { + if (isBreakableGlass(t)) { relative.setType(Material.AIR); } } } } + private boolean isBreakableGlass(Material material) { + String materialName = material.name(); + return material == Material.GLASS + || material == Material.GLASS_PANE + || material == Material.GLOWSTONE + || materialName.endsWith("_STAINED_GLASS") + || materialName.endsWith("_STAINED_GLASS_PANE"); + } + @Override protected void onPlayerDamageByPlayer(EntityDamageByEntityEvent evt, Player damaged, Player damager, boolean ranged) { super.onPlayerDamageByPlayer(evt, damaged, damager, ranged); if (ranged && damaged.isSneaking()) { damaged.setVelocity(new Vector()); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> damaged.setVelocity(new Vector()), 1); + scheduleGameplayTask(() -> damaged.setVelocity(new Vector()), 1); } } @@ -490,19 +495,19 @@ public List getPotionChestItems() { meta.addCustomEffect(new PotionEffect(PotionEffectType.GLOWING, 600, 1), true); break; case 3: - meta.addCustomEffect(new PotionEffect(PotionEffectType.SLOW, 120, 2), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.SLOWNESS, 120, 2), true); break; case 4: meta.addCustomEffect(new PotionEffect(PotionEffectType.LEVITATION, 40, 3), true); break; case 5: - meta.addCustomEffect(new PotionEffect(PotionEffectType.CONFUSION, 280, 2), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.NAUSEA, 280, 2), true); break; case 6: meta.addCustomEffect(new PotionEffect(PotionEffectType.WEAKNESS, 400, 2), true); break; case 7: - meta.addCustomEffect(new PotionEffect(PotionEffectType.JUMP, 80, 8), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 80, 8), true); break; default: break; @@ -548,36 +553,36 @@ public List getMiddleChestItems() { n++; } if (Utils.Possibilitat(2)) { - ItemStack item = new ItemStack(Material.LEGACY_GOLD_LEGGINGS, 1); + ItemStack item = new ItemStack(Material.GOLDEN_LEGGINGS, 1); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.PROTECTION, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) item.addUnsafeEnchantment(Enchantment.THORNS, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.FIRE_PROTECTION, Utils.NombreEntre(1, 5)); llistaItems.add(item); n++; } if (Utils.Possibilitat(2)) { - ItemStack item = new ItemStack(Material.LEGACY_GOLD_CHESTPLATE, 1); + ItemStack item = new ItemStack(Material.GOLDEN_CHESTPLATE, 1); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.PROTECTION, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) item.addUnsafeEnchantment(Enchantment.THORNS, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.FIRE_PROTECTION, Utils.NombreEntre(1, 5)); llistaItems.add(item); n++; } if (Utils.Possibilitat(2)) { - ItemStack item = new ItemStack(Material.LEGACY_GOLD_BOOTS, 1); + ItemStack item = new ItemStack(Material.GOLDEN_BOOTS, 1); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.PROTECTION, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) item.addUnsafeEnchantment(Enchantment.THORNS, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.FIRE_PROTECTION, Utils.NombreEntre(1, 5)); llistaItems.add(item); n++; @@ -585,21 +590,21 @@ public List getMiddleChestItems() { if (Utils.Possibilitat(2)) { ItemStack item = new ItemStack(Material.GOLDEN_HELMET, 1); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.PROTECTION, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) item.addUnsafeEnchantment(Enchantment.THORNS, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(15)) - item.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, Utils.NombreEntre(1, 5)); + item.addUnsafeEnchantment(Enchantment.FIRE_PROTECTION, Utils.NombreEntre(1, 5)); llistaItems.add(item); n++; } if (Utils.Possibilitat(1)) { - ItemStack item = new ItemStack(Material.LEGACY_GOLD_AXE, 1); + ItemStack item = new ItemStack(Material.GOLDEN_AXE, 1); if (Utils.Possibilitat(30)) item.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, Utils.NombreEntre(1, 5)); if (Utils.Possibilitat(1)) - item.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 1); + item.addUnsafeEnchantment(Enchantment.SHARPNESS, 1); llistaItems.add(item); n++; @@ -632,13 +637,13 @@ public List getMiddleChestItems() { meta.addCustomEffect(new PotionEffect(PotionEffectType.ABSORPTION, 800, 4), true); break; case 3: - meta.addCustomEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 800, 2), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.HASTE, 800, 2), true); break; case 4: meta.addCustomEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 1200, 1), true); break; case 5: - meta.addCustomEffect(new PotionEffect(PotionEffectType.JUMP, 320, 5), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 320, 5), true); break; case 6: meta.addCustomEffect(new PotionEffect(PotionEffectType.REGENERATION, 600, 1), true); @@ -647,12 +652,12 @@ public List getMiddleChestItems() { meta.addCustomEffect(new PotionEffect(PotionEffectType.GLOWING, 320, 1), true); break; case 9: - meta.addCustomEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 600, 1), true); + meta.addCustomEffect(new PotionEffect(PotionEffectType.STRENGTH, 600, 1), true); break; default: break; } - meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); + meta.addItemFlags(ItemFlag.HIDE_ADDITIONAL_TOOLTIP); meta.setDisplayName("Poció Màgica"); meta.setColor(Color.YELLOW); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/RedstoneWars.java b/src/main/java/com/biel/lobby/mapes/jocs/RedstoneWars.java index c20aa65..c7d14b1 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/RedstoneWars.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/RedstoneWars.java @@ -54,8 +54,8 @@ protected ArrayList getStartingItems(Player ply) { items.add(Utils.createColoredTeamArmor(Material.LEATHER_BOOTS, e)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 10); - arc.addUnsafeEnchantment(Enchantment.ARROW_KNOCKBACK, 1); + arc.addUnsafeEnchantment(Enchantment.INFINITY, 10); + arc.addUnsafeEnchantment(Enchantment.PUNCH, 1); arc.addUnsafeEnchantment(Enchantment.KNOCKBACK, 4); items.add(arc); items.add(new ItemStack(Material.ARROW, 1)); @@ -131,7 +131,7 @@ public Boolean getBlockBreakPlace() { protected void onBlockBreak(BlockBreakEvent evt, Block blk) { // TODO Auto-generated method stub super.onBlockBreak(evt, blk); - if(blk.getType() == Material.LEGACY_GLOWING_REDSTONE_ORE)evt.setCancelled(false); + if(blk.getType() == Material.REDSTONE_ORE)evt.setCancelled(false); if (blk.getType() == Material.GOLD_BLOCK) { GUtils.getLocationsCircle(blk.getLocation(), 1.1, 32).forEach(l -> { FallingBlock tnt = world.spawnFallingBlock(l, Material.REDSTONE_ORE, (byte) 0x0); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/ResourceRush.java b/src/main/java/com/biel/lobby/mapes/jocs/ResourceRush.java index f0e9bd6..66e28ba 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/ResourceRush.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/ResourceRush.java @@ -102,7 +102,7 @@ public double getMaterialStartingAmount(Material m){ } public ArrayList getChestStartingContents(int m){ ArrayList r = new ArrayList<>(); - r.add(new ItemStack(Material.LEGACY_LOG, 2 * m)); + r.add(new ItemStack(Material.OAK_LOG, 2 * m)); r.add(new ItemStack(Material.COAL, 4 * m)); r.add(new ItemStack(Material.COAL, 4 * m)); r.add(new ItemStack(Material.IRON_INGOT, 4 * m)); @@ -271,9 +271,9 @@ public void updatePotionEffects(){ getPlayer().removePotionEffect(PotionEffectType.SPEED); } if (SL > 0) { - getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 5, SL - 1, true, true)); + getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 5, SL - 1, true, true)); }else{ - getPlayer().removePotionEffect(PotionEffectType.SLOW); + getPlayer().removePotionEffect(PotionEffectType.SLOWNESS); } } private int getModifier(int SP, int SL){ diff --git a/src/main/java/com/biel/lobby/mapes/jocs/RoboRampage.java b/src/main/java/com/biel/lobby/mapes/jocs/RoboRampage.java index 4c5e2a8..23c5d99 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/RoboRampage.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/RoboRampage.java @@ -176,7 +176,7 @@ public void spawnEnemy(){ } public void ProgTask(){ - tid = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> spawnEnemy(), 1, 2 * 20); // *12 + tid = scheduleGameplayRepeatingTask(() -> spawnEnemy(), 1, 2 * 20); // *12 } @Override protected void onBlockPlace(BlockPlaceEvent evt, Block blk) { @@ -196,7 +196,7 @@ protected void onEntityDeath(EntityDeathEvent evt, Entity e) { Material htype = z.getEquipment().getHelmet().getType(); if (htype == Material.REDSTONE_BLOCK){ - killer.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20 * 20, 1)); + killer.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 20 * 20, 1)); } if (htype == Material.LAPIS_BLOCK){ killer.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20 * 20, 1)); diff --git a/src/main/java/com/biel/lobby/mapes/jocs/Spleef.java b/src/main/java/com/biel/lobby/mapes/jocs/Spleef.java index 538b46c..4ef1412 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/Spleef.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/Spleef.java @@ -42,6 +42,15 @@ public class Spleef extends JocLastStanding { + private static final int WOOD_HOE_REVEAL_TICKS = 12; + private static final int STONE_HOE_REVEAL_TICKS = 14; + private static final int DIAMOND_HOE_REVEAL_TICKS = 16; + private static final int[] IRON_HOE_REVEAL_DELAYS = { + 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 15, 19, 24 + }; + private static final int[] GOLD_HOE_REVEAL_DELAYS = { + 0, 1, 2, 3, 5, 6, 8, 10, 12, 14, 16, 19, 22, 25, 29, 33, 41 + }; public Spleef() { @@ -67,11 +76,12 @@ public void customJocIniciat() { super.customJocIniciat(); setBlockBreakPlace(true); initAlivePlayers(); - BukkitTask task = new DonarPales().runTaskLater(plugin, 4 * 20); + BukkitTask shovelTask = new DonarPales().runTaskTimer(plugin, 4 * 20L, 6 * 20L); + handleTask(shovelTask.getTaskId()); for (Player p : getPlayers()) { - p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 400 * 20, 8, true), true); - p.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20 * 20, 85, true), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 400 * 20, 8, true), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.HASTE, 20 * 20, 85, true), true); p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 16 * 20, 2, true), true); } } @@ -104,65 +114,38 @@ void Pales(){ } public class DonarPales extends BukkitRunnable { public int vegades = 0; - public Boolean Hoe = true; - - - public DonarPales() { - - } - - public void run() { - timer.schedule (hourlyTask, 0L, 1000 * 5 + 58); - } - Timer timer = new Timer (); - TimerTask hourlyTask = new TimerTask () { - @Override - public void run () { - List play = getPlayers(); - - - - for (Player d : play) { // d gets successively each value in ar. - // - Material mat = pala(vegades); - - Hoe = !mat.name().contains("_SPADE"); - Inventory inv = d.getInventory(); + @Override + public void run() { + if (world == null || !JocEnMarxa()) { + cancel(); + return; + } - ItemStack itemstack = new ItemStack(mat, 1); + for (Player player : getPlayers()) { + Material material = pala(vegades); + Inventory inventory = player.getInventory(); + ItemStack itemStack = new ItemStack(material, 1); - if (vegades == 6){ - //itemstack.addUnsafeEnchantment(Enchantment.DIG_SPEED, 10); - } - if (vegades == 10){ - itemstack.addUnsafeEnchantment(Enchantment.ARROW_KNOCKBACK, 1); - ItemStack arr = new ItemStack(Material.ARROW, 3); - inv.addItem(arr); - } - if (vegades == 12){ - ItemStack arr = new ItemStack(Material.ARROW, 2); - inv.addItem(arr); - } - if (Hoe){ - inv.addItem(itemstack); - }else{ - inv.setItem(0, itemstack); - } + if (vegades == 10) { + itemStack.addUnsafeEnchantment(Enchantment.PUNCH, 1); + inventory.addItem(new ItemStack(Material.ARROW, 3)); } - if (vegades != 10){ - // World world = plugin.getServer().getWorlds().get(0); - // ArrayList locs = plugin.pMapaActual.ObtenirLocations("arena", world); - // Location loc = new Location(world, plugin.NombreEntre(locs.get(0).getBlockX(), locs.get(1).getBlockX()), locs.get(0).getY() + 1, plugin.NombreEntre(locs.get(0).getBlockZ(), locs.get(1).getBlockZ())); - // ItemStack arr = new ItemStack(Material.LAPIS_BLOCK, 1); - // world.dropItem(loc, arr); + if (vegades == 12) { + inventory.addItem(new ItemStack(Material.ARROW, 2)); } + if (material.name().endsWith("_SHOVEL")) { + inventory.setItem(0, itemStack); + } else { + inventory.addItem(itemStack); + } + } - vegades = vegades + 1; + vegades++; + } - } - public Material pala(int vegades){ + public Material pala(int vegades){ Material mat = Material.WOODEN_SHOVEL; if (vegades == 0){mat = Material.WOODEN_SHOVEL;} if (vegades == 1){mat = Material.WOODEN_HOE;} @@ -192,11 +175,7 @@ public Material pala(int vegades){ } } return mat; - - } - - - }; + } } @@ -240,7 +219,7 @@ protected synchronized void gameEvent(Event event) { if (event instanceof EntityExplodeEvent){ EntityExplodeEvent evt = (EntityExplodeEvent)event; evt.setYield(8); - if (entity.getType() == EntityType.PRIMED_TNT){ + if (entity.getType() == EntityType.TNT){ ArrayList rem = new ArrayList<>(); for (Block b : evt.blockList()){ if (b.getType() != Material.SNOW_BLOCK){ @@ -340,7 +319,7 @@ private void arrowAoE(Location loc, ProjectileHitEvent evt, private void efectesPales(Player p, PlayerInteractEvent evt, ItemStack stack, Inventory inv) { if (stack == null) {return;} - Material hand = p.getItemInHand().getType(); + Material hand = stack.getType(); if (hand == Material.LAPIS_BLOCK || hand == Material.REDSTONE_BLOCK || hand == Material.GOLD_BLOCK || hand == Material.IRON_BLOCK){ if (evt.getAction() == Action.RIGHT_CLICK_AIR){ Byte blockData = 0x0; @@ -368,18 +347,13 @@ private void efectesPales(Player p, PlayerInteractEvent evt, Boolean utilitzat = false; if (evt.getAction() == Action.RIGHT_CLICK_BLOCK){ Location loc = evt.getClickedBlock().getLocation(); - if (stack.getType() == Material.LEGACY_WOOD_HOE || stack.getType() == Material.STONE_HOE || stack.getType() == Material.IRON_HOE || stack.getType() == Material.LEGACY_GOLD_HOE || stack.getType() == Material.DIAMOND_HOE){ + if (stack.getType() == Material.WOODEN_HOE || stack.getType() == Material.STONE_HOE || stack.getType() == Material.IRON_HOE || stack.getType() == Material.GOLDEN_HOE || stack.getType() == Material.DIAMOND_HOE){ Location ploc = p.getLocation(); ploc.setY(ploc.getY() - 1); int dir = 0; - Boolean CoordX = null; - if (loc.getBlockX() == ploc.getBlockX()){ - CoordX = false; - } - if (loc.getBlockZ() == ploc.getBlockZ()){ - CoordX = true; - } + Boolean CoordX = Math.abs(loc.getBlockX() - ploc.getBlockX()) + >= Math.abs(loc.getBlockZ() - ploc.getBlockZ()); if (CoordX != null){ Boolean Signe = null; if (CoordX == true){ @@ -397,8 +371,12 @@ private void efectesPales(Player p, PlayerInteractEvent evt, //Bukkit.broadcastMessage("Signe=" + Signe.toString() + " CoordX=" + CoordX.toString()); if (stack.getType() == Material.WOODEN_HOE || stack.getType() == Material.STONE_HOE){ int pass = 0; + int lastPass = Math.max(0, countSnowRun(bloc, CoordX, Increment) - 1); Boolean wood = false; while (bloc.getBlock().getType() == Material.SNOW_BLOCK){ + int revealTicks = stack.getType() == Material.WOODEN_HOE + ? WOOD_HOE_REVEAL_TICKS : STONE_HOE_REVEAL_TICKS; + int delay = easeOutRevealDelay(pass, lastPass, revealTicks); if (bloc.equals(ploc) == false){ if (stack.getType() == Material.WOODEN_HOE){ utilitzat = true; @@ -408,25 +386,25 @@ private void efectesPales(Player p, PlayerInteractEvent evt, if (CoordX == false){ blocmod.setX(bloc.getX() + 1); //blocmod.getBlock().setType(BREAK_TYPE); - blocmod.getBlock().setType(Material.SAND); + setBlockLater(blocmod.getBlock(), Material.SAND, delay); blocmod.setX(bloc.getX() - 1); //blocmod.getBlock().setType(BREAK_TYPE); - blocmod.getBlock().setType(Material.SAND); + setBlockLater(blocmod.getBlock(), Material.SAND, delay); }else{ blocmod.setZ(bloc.getZ() + 1); - blocmod.getBlock().setType(BREAK_TYPE); + setBlockLater(blocmod.getBlock(), BREAK_TYPE, delay); blocmod.setZ(bloc.getZ() - 1); - blocmod.getBlock().setType(BREAK_TYPE); - } + setBlockLater(blocmod.getBlock(), BREAK_TYPE, delay); + } }else{ //bloc.getBlock().setType(BREAK_TYPE); - bloc.getBlock().setType(Material.SAND); + setBlockLater(bloc.getBlock(), Material.SAND, delay); } wood = !wood; } if (stack.getType() == Material.STONE_HOE){ utilitzat = true; - bloc.getBlock().setType(BREAK_TYPE); + setBlockLater(bloc.getBlock(), BREAK_TYPE, delay); if (Utils.Possibilitat(30)){ int direcció = 1; if (Utils.Possibilitat(50)){ @@ -438,7 +416,7 @@ private void efectesPales(Player p, PlayerInteractEvent evt, }else{ blocmod.setZ(bloc.getZ() + direcció); } - blocmod.getBlock().setType(BREAK_TYPE); + setBlockLater(blocmod.getBlock(), BREAK_TYPE, delay); ItemStack itemstack = new ItemStack(Material.STONE, 1); // A stack of diamonds //world.dropItem(blocmod, itemstack); } @@ -464,21 +442,22 @@ private void efectesPales(Player p, PlayerInteractEvent evt, while (bloc.getBlock().getType() == Material.SNOW_BLOCK || bloc.getBlock().getType() == Material.AIR || stack.getType() == Material.DIAMOND_HOE){ if (stack.getType() == Material.IRON_HOE){ utilitzat = true; + int delay = authoredRevealDelay(pass, IRON_HOE_REVEAL_DELAYS); if (pass <= 8){ if (iron == true){ Location blocmodp = bloc.clone(); Location blocmodn = bloc.clone(); - Utils.BreakBlockLater(bloc.getBlock(), (1 * pass)/2,true); + breakBlockLater(bloc.getBlock(), delay,true); //bloc.getBlock().setType(Material.SAND); if (CoordX == false){ int i = 0; while (i < amp){ blocmodp.setX(blocmodp.getX() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), (1 * pass)/2,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setX(blocmodn.getX() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), (1 * pass)/2,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; } }else{ @@ -486,10 +465,10 @@ private void efectesPales(Player p, PlayerInteractEvent evt, while (i < amp){ blocmodp.setZ(blocmodp.getZ() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), (1 * pass)/2,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setZ(blocmodn.getZ() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), (1 * pass)/2,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; } } @@ -509,17 +488,17 @@ private void efectesPales(Player p, PlayerInteractEvent evt, if (pass == 14){break;} Location blocmodp = bloc.clone(); Location blocmodn = bloc.clone(); - Utils.BreakBlockLater(bloc.getBlock(), 1 * 9,true); + breakBlockLater(bloc.getBlock(), delay,true); //bloc.getBlock().setType(BREAK_TYPE); if (CoordX == false){ int i = 0; while (i < amp){ blocmodp.setX(blocmodp.getX() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), 1 * 9,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setX(blocmodn.getX() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), 1 * 9,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; } }else{ @@ -527,16 +506,16 @@ private void efectesPales(Player p, PlayerInteractEvent evt, while (i < amp){ blocmodp.setZ(blocmodp.getZ() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), 1 * 9,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setZ(blocmodn.getZ() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), 1 * 9,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; } } } } - if (stack.getType() == Material.LEGACY_GOLD_HOE){ + if (stack.getType() == Material.GOLDEN_HOE){ utilitzat = true; if (pass == 0){amp = 0;} @@ -560,31 +539,28 @@ private void efectesPales(Player p, PlayerInteractEvent evt, Location blocmodp = bloc.clone(); Location blocmodn = bloc.clone(); //bloc.getBlock().setType(BREAK_TYPE); - int delay = 2 * pass; - if(pass >= 16){ - delay += 20; - } - Utils.BreakBlockLater(bloc.getBlock(), delay,true); + int delay = authoredRevealDelay(pass, GOLD_HOE_REVEAL_DELAYS); + breakBlockLater(bloc.getBlock(), delay,true); if (CoordX == false){ int i = 0; while (i < amp){ - blocmodp.setX(blocmodp.getX() + 1); + blocmodp.setX(blocmodp.getX() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), delay,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setX(blocmodn.getX() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), delay,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; - } + } }else{ int i = 0; while (i < amp){ blocmodp.setZ(blocmodp.getZ() + 1); //blocmodp.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodp.getBlock(), delay,true); + breakBlockLater(blocmodp.getBlock(), delay,true); blocmodn.setZ(blocmodn.getZ() - 1); //blocmodn.getBlock().setType(Material.SAND); - Utils.BreakBlockLater(blocmodn.getBlock(), delay,true); + breakBlockLater(blocmodn.getBlock(), delay,true); i = i + 1; } } @@ -602,23 +578,24 @@ private void efectesPales(Player p, PlayerInteractEvent evt, if (pass == 12){break;} Location blocmodp = bloc.clone(); Location blocmodn = bloc.clone(); - bloc.getBlock().setType(BREAK_TYPE); + int delay = easeOutRevealDelay(pass, 11, DIAMOND_HOE_REVEAL_TICKS); + setBlockLater(bloc.getBlock(), BREAK_TYPE, delay); if (CoordX == false){ int i = 0; while (i < amp){ - blocmodp.setX(blocmodp.getX() + 1); - blocmodp.getBlock().setType(BREAK_TYPE); - blocmodn.setX(blocmodn.getX() - 1); - blocmodn.getBlock().setType(BREAK_TYPE); + blocmodp.setX(blocmodp.getX() + 1); + setBlockLater(blocmodp.getBlock(), BREAK_TYPE, delay); + blocmodn.setX(blocmodn.getX() - 1); + setBlockLater(blocmodn.getBlock(), BREAK_TYPE, delay); i = i + 1; - } + } }else{ int i = 0; while (i < amp){ blocmodp.setZ(blocmodp.getZ() + 1); - blocmodp.getBlock().setType(BREAK_TYPE); + setBlockLater(blocmodp.getBlock(), BREAK_TYPE, delay); blocmodn.setZ(blocmodn.getZ() - 1); - blocmodn.getBlock().setType(BREAK_TYPE); + setBlockLater(blocmodn.getBlock(), BREAK_TYPE, delay); i = i + 1; } } @@ -662,6 +639,47 @@ private void efectesPales(Player p, PlayerInteractEvent evt, } } + private int countSnowRun(Location start, boolean alongX, int increment) { + Location cursor = start.clone(); + int length = 0; + while (cursor.getBlock().getType() == Material.SNOW_BLOCK) { + length++; + if (alongX) { + cursor.setX(cursor.getX() + increment); + } else { + cursor.setZ(cursor.getZ() + increment); + } + } + return length; + } + + private int easeOutRevealDelay(int step, int lastStep, int durationTicks) { + if (lastStep <= 0 || step <= 0) return 0; + double spatialProgress = Math.min(1D, step / (double) lastStep); + // Invert easeOutCubic: the game knows distance and needs the tick when it is revealed. + double timeProgress = 1D - Math.cbrt(1D - spatialProgress); + return (int) Math.round(durationTicks * timeProgress); + } + private int authoredRevealDelay(int step, int[] timeline) { + return timeline[Math.min(Math.max(step, 0), timeline.length - 1)]; + } + + private void setBlockLater(Block block, Material material, int delay) { + Material expectedMaterial = block.getType(); + BukkitTask task = new BukkitRunnable() { + @Override + public void run() { + if (world != null && block.getWorld() == world && block.getType() == expectedMaterial) { + block.setType(material); + } + } + }.runTaskLater(plugin, delay); + handleTask(task.getTaskId()); + } + + private void breakBlockLater(Block block, int delay, boolean dropItems) { + scheduleTrackedBlockRemoval(block, delay, dropItems); + } } diff --git a/src/main/java/com/biel/lobby/mapes/jocs/TNTRun.java b/src/main/java/com/biel/lobby/mapes/jocs/TNTRun.java index 95cedc1..42fa881 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/TNTRun.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/TNTRun.java @@ -67,7 +67,7 @@ void updateEffects(Boolean hyper){ if (hasTNT(p)){ speed = 4; } - p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 800 * 20, 0, true), true); + p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 800 * 20, 0, true), true); p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 800 * 20, speed, true), true); }else{ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 800 * 20, 20, true), true); @@ -94,11 +94,11 @@ void giveImmunity(final Player ply, int secs){ immunePlayers.add(ply); ply.getInventory().setHelmet(new ItemStack(Material.QUARTZ_BLOCK)); ply.getInventory().setItem(8, new ItemStack(Material.QUARTZ_BLOCK)); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { ply.getInventory().setHelmet(null); ply.getInventory().clear(8); immunePlayers.remove(ply); - }, 20 * 2); + }, 20L * secs); } } void passarTNT(Player de, Player a){ @@ -170,7 +170,7 @@ void endRound(){ int taskId = 0; public void ProgTask(){ - taskId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> { + taskId = scheduleGameplayRepeatingTask(() -> { //time temps = temps - 1; if(Utils.Possibilitat(1)){ @@ -189,7 +189,7 @@ public void hipervelocitat(){ int secs = Utils.NombreEntre(2, 8); updateEffects(true); sendGlobalMessage(ChatColor.AQUA + "HIPERVELOCITAT! (" + Integer.toString(secs) + "s)" ); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> updateEffects(false), 20 * 2); + scheduleGameplayTask(() -> updateEffects(false), 20L * secs); } @Override protected void updateScoreBoard(Player ply) { diff --git a/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatch.java b/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatch.java index eb4e29b..4d51cca 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatch.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatch.java @@ -45,15 +45,16 @@ protected ArrayList getStartingItems(Player ply) { double balancingMultiplier = getBalancingMultiplier(ply); items.add(new ItemStack(Material.STONE_SWORD, 1)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); - //arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); + //arc.addUnsafeEnchantment(Enchantment.INFINITY, 1); items.add(arc); items.add(new ItemStack(Material.CHAINMAIL_HELMET, 1)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_HELMET, e)); items.add(new ItemStack(Material.IRON_BOOTS, 1)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); items.add(new ItemStack(Material.GOLDEN_APPLE, 2)); - items.add(Utils.setItemNameAndLore(new ItemStack(Material.SNOWBALL, (int) Math.round(4 * (balancingMultiplier - 0.2))), "Bomba", "Explota a l'impacte")); + int snowballAmount = Math.max(1, (int) Math.round(4 * (balancingMultiplier - 0.2))); + items.add(Utils.setItemNameAndLore(new ItemStack(Material.SNOWBALL, snowballAmount), "Bomba", "Explota a l'impacte")); items.add(new ItemStack(Material.ARROW, (int) (20 * balancingMultiplier))); return items; } diff --git a/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatchJaneatorForest.java b/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatchJaneatorForest.java index f38538b..1645c1a 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatchJaneatorForest.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/TeamDeathMatchJaneatorForest.java @@ -51,15 +51,16 @@ protected ArrayList getStartingItems(Player ply) { double balancingMultiplier = getBalancingMultiplier(ply); items.add(new ItemStack(Material.STONE_SWORD, 1)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); - //arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); + //arc.addUnsafeEnchantment(Enchantment.INFINITY, 1); items.add(arc); items.add(new ItemStack(Material.CHAINMAIL_HELMET, 1)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_HELMET, e)); items.add(new ItemStack(Material.IRON_BOOTS, 1)); items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); items.add(new ItemStack(Material.GOLDEN_APPLE, 2)); - items.add(Utils.setItemNameAndLore(new ItemStack(Material.SNOWBALL, (int) Math.round(4 * (balancingMultiplier - 0.2))), "Bomba", "Explota a l'impacte")); + int snowballAmount = Math.max(1, (int) Math.round(4 * (balancingMultiplier - 0.2))); + items.add(Utils.setItemNameAndLore(new ItemStack(Material.SNOWBALL, snowballAmount), "Bomba", "Explota a l'impacte")); items.add(new ItemStack(Material.ARROW, (int) (20 * balancingMultiplier))); return items; } diff --git a/src/main/java/com/biel/lobby/mapes/jocs/Torres.java b/src/main/java/com/biel/lobby/mapes/jocs/Torres.java index 56f46f7..aad0bb2 100644 --- a/src/main/java/com/biel/lobby/mapes/jocs/Torres.java +++ b/src/main/java/com/biel/lobby/mapes/jocs/Torres.java @@ -7,6 +7,7 @@ import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Effect; +import org.bukkit.GameRules; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; @@ -66,7 +67,7 @@ protected ArrayList getDesiredTeams() { @Override protected void setCustomGameRules() { // TODO Auto-generated method stub - world.setGameRuleValue("doTileDrops", "false"); + world.setGameRule(GameRules.BLOCK_DROPS, false); } @Override protected void donarEfectesInicials(Player ply) { @@ -74,8 +75,8 @@ protected void donarEfectesInicials(Player ply) { super.donarEfectesInicials(ply); int d = (int) (20 * (5 + Math.sqrt(segonsTranscorreguts()) / 9)); ply.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, 4 * 20 + d, 4, false), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 10, 2, false), true); - ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, d , 50, false), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 20 * 10, 2, false), true); + ply.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, d , 50, false), true); ply.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, d, 5, false), true); } @Override @@ -98,9 +99,9 @@ protected ArrayList getStartingItems(Player ply) { items.add(Utils.createColoredTeamArmor(Material.LEATHER_LEGGINGS, e)); ItemStack arc = new ItemStack(Material.BOW, 1); // A stack of diamonds - arc.addEnchantment(Enchantment.ARROW_KNOCKBACK, 1); - arc.addEnchantment(Enchantment.ARROW_INFINITE, 1); - arc.addUnsafeEnchantment(Enchantment.DURABILITY, 10); + arc.addEnchantment(Enchantment.PUNCH, 1); + arc.addEnchantment(Enchantment.INFINITY, 1); + arc.addUnsafeEnchantment(Enchantment.UNBREAKING, 10); ItemStack itemstack = new ItemStack(Material.ENCHANTED_BOOK, 1); // A stack of diamonds ItemMeta meta = itemstack.getItemMeta(); meta.setDisplayName(ChatColor.BLUE + "Control remot"); @@ -157,7 +158,7 @@ protected void customJocIniciat() { while(eq <= 1){ String eqStr = Integer.toString(eq); - //EnderCrystal cry = (EnderCrystal) world.spawnEntity(pMapaActual().ObtenirLocation("crystal" + eqStr, world).subtract(new Vector(0.5,0,0.5)), EntityType.ENDER_CRYSTAL); + //EnderCrystal cry = (EnderCrystal) world.spawnEntity(pMapaActual().ObtenirLocation("crystal" + eqStr, world).subtract(new Vector(0.5,0,0.5)), EntityType.END_CRYSTAL); //cry.setMetadata("Equip", new FixedMetadataValue(Com.getPlugin(), eq)); int tId = 0; ArrayList obtenirLocations = pMapaActual().ObtenirLocations("torres" + eqStr, world); @@ -249,7 +250,7 @@ protected void onEntityDamageByEntity(EntityDamageByEntityEvent evt, // TODO Auto-generated method stub super.onEntityDamageByEntity(evt, damaged, damager); - if (evt.getEntityType() == EntityType.ENDER_CRYSTAL){ + if (evt.getEntityType() == EntityType.END_CRYSTAL){ final EnderCrystal cry = (EnderCrystal) evt.getEntity(); int preequip = 0; @@ -313,22 +314,22 @@ protected void onEntityDamageByEntity(EntityDamageByEntityEvent evt, } } world.playSound(cry.getLocation(), Sound.AMBIENT_CAVE, 30F, 3F); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { for(Player p : plugin.getServer().getOnlinePlayers()){ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5 * 20, 1, false), true); } }, 1 * 20); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { for(Player p : plugin.getServer().getOnlinePlayers()){ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 4 * 20, 3, false), true); } }, 25); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { for(Player p : plugin.getServer().getOnlinePlayers()){ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 3 * 20, 6, false), true); } }, 30); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { for(Player p : plugin.getServer().getOnlinePlayers()){ if(obtenirEquip(p).getId() == equip){ p.sendMessage(ChatColor.BOLD + "" + ChatColor.RED + "Has perdut!"); @@ -378,7 +379,7 @@ protected void onPlayerInteract(PlayerInteractEvent evt, Player p) { int shoots = 5; int temps = 5; while (i1 < shoots){ - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + scheduleGameplayTask(() -> { int i = -3; while (i <= 3){ float angle = plyr.getLocation().getYaw() + (7 * i) + 90; @@ -482,7 +483,7 @@ protected void onPlayerDeath(PlayerDeathEvent evt, Player killed) { public ItemStack getTurretItem() { ItemStack arc = new ItemStack(Material.ARROW, 1); // A stack of diamonds - arc.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + arc.addUnsafeEnchantment(Enchantment.INFINITY, 1); ItemMeta meta = arc.getItemMeta(); meta.setDisplayName(ChatColor.YELLOW + "Torre de defensa"); arc.setItemMeta(meta); @@ -493,7 +494,7 @@ protected void onEntityDamage(EntityDamageEvent evt, Entity e) { // TODO Auto-generated method stub super.onEntityDamage(evt, e); - if (evt.getEntityType() == EntityType.ENDER_CRYSTAL){ + if (evt.getEntityType() == EntityType.END_CRYSTAL){ //if (evt.getCause() != DamageCause.ENTITY_ATTACK){ evt.setCancelled(true); //} @@ -525,7 +526,7 @@ protected void onPlayerFish(PlayerFishEvent evt, Player p) { player.teleport(loc2); caught.teleport(loc1); - ecaught.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 5, 2)); + ecaught.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, 20 * 5, 2)); world.playEffect(ecaught.getEyeLocation(), Effect.POTION_BREAK, 0); } }else{ @@ -540,16 +541,16 @@ protected void onEntityExplode(EntityExplodeEvent evt, Entity e) { // TODO Auto-generated method stub super.onEntityExplode(evt, e); - if (evt.getEntityType() == EntityType.ENDER_CRYSTAL){ + if (evt.getEntityType() == EntityType.END_CRYSTAL){ EnderCrystal cry = (EnderCrystal) evt.getEntity(); evt.setYield(0F); JocFinalitzat(); } - if (evt.getEntityType() == EntityType.PRIMED_TNT){ + if (evt.getEntityType() == EntityType.TNT){ for (Iterator iterator = evt.blockList().iterator(); iterator.hasNext();) { Block b = iterator.next(); Material t = b.getType(); - if(t == Material.GRASS || t == Material.DIRT || t == Material.GRAVEL)iterator.remove(); + if(t == Material.SHORT_GRASS || t == Material.DIRT || t == Material.GRAVEL)iterator.remove(); } getPlayers().stream().filter(p -> p.getLocation().distance(e.getLocation()) < 12).forEach(p -> {p.damage(10); p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1 * 20, 1));}); } @@ -613,7 +614,7 @@ public void Initialize(){ void setEffect(Player plyr){ switch(tipus){ case DAMAGE: - plyr.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 34 * 20, 0, false), true); + plyr.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 34 * 20, 0, false), true); //Bukkit.broadcastMessage(plyr.getName() + " té més dany!"); break; case HEAL: @@ -626,14 +627,14 @@ void setEffect(Player plyr){ break; case PROTECTION: if (força == 3){ - plyr.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 70 * 20, 3, false), true); + plyr.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 70 * 20, 3, false), true); }else{ - plyr.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 38 * 20, 1, false), true); + plyr.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 38 * 20, 1, false), true); } break; case JUMP: - plyr.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20 * 6, 4, false), true); + plyr.addPotionEffect(new PotionEffect(PotionEffectType.JUMP_BOOST, 20 * 6, 4, false), true); break; default: break; @@ -660,7 +661,7 @@ public void onDespawn(ItemDespawnEvent evt) { } } void replaceItem(){ - Com.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), () -> { + scheduleGameplayTask(() -> { ItemStack item = new ItemStack(getItem()); Item dropitem = world.dropItem(loc.clone().add(new Vector(0.5,1.1,0.5)), item); dropitem.setVelocity(new Vector(0,0,0)); @@ -679,12 +680,12 @@ Material getItem(){ if (força == 3){ return(Material.DIAMOND_CHESTPLATE); } - return(Material.LEGACY_GOLD_CHESTPLATE); + return(Material.GOLDEN_CHESTPLATE); case JUMP: if (força >= 3){ - return(Material.LEGACY_IRON_PLATE); + return(Material.HEAVY_WEIGHTED_PRESSURE_PLATE); } - return(Material.LEGACY_WOOD_PLATE); + return(Material.OAK_PRESSURE_PLATE); default: return(Material.COBBLESTONE); diff --git a/src/main/java/com/biel/lobby/utilities/CBUtils.java b/src/main/java/com/biel/lobby/utilities/CBUtils.java index 1c3f466..29cc8d0 100644 --- a/src/main/java/com/biel/lobby/utilities/CBUtils.java +++ b/src/main/java/com/biel/lobby/utilities/CBUtils.java @@ -1,14 +1,11 @@ package com.biel.lobby.utilities; -import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer; import org.bukkit.entity.Player; public class CBUtils { - // CraftBukkit needed // public static int getPing(Player player) { - return ((CraftPlayer) player).getHandle().ping; + return player.getPing(); } } - diff --git a/src/main/java/com/biel/lobby/utilities/Cuboid.java b/src/main/java/com/biel/lobby/utilities/Cuboid.java index 61f33f5..a881e3f 100644 --- a/src/main/java/com/biel/lobby/utilities/Cuboid.java +++ b/src/main/java/com/biel/lobby/utilities/Cuboid.java @@ -9,6 +9,7 @@ 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.configuration.serialization.ConfigurationSerializable; @@ -435,32 +436,32 @@ public Cuboid contract(CuboidDirection dir) { Cuboid face = getFace(dir.opposite()); switch (dir) { case Down: - while (face.containsOnly(0) && face.getLowerY() > this.getLowerY()) { + while (face.containsOnlyAir() && face.getLowerY() > this.getLowerY()) { face = face.shift(CuboidDirection.Down, 1); } return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, face.getUpperY(), this.z2); case Up: - while (face.containsOnly(0) && face.getUpperY() < this.getUpperY()) { + while (face.containsOnlyAir() && face.getUpperY() < this.getUpperY()) { face = face.shift(CuboidDirection.Up, 1); } return new Cuboid(this.worldName, this.x1, face.getLowerY(), this.z1, this.x2, this.y2, this.z2); case North: - while (face.containsOnly(0) && face.getLowerX() > this.getLowerX()) { + while (face.containsOnlyAir() && face.getLowerX() > this.getLowerX()) { face = face.shift(CuboidDirection.North, 1); } return new Cuboid(this.worldName, this.x1, this.y1, this.z1, face.getUpperX(), this.y2, this.z2); case South: - while (face.containsOnly(0) && face.getUpperX() < this.getUpperX()) { + while (face.containsOnlyAir() && face.getUpperX() < this.getUpperX()) { face = face.shift(CuboidDirection.South, 1); } return new Cuboid(this.worldName, face.getLowerX(), this.y1, this.z1, this.x2, this.y2, this.z2); case East: - while (face.containsOnly(0) && face.getLowerZ() > this.getLowerZ()) { + while (face.containsOnlyAir() && face.getLowerZ() > this.getLowerZ()) { face = face.shift(CuboidDirection.East, 1); } return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, face.getUpperZ()); case West: - while (face.containsOnly(0) && face.getUpperZ() < this.getUpperZ()) { + while (face.containsOnlyAir() && face.getUpperZ() < this.getUpperZ()) { face = face.shift(CuboidDirection.West, 1); } return new Cuboid(this.worldName, this.x1, this.y1, face.getLowerZ(), this.x2, this.y2, this.z2); @@ -497,12 +498,24 @@ public Cuboid getFace(CuboidDirection dir) { /** * Check if the Cuboid contains only blocks of the given type * - * @param blockId - The block ID to check for + * @param material - The block material to check for * @return true if this Cuboid contains only blocks of the given type */ - public boolean containsOnly(int blockId) { + public boolean containsOnly(Material material) { for (Block b : this) { - if (b.getType().getId() != blockId) return false; + if (b.getType() != material) return false; + } + return true; + } + + /** + * Check if the Cuboid contains only air blocks, including cave and void air. + * + * @return true if every block in this Cuboid is air + */ + public boolean containsOnlyAir() { + for (Block b : this) { + if (!b.getType().isAir()) return false; } return true; } @@ -655,4 +668,4 @@ public CuboidDirection opposite() { } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/utilities/FireworkEffectPlayer.java b/src/main/java/com/biel/lobby/utilities/FireworkEffectPlayer.java index 1fd99b9..4380aa2 100644 --- a/src/main/java/com/biel/lobby/utilities/FireworkEffectPlayer.java +++ b/src/main/java/com/biel/lobby/utilities/FireworkEffectPlayer.java @@ -1,7 +1,5 @@ package com.biel.lobby.utilities; -import java.lang.reflect.Method; - import org.bukkit.FireworkEffect; import org.bukkit.entity.Firework; import org.bukkit.inventory.meta.FireworkMeta; @@ -36,12 +34,6 @@ public class FireworkEffectPlayer { * * } */ - - // internal references, performance improvements - private Method world_getHandle = null; - private Method nms_world_broadcastEntityEffect = null; - private Method firework_getHandle = null; - /** * Play a pretty firework at the location with the FireworkEffect when called * @param world @@ -49,63 +41,14 @@ public class FireworkEffectPlayer { * @param fe * @throws Exception */ - public void playFirework(World world, Location loc, FireworkEffect fe) throws Exception { - // Bukkity load (CraftFirework) + public void playFirework(World world, Location loc, FireworkEffect fe) { Firework fw = world.spawn(loc, Firework.class); - // the net.minecraft.server.World - Object nms_world = null; - Object nms_firework = null; - /* - * The reflection part, this gives us access to funky ways of messing around with things - */ - if(world_getHandle == null) { - // get the methods of the craftbukkit objects - world_getHandle = getMethod(world.getClass(), "getHandle"); - firework_getHandle = getMethod(fw.getClass(), "getHandle"); - } - // invoke with no arguments - nms_world = world_getHandle.invoke(world, (Object[]) null); - nms_firework = firework_getHandle.invoke(fw, (Object[]) null); - // null checks are fast, so having this seperate is ok - if(nms_world_broadcastEntityEffect == null) { - // get the method of the nms_world - nms_world_broadcastEntityEffect = getMethod(nms_world.getClass(), "broadcastEntityEffect"); - } - /* - * Now we mess with the metadata, allowing nice clean spawning of a pretty firework (look, pretty lights!) - */ - // metadata load FireworkMeta data = fw.getFireworkMeta(); - // clear existing data.clearEffects(); - // power of one data.setPower(1); - // add the effect data.addEffect(fe); - // set the meta fw.setFireworkMeta(data); - /* - * Finally, we broadcast the entity effect then kill our fireworks object - */ - // invoke with arguments - nms_world_broadcastEntityEffect.invoke(nms_world, nms_firework, (byte) 17); - // remove from the game - fw.remove(); - } - - /** - * Internal method, used as shorthand to grab our method in a nice friendly manner - * @param cl - * @param method - * @return Method (or null) - */ - private static Method getMethod(Class cl, String method) { - for(Method m : cl.getMethods()) { - if(m.getName().equals(method)) { - return m; - } - } - return null; + fw.detonate(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/biel/lobby/utilities/GestorPropietats.java b/src/main/java/com/biel/lobby/utilities/GestorPropietats.java index e72022c..abf119e 100644 --- a/src/main/java/com/biel/lobby/utilities/GestorPropietats.java +++ b/src/main/java/com/biel/lobby/utilities/GestorPropietats.java @@ -5,6 +5,8 @@ import org.bukkit.*; +import com.biel.lobby.Com; + public class GestorPropietats { String Ruta = ""; public GestorPropietats(String RutaArxiuPropietats){ @@ -30,7 +32,7 @@ private ArrayList LlegirArxiuPropietats(){ //Close the input stream in.close(); }catch (Exception e){//Catch exception if any - System.err.println("Error: " + e.getMessage()); + Com.getPlugin().getLogger().log(java.util.logging.Level.WARNING, "Error reading properties", e); } return Arr; } @@ -194,7 +196,7 @@ public void EstablirCuboid(String Nom, Location loc1, Location loc2){ } public Cuboid ObtenirCuboid(String Nom, World world){ ArrayList locs = ObtenirLocations(Nom, world); - if (locs.size() != 2){System.out.println("Cuboid mal definit: " + Nom + ", " + Integer.toString(locs.size()) + " location(s)"); return null;} + if (locs.size() != 2){Com.getPlugin().getLogger().warning("Cuboid mal definit: " + Nom + ", " + Integer.toString(locs.size()) + " location(s)"); return null;} return new Cuboid(locs.get(0), locs.get(1)); } } diff --git a/src/main/java/com/biel/lobby/utilities/HologramFacade.java b/src/main/java/com/biel/lobby/utilities/HologramFacade.java new file mode 100644 index 0000000..308671d --- /dev/null +++ b/src/main/java/com/biel/lobby/utilities/HologramFacade.java @@ -0,0 +1,65 @@ +package com.biel.lobby.utilities; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import eu.decentsoftware.holograms.api.DHAPI; +import eu.decentsoftware.holograms.api.holograms.Hologram; + +public final class HologramFacade { + private static final String NAME_PREFIX = "minicat-"; + private static final Set ACTIVE_HANDLES = new HashSet<>(); + + private HologramFacade() { + } + + public static Handle create(Location location) { + String name = NAME_PREFIX + UUID.randomUUID(); + Hologram hologram = DHAPI.createHologram(name, location, false, List.of()); + Handle handle = new Handle(hologram); + ACTIVE_HANDLES.add(handle); + return handle; + } + + public static void deleteAll() { + for (Handle handle : List.copyOf(ACTIVE_HANDLES)) { + handle.delete(); + } + } + + public static final class Handle { + private final Hologram hologram; + + private Handle(Hologram hologram) { + this.hologram = hologram; + } + + public void clearLines() { + DHAPI.setHologramLines(hologram, List.of()); + } + + public void appendTextLine(String text) { + DHAPI.addHologramLine(hologram, text); + } + + public void setLines(String... lines) { + DHAPI.setHologramLines(hologram, Arrays.asList(lines)); + } + + public void showOnlyTo(Player player) { + hologram.setDefaultVisibleState(false); + hologram.setShowPlayer(player); + } + + public void delete() { + hologram.delete(); + ACTIVE_HANDLES.remove(this); + } + } +} diff --git a/src/main/java/com/biel/lobby/utilities/Options.java b/src/main/java/com/biel/lobby/utilities/Options.java index a34f986..bc98c70 100644 --- a/src/main/java/com/biel/lobby/utilities/Options.java +++ b/src/main/java/com/biel/lobby/utilities/Options.java @@ -26,7 +26,7 @@ public static void giveStartingButtons(final Player ply){ PlayerInventory inventory = ply.getInventory(); inventory.clear(); ItemStack dBlk = new ItemStack(Material.DIAMOND_BLOCK); - dBlk.addUnsafeEnchantment(Enchantment.LOOT_BONUS_BLOCKS, 10); + dBlk.addUnsafeEnchantment(Enchantment.FORTUNE, 10); ItemButton button = new ItemButton(Utils.setItemNameAndLore(dBlk, ChatColor.AQUA + "Teletransportador", ChatColor.WHITE + "Obre l'inventari de teletransport."), ply, event -> lobby.getPlugin().gest.ObrirMenuMapes(Bukkit.getPlayer(ply.getName()))); inventory.setItem(1, button.getItemStack()); ItemButton button3 = new ItemButton(Utils.setItemNameAndLore(new ItemStack(Material.GOLD_INGOT), ChatColor.GOLD + "Ranking " + ChatColor.YELLOW + "(" + "#" + playerData.getRank() + ")", ChatColor.WHITE + "Mostra el rànquing de jugadors.", ChatColor.DARK_AQUA + "Elo: " + ChatColor.WHITE + Math.round(playerData.getElo()) + ChatColor.YELLOW + " #" + playerData.getRank()), ply, event -> Com.displayRanking(event.getPlayer())); diff --git a/src/main/java/com/biel/lobby/utilities/PaperMessages.java b/src/main/java/com/biel/lobby/utilities/PaperMessages.java new file mode 100644 index 0000000..6ba2316 --- /dev/null +++ b/src/main/java/com/biel/lobby/utilities/PaperMessages.java @@ -0,0 +1,48 @@ +package com.biel.lobby.utilities; + +import java.time.Duration; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.kyori.adventure.title.Title; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.biel.lobby.Com; + +public final class PaperMessages { + private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection(); + private static final Duration TICK = Duration.ofMillis(50); + + private PaperMessages() { + } + + public static Component legacy(String text) { + return LEGACY.deserialize(text == null ? "" : text); + } + + public static void sendActionBar(Player player, String message, long durationTicks) { + Component component = legacy(message); + for (long delay = 0; delay < durationTicks; delay += 40) { + Bukkit.getScheduler().runTaskLater(Com.getPlugin(), () -> { + if (player.isOnline()) { + player.sendActionBar(component); + } + }, delay); + } + Bukkit.getScheduler().runTaskLater(Com.getPlugin(), () -> { + if (player.isOnline()) { + player.sendActionBar(Component.empty()); + } + }, durationTicks); + } + + public static void showTitle(Player player, int fadeInTicks, int stayTicks, int fadeOutTicks, + String title, String subtitle) { + player.showTitle(Title.title( + legacy(title), + legacy(subtitle), + Title.Times.times(TICK.multipliedBy(fadeInTicks), TICK.multipliedBy(stayTicks), + TICK.multipliedBy(fadeOutTicks)))); + } +} diff --git a/src/main/java/com/biel/lobby/utilities/PlayerTagState.java b/src/main/java/com/biel/lobby/utilities/PlayerTagState.java new file mode 100644 index 0000000..8cf1d4a --- /dev/null +++ b/src/main/java/com/biel/lobby/utilities/PlayerTagState.java @@ -0,0 +1,138 @@ +package com.biel.lobby.utilities; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +public final class PlayerTagState { + private static final Map TAGS = new ConcurrentHashMap<>(); + private static final TagStyle DEFAULT_STYLE = new TagStyle("", ""); + + private PlayerTagState() { + } + + public static void setPrefix(Player player, String prefix) { + update(player, style(player).withPrefix(normalizeLegacyColors(prefix))); + } + + public static void setSuffix(Player player, String suffix) { + update(player, style(player).withSuffix(normalizeLegacyColors(suffix))); + } + + public static String getPrefix(Player player) { + return style(player).prefix(); + } + + public static void remove(Player player) { + TAGS.remove(player.getUniqueId()); + for (Player viewer : Bukkit.getOnlinePlayers()) { + Scoreboard scoreboard = viewer.getScoreboard(); + Team team = scoreboard.getEntryTeam(player.getName()); + if (team != null && isPersonalTeam(team)) { + team.removeEntry(player.getName()); + } + cleanUpPersonalTeam(scoreboard, player); + } + } + + public static void assignScoreboard(Player viewer, Scoreboard scoreboard) { + applyAll(scoreboard); + viewer.setScoreboard(scoreboard); + } + + public static void applyAll(Scoreboard scoreboard) { + for (Player target : Bukkit.getOnlinePlayers()) { + apply(scoreboard, target); + } + } + + private static void update(Player player, TagStyle style) { + TAGS.put(player.getUniqueId(), style); + for (Player viewer : Bukkit.getOnlinePlayers()) { + apply(viewer.getScoreboard(), player); + } + } + + private static void apply(Scoreboard scoreboard, Player player) { + Team currentTeam = scoreboard.getEntryTeam(player.getName()); + if (currentTeam != null && !isPersonalTeam(currentTeam)) { + // Gameplay and system teams own their membership and shared styling. + cleanUpPersonalTeam(scoreboard, player); + return; + } + + Team team = currentTeam != null ? currentTeam : getOrCreatePersonalTeam(scoreboard, player); + if (currentTeam == null) { + team.addEntry(player.getName()); + } + applyStyle(team, style(player)); + } + + private static boolean isPersonalTeam(Team team) { + return team.getName().startsWith("mt_"); + } + + private static String personalTeamName(Player player) { + return "mt_" + player.getUniqueId().toString().replace("-", "").substring(0, 12); + } + + private static Team getOrCreatePersonalTeam(Scoreboard scoreboard, Player player) { + String teamName = personalTeamName(player); + Team team = scoreboard.getTeam(teamName); + return team != null ? team : scoreboard.registerNewTeam(teamName); + } + + private static void cleanUpPersonalTeam(Scoreboard scoreboard, Player player) { + Team personalTeam = scoreboard.getTeam(personalTeamName(player)); + if (personalTeam != null && personalTeam.getEntries().isEmpty()) { + personalTeam.unregister(); + } + } + + private static void applyStyle(Team team, TagStyle style) { + team.prefix(PaperMessages.legacy(style.prefix())); + team.suffix(PaperMessages.legacy(style.suffix())); + ChatColor color = lastColor(style.prefix()); + team.setColor(color != null ? color : ChatColor.RESET); + } + + private static ChatColor lastColor(String text) { + String colors = ChatColor.getLastColors(text); + for (int index = colors.length() - 1; index >= 0; index--) { + ChatColor color = ChatColor.getByChar(colors.charAt(index)); + if (color != null && color.isColor()) { + return color; + } + } + return null; + } + + private static String normalizeLegacyColors(String text) { + return ChatColor.translateAlternateColorCodes('&', text == null ? "" : text); + } + + private static TagStyle style(Player player) { + return TAGS.getOrDefault(player.getUniqueId(), DEFAULT_STYLE); + } + + private record TagStyle(String prefix, String suffix) { + private TagStyle { + prefix = prefix == null ? "" : prefix; + suffix = suffix == null ? "" : suffix; + } + + private TagStyle withPrefix(String newPrefix) { + return new TagStyle(newPrefix, suffix); + } + + private TagStyle withSuffix(String newSuffix) { + return new TagStyle(prefix, newSuffix); + } + } +} diff --git a/src/main/java/com/biel/lobby/utilities/ScoreBoardUpdater.java b/src/main/java/com/biel/lobby/utilities/ScoreBoardUpdater.java index 8f964d8..9eac287 100644 --- a/src/main/java/com/biel/lobby/utilities/ScoreBoardUpdater.java +++ b/src/main/java/com/biel/lobby/utilities/ScoreBoardUpdater.java @@ -3,8 +3,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Locale; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; +import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; @@ -66,21 +69,28 @@ static public void updateTeamScore(JocEquips j){ ScoreboardManager manager = Bukkit.getScoreboardManager(); Scoreboard board = manager.getNewScoreboard(); for (Equip e : j.Equips){ - Team Ghosts = board.registerNewTeam(e.getAdjectiu()); + Team gameplayTeam = board.registerNewTeam(e.getAdjectiu()); + gameplayTeam.setCanSeeFriendlyInvisibles(true); + gameplayTeam.setAllowFriendlyFire(false); + gameplayTeam.color(namedColor(e.getChatColor())); for(Player p : e.getPlayers()){ - p.setScoreboard(board); - Ghosts.addPlayer(p); + gameplayTeam.addEntry(p.getName()); Com.setHeadColor(p, ColorConverter.chatToRaw(e.getChatColor())); } - Ghosts.setCanSeeFriendlyInvisibles(true); - Ghosts.setAllowFriendlyFire(false); - //Ghosts.setPrefix(e.getChatColor() + ""); - //Ghosts.setPrefix(e.getChatColor() + "[" + e.getAdjectiu() +"]"); - - } + } + for (Equip e : j.Equips) { + for (Player player : e.getPlayers()) { + PlayerTagState.assignScoreboard(player, board); + } + } } + + private static NamedTextColor namedColor(ChatColor color) { + NamedTextColor namedColor = NamedTextColor.NAMES.value(color.name().toLowerCase(Locale.ROOT)); + return namedColor != null ? namedColor : NamedTextColor.WHITE; + } @Deprecated static public void updateSpectatorScore(ArrayList ply){ ScoreboardManager manager = Bukkit.getScoreboardManager(); @@ -88,9 +98,9 @@ static public void updateSpectatorScore(ArrayList ply){ Team Ghosts = board.registerNewTeam("Ghost"); Ghosts.setCanSeeFriendlyInvisibles(true); Ghosts.setAllowFriendlyFire(false); - for(Player p : ply){ - p.setScoreboard(board); - } + for(Player p : ply){ + PlayerTagState.assignScoreboard(p, board); + } } static public void setScore(Objective objective, String name, int value){ Score score = objective.getScore(Bukkit.getOfflinePlayer(name)); //Get a fake offline player @@ -127,11 +137,11 @@ static public void setScoreBoard(Player ply, String title, ArrayList ite setScore(objective, item, value); } - ply.setScoreboard(board); + PlayerTagState.assignScoreboard(ply, board); } static public void clearScoreBoard(Player ply){ ScoreboardManager mng = Bukkit.getScoreboardManager(); - ply.setScoreboard(mng.getNewScoreboard()); + PlayerTagState.assignScoreboard(ply, mng.getNewScoreboard()); } } diff --git a/src/main/java/com/biel/lobby/utilities/Turret.java b/src/main/java/com/biel/lobby/utilities/Turret.java index cff1d63..0f0c8ad 100644 --- a/src/main/java/com/biel/lobby/utilities/Turret.java +++ b/src/main/java/com/biel/lobby/utilities/Turret.java @@ -7,6 +7,7 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.PistonMoveReaction; import org.bukkit.block.Sign; +import org.bukkit.block.data.Directional; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; @@ -24,7 +25,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.potion.Potion; import org.bukkit.potion.PotionType; import org.bukkit.util.BlockIterator; import org.bukkit.util.Vector; @@ -175,7 +175,7 @@ public Boolean canBuild(){ if (loc.getBlock().getType() != Material.AIR){ return false; } - if(loc.getBlock().getRelative(BlockFace.DOWN).getType() == Material.LEGACY_LEAVES){ + if(Tag.LEAVES.isTagged(loc.getBlock().getRelative(BlockFace.DOWN).getType())){ return false; } } @@ -192,10 +192,10 @@ public void Build(){ loc.getBlock().setType(mat); TurretBlocks.add(loc.clone()); loc.setY(loc.getY() + 1); - loc.getBlock().setType(Material.LEGACY_NETHER_FENCE); + loc.getBlock().setType(Material.NETHER_BRICK_FENCE); TurretBlocks.add(loc.clone()); loc.setY(loc.getY() + 1); - loc.getBlock().setType(Material.LEGACY_REDSTONE_TORCH_ON); + loc.getBlock().setType(Material.REDSTONE_TORCH); TurretBlocks.add(loc.clone()); resetArmorCD(); built = true; @@ -283,11 +283,6 @@ public void BuildArmor(int height){ ArmorBlocks.clear(); while (h >= 0){ Location iLoc = location.clone().add(new Vector(0,h,0)); - ArrayList dirs = new ArrayList<>(); - dirs.add((byte) 0x2); - dirs.add((byte) 0x3); - dirs.add((byte) 0x4); - dirs.add((byte) 0x5); ArrayList faces = new ArrayList<>(); faces.add(BlockFace.NORTH); faces.add(BlockFace.SOUTH); @@ -299,7 +294,10 @@ public void BuildArmor(int height){ if (block.getType() != Material.AIR && block.getPistonMoveReaction() != PistonMoveReaction.BREAK){ continue; } - block.setType(Material.LEGACY_WALL_SIGN); + block.setType(Material.OAK_WALL_SIGN, false); + Directional signData = (Directional) block.getBlockData(); + signData.setFacing(face); + block.setBlockData(signData, false); Sign sign = (Sign)block.getState(); if (creador != null){ sign.setLine(1,creador.getName()); @@ -309,8 +307,6 @@ public void BuildArmor(int height){ } sign.update(); -// TODO UPDATE -// block.setData(dirs.get(faces.indexOf(face))); ArmorBlocks.add(block.getLocation()); } h = h - 1; @@ -339,7 +335,7 @@ public void setArmorCD(int CD){ //Bukkit.broadcastMessage("CD i!"); plugin.getServer().getScheduler().cancelTask(taskEscutId); if (CD < 0){return;} - taskEscutId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + taskEscutId = joc.scheduleGameplayTask(() -> { //Bukkit.broadcastMessage("CD acabat!"); hpEscut = maxHpEscut; @@ -389,7 +385,7 @@ public void PotionAttack(int id, int power, int delayOffSet){ while (count <= range){ Block block = iLoc.getBlock().getRelative(face); Location loc = block.getLocation().clone(); - tirarPoció(loc, PotionType.INSTANT_DAMAGE, (3 * count) + 1 + delayOffSet); + tirarPoció(loc, PotionType.HARMING, (3 * count) + 1 + delayOffSet); iLoc = loc; count++; } @@ -429,13 +425,12 @@ public void PotionAttack(int id, int power, int delayOffSet){ dir.add(addUp); ThrownPotion potion = (ThrownPotion)world.spawnEntity(spawnpoint.add(dir.multiply(0.65)), EntityType.SPLASH_POTION); potion.setVelocity(dir); - Potion pot = new Potion(type).splash(); - ItemStack stack1 = pot.toItemStack(1); + ItemStack stack1 = Utils.createPotion(type, 1, true); potion.setItem(stack1); potion.setShooter(creador); } public void tirarPoció(final Location loc, final PotionType type, int delay){ - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> tirarPoció(loc, type), delay); + joc.scheduleGameplayTask(() -> tirarPoció(loc, type), delay); } public void checkIntegrity(){ if(built && canBuild()){ @@ -446,7 +441,7 @@ public void Attack(){ //if (headless = false){ if (built == false){return;} //} - taskId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable(){ + taskId = joc.scheduleGameplayRepeatingTask(new Runnable(){ public void run() { checkIntegrity(); LivingEntity target = getTarget(); @@ -472,14 +467,11 @@ public void run() { Vector addUp = new Vector(0, rawDir.length() / 40.0,0); dir.add(addUp); Arrow arrow = (Arrow)world.spawnEntity(spawnpoint, EntityType.ARROW); - //TNTPrimed arrow = (TNTPrimed)world.spawnEntity(spawnpoint, EntityType.PRIMED_TNT); + //TNTPrimed arrow = (TNTPrimed)world.spawnEntity(spawnpoint, EntityType.TNT); arrow.setShooter(creador); if (foc == true){arrow.setFireTicks(20); world.playEffect(spawnpoint, Effect.MOBSPAWNER_FLAMES, 0);} arrow.setMetadata("Tower", new FixedMetadataValue(plugin, id)); arrow.setMetadata("Special", new FixedMetadataValue(plugin, false)); - arrow.setBounce(false); - arrow.setKnockbackStrength(0); - arrow.setVelocity(dir.multiply(3.4)); world.playSound(spawnpoint, Sound.ENTITY_IRON_GOLEM_ATTACK, 1, 0.3F); @@ -537,7 +529,7 @@ void AtacEspecial(){ int shoots = 1 + getByTipus(TipusMillora.MECÀNICA).lvl; int temps = 5; while (i1 < shoots){ - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + joc.scheduleGameplayTask(() -> { int i = 0; int espai = 32 - (getByTipus(TipusMillora.MECÀNICA).lvl * 4); while (i <= 360){ @@ -685,7 +677,6 @@ protected void onProjectileHit(ProjectileHitEvent evt, Projectile proj) { hit = false; } } - arrow.setBounce(hit); if (hit) { Hit(10); player.playSound(player.getEyeLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1F, 0.9F); @@ -889,12 +880,12 @@ public Millora(TipusMillora millora) { break; case QUÍMICA: name = "Química"; Description = "Habilitats amb pocions"; - material = Material.LEGACY_BREWING_STAND_ITEM; + material = Material.BREWING_STAND; Cost = 50; break; case MECÀNICA: name = "Mecànica avançada"; Description = "Habilitats especials cada 10 tirs"; - material = Material.LEGACY_PISTON_BASE; + material = Material.PISTON; Cost = 100; max = 5; break; @@ -1013,6 +1004,3 @@ ItemStack toItemStack(){ } } - - - diff --git a/src/main/java/com/biel/lobby/utilities/Utils.java b/src/main/java/com/biel/lobby/utilities/Utils.java index fb7a18c..0d007b6 100644 --- a/src/main/java/com/biel/lobby/utilities/Utils.java +++ b/src/main/java/com/biel/lobby/utilities/Utils.java @@ -12,6 +12,7 @@ import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.Tag; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -29,9 +30,9 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.metadata.Metadatable; -import org.bukkit.potion.Potion; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionType; +import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.util.BlockIterator; import org.bukkit.util.BlockVector; import org.bukkit.util.Vector; @@ -44,8 +45,14 @@ public Utils() { // TODO Auto-generated constructor stub } public static ItemStack setItemNameAndLore(ItemStack item, String name, String... lore) { + if (item == null) { + throw new IllegalArgumentException("Item stack must not be null"); + } ItemMeta im = item.getItemMeta(); - if (!name.isEmpty()){im.setDisplayName(name);} + if (im == null) { + throw new IllegalArgumentException("Material " + item.getType() + " does not support item metadata"); + } + if (name != null && !name.isEmpty()){im.setDisplayName(name);} im.setLore(Arrays.asList(lore)); item.setItemMeta(im); return item; @@ -250,16 +257,6 @@ public static ArrayList getInventoryPercent(Inventory inv, float perc } return list; } - public static void BreakBlockLater(final Block block, int delay, final boolean give){ - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Com.getPlugin(), () -> { - if (give){ - block.breakNaturally(); - }else{ - block.setType(Material.AIR); - } - - }, delay); - } public static GestorPropietats getpMapaFromWorld(World world){ return new GestorPropietats(world.getWorldFolder().getAbsolutePath() + "/" + "pMapaActual.txt"); } @@ -284,7 +281,7 @@ public static ArrayList getAdjacentFaces(Block b, ArrayList faces = new ArrayList<>(); for (BlockFace f : fToCheck){ Block bl = b.getRelative(f); - if (bl.getType() == Material.LEGACY_LOG){faces.add(f);} + if (Tag.LOGS.isTagged(bl.getType())){faces.add(f);} } return faces; } @@ -531,14 +528,18 @@ public static T getRandomListItem(List a){ return a.get(0); } public static ItemStack getRandomPotion(){ - Potion p = new Potion(getRandomPotionType()); - if (Utils.Possibilitat(55)){p.setSplash(true);} - //p.setLevel(1); - return p.toItemStack(1); + return createPotion(getRandomPotionType(), 1, Utils.Possibilitat(55)); + } + public static ItemStack createPotion(PotionType type, int amount, boolean splash){ + ItemStack potion = new ItemStack(splash ? Material.SPLASH_POTION : Material.POTION, amount); + PotionMeta meta = (PotionMeta) potion.getItemMeta(); + meta.setBasePotionType(type); + potion.setItemMeta(meta); + return potion; } public static ArrayList getBrewingItems(){ ArrayList i = new ArrayList<>(); - i.add(new ItemStack(Material.LEGACY_NETHER_WARTS)); + i.add(new ItemStack(Material.NETHER_WART)); i.add(new ItemStack(Material.GLOWSTONE)); i.add(new ItemStack(Material.REDSTONE)); i.add(new ItemStack(Material.SPIDER_EYE)); @@ -553,7 +554,7 @@ ArrayList freadHumanReadableList(String text){ int lastIndex = 0; ArrayList parts = new ArrayList<>(); while(parts.size() < 3){ - System.out.println(lastIndex); + Com.getPlugin().getLogger().fine("Readable-list index: " + lastIndex); if (lastIndex > text.length()){ lastIndex = text.length() - 1; } @@ -565,8 +566,8 @@ ArrayList freadHumanReadableList(String text){ if (endIndex == -1){ endIndex = text.length(); } - System.out.println("Begin: " + beginIndex); - System.out.println("End: " + endIndex); + Com.getPlugin().getLogger().fine("Readable-list begin: " + beginIndex); + Com.getPlugin().getLogger().fine("Readable-list end: " + endIndex); parts.add(text.substring(beginIndex, endIndex)); lastIndex = endIndex; diff --git a/src/main/java/com/biel/lobby/utilities/data/DataAPI.java b/src/main/java/com/biel/lobby/utilities/data/DataAPI.java index 00a61b2..8d7e663 100644 --- a/src/main/java/com/biel/lobby/utilities/data/DataAPI.java +++ b/src/main/java/com/biel/lobby/utilities/data/DataAPI.java @@ -3,17 +3,17 @@ import java.sql.*; import java.util.ArrayList; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.bukkit.entity.Player; import com.biel.BielAPI.Utils.Pair; -import com.mysql.jdbc.Statement; - - public class DataAPI { boolean datalessMode = false; Logger logger = Logger.getLogger("DataAPI"); + private final Set emittedDatalessWarnings = ConcurrentHashMap.newKeySet(); public DataAPI() { } @@ -21,6 +21,11 @@ public DataAPI() { public boolean isInDatalessMode() { return datalessMode; } + private void warnDatalessOnce(String operation, String message) { + if (emittedDatalessWarnings.add(operation)) { + logger.warning(message); + } + } public Connection connection; void openConnection() { @@ -31,11 +36,10 @@ void openConnection() { String password = "minicat"; try { connection = DriverManager.getConnection("jdbc:mysql://" + host - + ":" + port + "/" + db + "?autoReconnect=true&useSSL=false", user, password); + + ":" + port + "/" + db + "?connectTimeout=2000&socketTimeout=3000&useSSL=false", user, password); } catch (Exception e) { - e.printStackTrace(); datalessMode = true; - logger.warning("Could not connect to database, switching to off-server datalessMode mode."); + logger.warning("Could not connect to database; switching to dataless mode: " + e.getMessage()); } } public void repairConnection(){ @@ -67,7 +71,7 @@ public void registerNewPlayer(Player player) { } public int getPlayerId(String player) { if(datalessMode){ - logger.warning("Tried to translate player name to id in dataless mode"); + warnDatalessOnce("player-id", "Player IDs are unavailable in dataless mode; returning the fallback ID."); return -1; } try { @@ -231,10 +235,11 @@ public ArrayList getRanking() { ArrayList r = new ArrayList<>(); if(datalessMode){ - logger.warning("Tried to get ranking in dataless mode."); + warnDatalessOnce("ranking", "Rankings are unavailable in dataless mode; returning an empty ranking."); return r; } repairConnection(); + if(datalessMode || connection == null)return r; try { //TODO PreparedStatement sql = connection.prepareStatement("SELECT `player_id` FROM `players` WHERE TIMESTAMPDIFF(DAY, players.last_played, NOW()) < 15 ORDER BY `elo` DESC;"); ResultSet result = sql.executeQuery(); @@ -283,7 +288,7 @@ public int getGameId(String name) { public ArrayList> getAutoRating() { ArrayList> r = new ArrayList<>(); if(datalessMode){ - logger.warning("Tried to access automatic rating while in dataless mode."); + warnDatalessOnce("automatic-rating", "Automatic game ratings are unavailable in dataless mode; using the configured order."); return r; } try { diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/Skill.java b/src/main/java/com/biel/lobby/utilities/events/skills/Skill.java index b8c90a6..02e1c72 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/Skill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/Skill.java @@ -4,7 +4,6 @@ import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -191,9 +190,8 @@ private static int getCharsForDescLine() { return 32; } protected ItemStack getItemStack(){ - ItemStack i = Utils.setItemNameAndLore(new ItemStack(getMaterial(), 1, getDamageValue(), getData()), getTierChatColor() + getName(), getLoreArr()); - //ItemStack i = new ItemStack(getMaterial()); - i.addUnsafeEnchantment(Enchantment.DEPTH_STRIDER, getTier()); + ItemStack i = Utils.setItemNameAndLore(new ItemStack(getMaterial()), getTierChatColor() + getName(), getLoreArr()); + i.editMeta(meta -> meta.setEnchantmentGlintOverride(true)); return i;//"[Line1]", "[Line2]", "Info{Current/Max}"); } //-END-OLD- diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/SkillPool.java b/src/main/java/com/biel/lobby/utilities/events/skills/SkillPool.java index bcf7acb..ce6d762 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/SkillPool.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/SkillPool.java @@ -14,6 +14,7 @@ import com.biel.BielAPI.Utils.IconMenu; import com.biel.BielAPI.Utils.ItemButton; +import com.biel.lobby.Com; import com.biel.lobby.utilities.Utils; public class SkillPool { @@ -70,7 +71,7 @@ public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(clickable); //select skill int pos = event.getPosition(); - System.out.println("--Clicat--"); + Com.getPlugin().getLogger().fine("Skill selection clicked"); if(clickable){ Skill s = registered.get(pos); Skill reflectedS; @@ -89,8 +90,7 @@ public void onOptionClick(IconMenu.OptionClickEvent event) { } } catch (Exception e) { // TODO Auto-generated catch block - System.out.println("--Error reflexió / removing habilitat--"); - e.printStackTrace(); + Com.getPlugin().getLogger().log(java.util.logging.Level.SEVERE, "Error creating or assigning a selected skill", e); } } } @@ -134,7 +134,7 @@ public int getUnlockerID(ItemStack s){ } public ItemButton getUnlockerButton(Player p, int n){ ItemStack dBlk = new ItemStack(Material.CHEST); - dBlk.addUnsafeEnchantment(Enchantment.LOOT_BONUS_BLOCKS, 1); + dBlk.addUnsafeEnchantment(Enchantment.FORTUNE, 1); ItemButton button = new ItemButton(Utils.setItemNameAndLore(dBlk, ChatColor.AQUA + "Habilitat #" + n, ChatColor.WHITE + "Obre l'inventari de selecció d'habilitats", Integer.toString(n)), p, event -> { int data = (int) event.getData(); openSelectionMenu(event.getPlayer(), true, data); diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/ItemAttatchedModeSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/ItemAttatchedModeSkill.java index f835fce..c15a64d 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/ItemAttatchedModeSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/ItemAttatchedModeSkill.java @@ -13,6 +13,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; +import com.biel.lobby.Com; import com.biel.lobby.mapes.Joc.PlayerInfo; import com.biel.lobby.utilities.events.statuseffects.StatusEffect; @@ -172,9 +173,9 @@ private ItemAttatchedModeSkillTrayEffect getTrayEffectInstance(){ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { // TODO Auto-generated catch block - e.printStackTrace(); + Com.getPlugin().getLogger().log(java.util.logging.Level.SEVERE, "Could not create the skill tray effect", e); } - System.out.println("Null TrayEffectInstance"); + Com.getPlugin().getLogger().warning("Skill tray effect instance is null"); return null; } public class ItemAttatchedModeSkillTrayEffect extends StatusEffect{ diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/BerserkSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/BerserkSkill.java index a164574..feae181 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/BerserkSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/BerserkSkill.java @@ -26,7 +26,7 @@ public double getCDSeconds() { @Override public Material getMaterial() { // TODO Auto-generated method stub - return Material.LEGACY_GOLD_AXE; + return Material.GOLDEN_AXE; } @Override public String getName() { diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/CreeperSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/CreeperSkill.java index 117406e..24f022d 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/CreeperSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/CreeperSkill.java @@ -31,7 +31,7 @@ public double getCDSeconds() { @Override public Material getMaterial() { // TODO Auto-generated method stub - return Material.LEGACY_SKULL_ITEM; + return Material.CREEPER_HEAD; } @Override public Byte getData() { diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/FrostArcherSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/FrostArcherSkill.java index 584640d..869b612 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/FrostArcherSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/FrostArcherSkill.java @@ -112,14 +112,14 @@ public void empresonar(Player damaged, Player damager) { continue; } block.setType(Material.ICE); - Utils.BreakBlockLater(block, (int) (20 * getModifier()), false); + getGame().scheduleTrackedBlockRemoval(block, (int) (20 * getModifier()), false); } damaged.teleport(damaged.getLocation().getBlock().getLocation().add(new Vector(0.5,0,0.5))); Block gblock = damaged.getLocation().add(0, 2, 0).getBlock(); if (gblock.getType() == Material.AIR){ gblock.setType(Material.GOLD_BLOCK); - Utils.BreakBlockLater(gblock, (int) (20 * getModifier()), false); + getGame().scheduleTrackedBlockRemoval(gblock, (int) (20 * getModifier()), false); } damaged.playSound(damager.getLocation(), Sound.ENTITY_PLAYER_BURP, 1, 0.5F); //Remove aura diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/GravityBendingSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/GravityBendingSkill.java index f1901a4..2c66155 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/GravityBendingSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/GravityBendingSkill.java @@ -31,7 +31,7 @@ public double getCDSeconds() { @Override public Material getMaterial() { // TODO Auto-generated method stub - return Material.LEGACY_GOLD_BOOTS; + return Material.GOLDEN_BOOTS; } @Override public String getName() { diff --git a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/MagicArcherSkill.java b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/MagicArcherSkill.java index 8b1fa0c..8c41c9b 100644 --- a/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/MagicArcherSkill.java +++ b/src/main/java/com/biel/lobby/utilities/events/skills/types/specificskills/MagicArcherSkill.java @@ -4,12 +4,10 @@ import java.util.function.Consumer; import java.util.function.Predicate; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; -import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer; import org.bukkit.FireworkEffect.Builder; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -26,6 +24,7 @@ import com.biel.BielAPI.Utils.ColorConverter; import com.biel.BielAPI.Utils.GUtils; import com.biel.lobby.Com; +import com.biel.lobby.mapes.Joc; import com.biel.lobby.utilities.events.skills.types.ItemAttatchedStackModeSkill; import com.biel.lobby.utilities.events.statuseffects.LifeDrainStatusEffect; @@ -164,7 +163,7 @@ protected void onEntityShootBow(EntityShootBowEvent evt, Entity e, ItemStack bow float power) { // TODO Auto-generated method stub super.onEntityShootBow(evt, e, bow, proj, power); - System.out.println("Shootbow: " + e.getName() + ", " + getPlayer().getName()); + Com.getPlugin().getLogger().fine("Magic Archer bow shot: " + e.getName() + ", " + getPlayer().getName()); if(e.getName().equalsIgnoreCase(getPlayer().getName())){ if(isMaxed()){ //Shoot with effect @@ -228,7 +227,10 @@ protected void onProjectileHit(ProjectileHitEvent evt, Projectile proj) { flyingEffect = false; } }; - Bukkit.getScheduler().runTaskLater(Com.getPlugin(), runnable, 2); + Joc game = getGame(); + if (game != null) { + game.scheduleGameplayTask(runnable, 2); + } } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index e773099..1f36482 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -3,14 +3,19 @@ main: com.biel.lobby.lobby description: Main plugin for the minicat (1.0) server. depend: - BielAPI +- DecentHolograms loadBefore: - AuthMe -version: 1.3 -api-version: 1.16 +version: 1.4-dev +api-version: '26.2' +libraries: +- commons-io:commons-io:2.21.0 +- commons-lang:commons-lang:2.6 +- com.mysql:mysql-connector-j:9.6.0 commands: prova: - description: Prova. - usage: /r [Mapa] El mapa es pot indicar pel seu ID o pel seu nom + description: Crea, llista o elimina instàncies de diagnòstic operatiu. + usage: /prova [variant] | /prova llista | /prova elimina mapes: description: Mostra una llista dels mapes. usage: /mapes @@ -20,6 +25,9 @@ commands: m: description: Mostra l'inventari del teletransportador. usage: /m + minicatjoin: + description: Entra en una instància registrada des d'una invitació. + usage: /minicatjoin a: description: Mostra totes les partides en curs. usage: /a @@ -49,4 +57,4 @@ commands: usage: /ranking prog: description: Progres estimat de la partida (ETA). - usage: /prog \ No newline at end of file + usage: /prog