diff --git a/Challenge/src/main/java/de/fanta/challenge/Challenge.java b/Challenge/src/main/java/de/fanta/challenge/Challenge.java index 7cf0bc7..ebb3d72 100644 --- a/Challenge/src/main/java/de/fanta/challenge/Challenge.java +++ b/Challenge/src/main/java/de/fanta/challenge/Challenge.java @@ -3,6 +3,7 @@ import com.destroystokyo.paper.profile.PlayerProfile; import de.cubeside.nmsutils.NMSUtils; import de.fanta.challenge.challenges.AllItemsChallenge; +import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEventMonth; import de.fanta.challenge.challenges.MLGChallenge; import de.fanta.challenge.challenges.RandomDropsChallenge; import de.fanta.challenge.commands.CommandRegistration; @@ -13,9 +14,7 @@ import de.fanta.challenge.events.TimerChangedEvent; import de.fanta.challenge.guis.BackpackGui; import de.fanta.challenge.listeners.EventRegistration; -import de.fanta.challenge.scoreboard.BukkitScoreBoardManager; -import de.fanta.challenge.scoreboard.ScoreBoardMananger; -import de.fanta.challenge.scoreboard.ScoreManager; +import de.fanta.challenge.score.ScoreManager; import de.fanta.challenge.utils.ComponentUtil; import de.fanta.challenge.utils.ColorUtils; import de.fanta.challenge.utils.Config; @@ -57,6 +56,7 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.Random; import java.util.ResourceBundle; import java.util.UUID; @@ -87,7 +87,6 @@ private Timer timer; private VanishUtils vanish; private BackpackGui backpack; - private ScoreBoardMananger sbManager; private ScoreManager scoreManager; private Player currentEditor; @@ -184,12 +183,12 @@ new EventRegistration(this).registerEvents(); this.backpack.loadInventoryFromConfig(); - this.sbManager = new BukkitScoreBoardManager(this); this.componentUtil = new ComponentUtil(); resetwithseed = Config.getBoolean("resetwithseed"); + boolean worldReset = Config.getBoolean("World_Reset"); - if (Config.getBoolean("World_Reset") && (serverType == ServerType.CHALLENGE || serverType == ServerType.CHALLENGE_EVENT)) { + if (worldReset && (serverType == ServerType.CHALLENGE || serverType == ServerType.CHALLENGE_EVENT)) { if (!Config.getBoolean("firsttimerstart")) { timer.setTime(0); } @@ -208,6 +207,12 @@ timer.setTime(getConfig().getInt("timertime")); } + Timer.TimerMode timerMode = Timer.TimerMode.valueOf(getConfig().getString("timermode", "UP")); + if (timerMode == Timer.TimerMode.DATE) { + timer.setTargetDateTimestamp(getConfig().getLong("timerdate", 0)); + timer.setMode(timerMode); + } + waypointMananger = new WaypointManager(this); if (plugin.getServerType() == ServerType.ADVENTURE) { @@ -241,7 +246,9 @@ } getConfig().set("showtimer", false); } else { - getConfig().set("showtimer", true); + if (worldReset) { + getConfig().set("showtimer", true); + } } for (String string : getItemConfig().getStringList("items")) { @@ -295,16 +302,24 @@ plugin.setDayLightCircle(false); MLGChallenge.checkMLGWorld(); setPvP(Config.getBoolean("pvp")); - if (plugin.getServerType() != ServerType.ADVENTURE) { - plugin.getSBManager().initScoreboard(); - } }, 1L); plugin.getServer().getScheduler().runTaskLater(this, () -> { EventRegistration.pM.callEvent(new ServerStatusChangedEvent(true)); EventRegistration.pM.callEvent(new TimerChangedEvent(timer.isRunning())); EventRegistration.pM.callEvent(new PlayerCountChangedEvent(Bukkit.getOnlinePlayers().size() - plugin.getVanish().countVanishPlayers())); + + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + DeathrunChallengeEventMonth.load(Bukkit.getWorld("world")); + timer.startTimer(); + } }, 1L); + + plugin.getServer().getScheduler().runTaskLater(this, () -> { + if (Config.getBoolean("event.enabled")) { + Bukkit.getPluginManager().callEvent(new EventStatusChangedEvent(true)); + } + }, 100L); getLogger().info("Plugin loaded!"); } @@ -326,7 +341,6 @@ } Config.setValue("timertime", timer.getTime()); if (getConfig().getBoolean("event.enabled")) { - Config.setValue("event.enabled", false); Bukkit.getPluginManager().callEvent(new EventStatusChangedEvent(false)); Bukkit.getPluginManager().callEvent(new ChallengeEventStatusChangedEvent(false)); getScoreManager().saveScores(null); @@ -448,10 +462,6 @@ } } - public ScoreBoardMananger getSBManager() { - return this.sbManager; - } - public Player getCurrentEditor() { return currentEditor; } diff --git a/Challenge/src/main/java/de/fanta/challenge/Timer.java b/Challenge/src/main/java/de/fanta/challenge/Timer.java index 9c7e4e7..6768ffb 100644 --- a/Challenge/src/main/java/de/fanta/challenge/Timer.java +++ b/Challenge/src/main/java/de/fanta/challenge/Timer.java @@ -18,7 +18,12 @@ import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.Optional; +import java.util.TimeZone; +import java.util.logging.Level; public class Timer { @@ -28,6 +33,7 @@ private long time; // milliseconds private TimerMode mode; private long countingSinceTimestamp; + private Long targetDateTimestamp = null; private static final int[] baseColorsTimer = new int[]{0xFF6668, 0xFFB566, 0xFFED66, 0x66FF75, 0x66B8FF, 0xE666FF}; private static final int[] baseColorsReserveTimer = new int[]{0x7FD4E0, 0x947DFF, 0xFF88F1, 0xFF7D7D}; @@ -48,42 +54,64 @@ idleActionBarTaskId = null; } actionBarTaskId = plugin.getServer().getScheduler().runTaskTimer(plugin, () -> { - if (mode == TimerMode.DOWN) { - if (time <= 0) { - if (Config.getBoolean("event.enabled")) { - for (Player p : Bukkit.getOnlinePlayers()) { - p.setGameMode(GameMode.SPECTATOR); - } - plugin.getComponentUtil().sendTitleToAll(Component.text("Event"), Component.text("Die Zeit ist abgelaufen!", Color.GREEN)); + switch (mode) { + case DOWN -> { + if (time <= 0) { + handleTimerEnd(); } else { - for (Player p : Bukkit.getOnlinePlayers()) { - p.setGameMode(GameMode.SPECTATOR); - } - plugin.getComponentUtil().sendTitleToAll(Component.text("ZEIT ABGELAUFEN!", Color.RED), Component.text("Challenge fehlgeschlagen", Color.RED)); - - plugin.getComponentUtil().sendBrodCastMessage(Component.text("Die Zeit ist abgelaufen und die Challenge somit fehlgeschlagen!", Color.RED)); - Optional optionalWorld = Bukkit.getWorlds().stream().findFirst(); - optionalWorld.ifPresent(world -> plugin.getComponentUtil().sendBrodCastMessage(Component.text("Seed: ", Color.GREEN).append(Component.text(world.getSeed(), Color.BLUE)))); - + updateDownTimer(); } - stopTimer(); - } else { - time -= (System.currentTimeMillis() - countingSinceTimestamp); - countingSinceTimestamp = System.currentTimeMillis(); - sendTimerActionBar(); } - } else { - time += (System.currentTimeMillis() - countingSinceTimestamp); - countingSinceTimestamp = System.currentTimeMillis(); - sendTimerActionBar(); + case UP -> updateUpTimer(); + case DATE -> updateDateTimer(); } }, 1L, 1L); + if (!Config.getBoolean("firsttimerstart")) { Config.setValue("firsttimerstart", true, false); } Bukkit.getPluginManager().callEvent(new TimerChangedEvent(true)); } + private void handleTimerEnd() { + if (Config.getBoolean("event.enabled")) { + for (Player p : Bukkit.getOnlinePlayers()) { + p.setGameMode(GameMode.SPECTATOR); + } + plugin.getComponentUtil().sendTitleToAll(Component.text("Event"), Component.text("Die Zeit ist abgelaufen!", Color.GREEN)); + } else { + for (Player p : Bukkit.getOnlinePlayers()) { + p.setGameMode(GameMode.SPECTATOR); + } + plugin.getComponentUtil().sendTitleToAll(Component.text("ZEIT ABGELAUFEN!", Color.RED), Component.text("Challenge fehlgeschlagen", Color.RED)); + plugin.getComponentUtil().sendBrodCastMessage(Component.text("Die Zeit ist abgelaufen und die Challenge somit fehlgeschlagen!", Color.RED)); + Optional optionalWorld = Bukkit.getWorlds().stream().findFirst(); + optionalWorld.ifPresent(world -> plugin.getComponentUtil().sendBrodCastMessage(Component.text("Seed: ", Color.GREEN).append(Component.text(world.getSeed(), Color.BLUE)))); + } + stopTimer(); + } + + private void updateDownTimer() { + time -= (System.currentTimeMillis() - countingSinceTimestamp); + countingSinceTimestamp = System.currentTimeMillis(); + sendTimerActionBar(); + } + + private void updateUpTimer() { + time += (System.currentTimeMillis() - countingSinceTimestamp); + countingSinceTimestamp = System.currentTimeMillis(); + sendTimerActionBar(); + } + + private void updateDateTimer() { + time = targetDateTimestamp - System.currentTimeMillis(); + if (time <= 0) { + handleTimerEnd(); + } else { + sendTimerActionBar(); + } + } + public void stopTimer() { if (actionBarTaskId != null) { actionBarTaskId.cancel(); @@ -179,26 +207,57 @@ this.countingSinceTimestamp = System.currentTimeMillis(); } - public void addTime(int seconds) { - this.time = Math.max(time + (seconds * 1000L), 0); - this.countingSinceTimestamp = System.currentTimeMillis(); - Config.setValue("editsettings", true); + public boolean setDate(String targetDate) { + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); + try { + Date date = sdf.parse(targetDate); + this.targetDateTimestamp = date.getTime(); + this.time = targetDateTimestamp - System.currentTimeMillis(); + this.mode = TimerMode.DATE; + return true; + } catch (ParseException e) { + plugin.getLogger().log(Level.SEVERE, "Error while parsing Date", e); + } + return false; + } + public void addTime(int seconds) { + if (mode != TimerMode.DATE) { + this.time = Math.max(time + (seconds * 1000L), 0); + this.countingSinceTimestamp = System.currentTimeMillis(); + Config.setValue("editsettings", true); + } } public void removeTime(int seconds) { - this.time = Math.max(time - (seconds * 1000L), 0); - this.countingSinceTimestamp = System.currentTimeMillis(); - Config.setValue("editsettings", true); + if (mode != TimerMode.DATE) { + this.time = Math.max(time - (seconds * 1000L), 0); + this.countingSinceTimestamp = System.currentTimeMillis(); + Config.setValue("editsettings", true); + } } public TimerMode getMode() { return mode; } - public enum TimerMode { - UP, - DOWN + public void setMode(TimerMode mode) { + this.mode = mode; } + public Long getTargetDateTimestamp() { + return targetDateTimestamp; + } + + public void setTargetDateTimestamp(Long targetDateTimestamp) { + this.targetDateTimestamp = targetDateTimestamp; + this.time = this.targetDateTimestamp - System.currentTimeMillis(); + } + + public enum TimerMode { + UP, + DOWN, + DATE + } } \ No newline at end of file diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BingoChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BingoChallengeEvent.java index 6b58f85..90dd4b4 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BingoChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BingoChallengeEvent.java @@ -3,7 +3,7 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; import de.fanta.challenge.guis.eventgui.BingoItemsGui; -import de.fanta.challenge.scoreboard.ChallengePlayer; +import de.fanta.challenge.score.ChallengePlayer; import de.fanta.challenge.teams.ChallengeTeam; import de.fanta.challenge.teams.TeamUtils; import de.fanta.challenge.utils.ChatSkullAPI.ChatSkull; diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BridgeRaceChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BridgeRaceChallengeEvent.java index 95d9145..f4e677a 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BridgeRaceChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/BridgeRaceChallengeEvent.java @@ -2,9 +2,9 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.Scorable; -import de.fanta.challenge.scoreboard.ScoreManager; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; +import de.fanta.challenge.score.ScoreManager; import de.fanta.challenge.utils.ChatSkullAPI.ChatSkull; import de.fanta.challenge.utils.Config; import de.fanta.challengeutils.Color; diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEvent.java index 20e470f..b85f6a2 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEvent.java @@ -2,13 +2,14 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.Scorable; -import de.fanta.challenge.scoreboard.ScoreManager; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; +import de.fanta.challenge.score.ScoreManager; import de.fanta.challenge.utils.ChatSkullAPI.ChatSkull; import de.fanta.challenge.utils.Config; import de.fanta.challenge.utils.CoordsTargeter; import de.fanta.challengeutils.Color; +import de.iani.cubesideutils.primitivewrapper.VariableInteger; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.Style; @@ -143,8 +144,13 @@ if (Objects.equals(Config.getString("event.type"), "deathrun") && plugin.getTimer().isRunning()) { deadPlayer.add(p.getUniqueId()); CoordsTargeter.removeLocation(e.getPlayer().getUniqueId()); - plugin.getSBManager().removeScoreboard(p); - if (plugin.getSBManager().countScoreboardPlayers() == 0) { + VariableInteger isPlayerAlive = new VariableInteger(0); + plugin.getVanish().getPlayerListWithoutVanishPlayers().forEach(player -> { + if (!deadPlayer.contains(player.getUniqueId())) { + isPlayerAlive.set(1); + } + }); + if (isPlayerAlive.intValue() == 0) { plugin.getTimer().stopTimer(); plugin.getComponentUtil().sendBrodCastMessage(Component.text("Das Event wurde beendet, da alle Spieler gestorben sind!", Color.GREEN)); } @@ -259,7 +265,7 @@ public void onPlayerJoin(PlayerJoinEvent e) { if (Objects.equals(Config.getString("event.type"), "deathrun")) { if (deadPlayer.contains(e.getPlayer().getUniqueId())) { - plugin.getSBManager().setScoreboardtoPlayer(e.getPlayer()); + //TODO Scorebord plugin.getSBManager().setScoreboardtoPlayer(e.getPlayer()); } } } diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEventMonth.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEventMonth.java new file mode 100644 index 0000000..c82a470 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DeathrunChallengeEventMonth.java @@ -0,0 +1,667 @@ +package de.fanta.challenge.challenges.ChallengeEvents; + +import de.fanta.challenge.Challenge; +import de.fanta.challenge.events.TimerChangedEvent; +import de.fanta.challenge.scoreboard.ChallengePlayerScoreboard; +import de.fanta.challenge.scoreboard.ChallengeScoreboard; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; +import de.fanta.challenge.score.ScoreManager; +import de.fanta.challenge.utils.Config; +import de.fanta.challenge.utils.CoordsTargeter; +import de.fanta.challenge.utils.CustomFontUtil; +import de.fanta.challenge.utils.MinecraftTextUtils; +import de.fanta.challenge.utils.Statistics; +import de.fanta.challengeutils.Color; +import de.iani.cubesideutils.bukkit.items.ItemGroups; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.Style; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Boat; +import org.bukkit.entity.ChestBoat; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityMountEvent; +import org.bukkit.event.entity.EntityPlaceEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerResourcePackStatusEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.vehicle.VehicleDamageEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class DeathrunChallengeEventMonth implements Listener { + + private static final Challenge plugin = Challenge.getPlugin(); + + private final Map bossBarMap = new HashMap<>(); + + private static Location spawnLocation; + private final Map> currentBarrier = new HashMap<>(); + private static final Material barrierBlock = Material.GLASS; + + private static final NamespacedKey UUIDKey = new NamespacedKey(Challenge.getPlugin(), "uuid_deathrun"); + + private static final Random random = new Random(); + private static World world; + private static final String TexturePackUrl = "https://fantacs.de/i/file/deathrun.zip"; + private final Collection loadingTexturePackPlayer = new ArrayList<>(); + + private static final ConcurrentHashMap currentScore = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap currentBestRunScore = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap deathScore = new ConcurrentHashMap<>(); + + private static ChallengeScoreboard challengeScoreboard; + private static final HashMap positionColors = new HashMap<>(); + + @EventHandler + public void onTimerChange(TimerChangedEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + if (e.isRunning()) { + plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + for (Player pp : Bukkit.getOnlinePlayers()) { + plugin.getScoreManager().join(new ChallengePlayer(pp.getUniqueId())); + Location spawn = world.getSpawnLocation(); + spawn.setYaw(-90f); + pp.teleportAsync(spawn); + } + }, 1L); + startStatsUpdateTask(); + startBossBarUpdateTask(); + startRollbackTask(); + } + } + } + + @EventHandler + public void onMove(PlayerMoveEvent e) { + Player p = e.getPlayer(); + World world = p.getWorld(); + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && plugin.getTimer().isRunning() && !plugin.getVanish().isVanish(p) && p.getGameMode() != GameMode.SPECTATOR) { + + if (loadingTexturePackPlayer.contains(p.getUniqueId())) { + e.setCancelled(true); + return; + } + + Location playerLoc = p.getLocation(); + double posRelatedToCenter = playerLoc.getZ() - spawnLocation.getZ(); + double distanceToCenter = Math.abs(posRelatedToCenter); + + List barrierLocations = currentBarrier.computeIfAbsent(p.getUniqueId(), uuid -> new ArrayList<>()); + + int BARRIER_POS = 150; + int BARRIER_SIZE = 6; + if (distanceToCenter >= BARRIER_POS) { //Outside border + plugin.getComponentUtil().sendTitleToPlayer(p, Component.text("⟲ ⟲ ⟲ ⟲", Style.style(Color.RED, TextDecoration.BOLD)), Component.text("Kehre zurück auf die Strecke!", Color.RED), 0, 20, 0, true); + resetBarrier(p, world, barrierLocations); + CoordsTargeter.addLocation(p.getUniqueId(), new Location(p.getWorld(), p.getLocation().getX(), p.getLocation().getY(), spawnLocation.getZ())); + if (p.getVehicle() instanceof Boat boat) { + boat.remove(); + boat.getWorld().dropItemNaturally(boat.getLocation(), new ItemStack(boat.getBoatType().getMaterial(), 3)); + boat.getWorld().dropItemNaturally(boat.getLocation(), new ItemStack(Material.STICK, 2)); + if (boat instanceof ChestBoat) { + boat.getWorld().dropItemNaturally(boat.getLocation(), new ItemStack(Material.CHEST, 1)); + } + } + if (distanceToCenter >= BARRIER_POS + 3) { + p.damage(0.5); + } + } else if (distanceToCenter >= BARRIER_POS - 8) { //Inside border + //Send barrier + double barrierZ = spawnLocation.getZ() + BARRIER_POS * (posRelatedToCenter > 0 ? 1 : -1); + Location loc = new Location(p.getWorld(), playerLoc.getX() - BARRIER_SIZE / 2d, playerLoc.getY() - BARRIER_SIZE / 2d, barrierZ); + + resetBarrier(p, world, barrierLocations); + + if (CoordsTargeter.containsLocation(p.getUniqueId())) { + CoordsTargeter.removeLocation(p.getUniqueId()); + } + for (int y = 0; y < BARRIER_SIZE; y++) { + for (int x = 0; x < BARRIER_SIZE; x++) { + Location blockLoc = loc.clone().add(x, y, 0); + if (!world.getBlockAt(blockLoc).isSolid()) { + p.sendBlockChange(blockLoc, Bukkit.createBlockData(barrierBlock)); + barrierLocations.add(blockLoc); + } + } + } + } else if (!barrierLocations.isEmpty()) { //Away from border + resetBarrier(p, world, barrierLocations); + } + + if (playerLoc.getY() > world.getMaxHeight() - 1) { + p.damage(1); + } + } + } + + @EventHandler + public void onDamage(EntityDamageEvent e) { + if (e.getEntity() instanceof Player p) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && plugin.getTimer().isRunning()) { + if (loadingTexturePackPlayer.contains(p.getUniqueId())) { + e.setCancelled(true); + } + + if (e.getCause() == EntityDamageEvent.DamageCause.CRAMMING) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onDeath(PlayerDeathEvent e) { + Player p = e.getEntity(); + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && plugin.getTimer().isRunning()) { + e.getDrops().clear(); + e.setShouldDropExperience(false); + CoordsTargeter.removeLocation(p.getUniqueId()); + currentScore.remove(p.getUniqueId()); + plugin.getStatistics().resetDeathrunCurrentStats(p.getUniqueId()); + + plugin.getStatistics().increaseDeathrunDeathStats(p.getUniqueId()); + int localDeathScore = deathScore.getOrDefault(p.getUniqueId(), 0); + localDeathScore++; + deathScore.put(p.getUniqueId(), localDeathScore); + } + } + + @EventHandler + public void onPlayerRespawn(PlayerRespawnEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + Location spawnlocation = world.getSpawnLocation().clone(); + spawnlocation.setYaw(-90f); + e.setRespawnLocation(spawnlocation); + } + } + + @EventHandler + public void onPortalUse(PlayerPortalEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + e.setCancelled(true); + } + } + + @EventHandler + public void onBarrierBreak(BlockBreakEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + Block block = e.getBlock(); + Location loc = block.getLocation(); + int x = loc.getBlockX(); + int z = loc.getBlockZ(); + int spawnX = spawnLocation.getBlockX(); + int spawnZ = spawnLocation.getBlockZ(); + + int distanceX = spawnX - x; + + if (distanceX > -15 && (Math.abs(distanceX) >= 15 || Math.abs(spawnZ - z) >= 150)) { + plugin.getComponentUtil().sendWarningMessage(e.getPlayer(), "Niemand hat die Absicht, eine Mauer zu errichten!"); + e.setCancelled(true); + } + } + } + + @EventHandler + public void onBoatMount(EntityMountEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + if (e.getMount() instanceof Boat boat && e.getEntity() instanceof Player player) { + PersistentDataContainer container = boat.getPersistentDataContainer(); + if (container.get(UUIDKey, PersistentDataType.STRING) != null && !container.get(UUIDKey, PersistentDataType.STRING).equals(player.getUniqueId().toString())) { + plugin.getComponentUtil().sendWarningMessage(player, "Du kannst nur in deine eigenen Boote einsteigen."); + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onVehiclePlace(EntityPlaceEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + if (e.getEntity() instanceof Boat boat) { + if (e.getPlayer() != null) { + PersistentDataContainer container = boat.getPersistentDataContainer(); + container.set(UUIDKey, PersistentDataType.STRING, e.getPlayer().getUniqueId().toString()); + } + } + } + } + + @EventHandler + public void onBoatBreak(VehicleDamageEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + if (e.getVehicle() instanceof Boat boat && e.getAttacker() instanceof Player player) { + PersistentDataContainer container = boat.getPersistentDataContainer(); + if (container.get(UUIDKey, PersistentDataType.STRING) != null && !container.get(UUIDKey, PersistentDataType.STRING).equals(player.getUniqueId().toString())) { + plugin.getComponentUtil().sendWarningMessage(player, "Du kannst nur deine eignen Boote zerstören."); + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + challengeScoreboard.addPlayer(e.getPlayer()); + e.getPlayer().setResourcePack(TexturePackUrl, "", true); + loadingTexturePackPlayer.add(e.getPlayer().getUniqueId()); + + ScoreManager scoreManager = plugin.getScoreManager(); + ChallengePlayer cp = new ChallengePlayer(e.getPlayer().getUniqueId()); + scoreManager.join(cp); + scoreManager.updateScore(cp, 0); + + Block block = e.getPlayer().getEyeLocation().getBlock(); + if (block.isSolid()) { + BlockBreakEvent blockBreakEvent = new BlockBreakEvent(block, e.getPlayer()); + blockBreakEvent.callEvent(); + block.setType(Material.AIR); + } + } + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + CoordsTargeter.removeLocation(e.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onPlantBreak(BlockBreakEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && plugin.getTimer().isRunning()) { + if (e.getBlock().getType() != Material.SHORT_GRASS) { + return; + } + if (random.nextInt(10) == 0) { + e.getBlock().getWorld().dropItem(e.getBlock().getLocation(), new ItemStack(Material.MELON_SLICE)); + } + } + } + + @EventHandler + public void onResourcePackLoad(PlayerResourcePackStatusEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && e.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { + loadingTexturePackPlayer.remove(e.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onEntityTarget(EntityTargetEvent e) { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + if (e.getTarget() instanceof Player player) { + if (loadingTexturePackPlayer.contains(player.getUniqueId())) { + e.setCancelled(true); + } + } + + } + } + + public static void load(World playerWold) { + world = playerWold; + + + positionColors.put(1, TextColor.fromHexString("#09FF00")); + positionColors.put(2, TextColor.fromHexString("#61FF5C")); + positionColors.put(3, TextColor.fromHexString("#93FF8F")); + + challengeScoreboard = new ChallengeScoreboard(); + challengeScoreboard.setSidebarTitle(CustomFontUtil.deathRunLogo); + + Statistics statistics = plugin.getStatistics(); + statistics.setAllTotaleScores(); + statistics.setAllCurrentRunScores(); + statistics.setAllBestRunScores(); + statistics.setAllDeathScores(); + + spawnLocation = world.getSpawnLocation(); + + int height = world.getMaxHeight() - world.getMinHeight(); + int width = 300; + + Location loc = spawnLocation.clone().subtract(15, 0, 150); + loc.setY(world.getMinHeight()); + for (int y = 0; y < height; y++) { + for (int z = 0; z < width; z++) { + Block block = loc.clone().add(0, y, z).getBlock(); + if (!block.isSolid()) { + block.setType(getRandomGlass()); + } + } + } + mexico(150, world); + mexico(-150, world); + + plugin.getServer().getOnlinePlayers().forEach(player1 -> { + player1.setResourcePack(TexturePackUrl, "", true); + challengeScoreboard.addPlayer(player1); + + ScoreManager scoreManager = plugin.getScoreManager(); + ChallengePlayer cp = new ChallengePlayer(player1.getUniqueId()); + scoreManager.join(cp); + scoreManager.updateScore(cp, 0); + }); + } + + private void resetBarrier(Player p, World world, List locations) { + for (Location location : locations) { + p.sendBlockChange(location, world.getBlockAt(location).getBlockData()); + } + locations.clear(); + } + + private static void mexico(int startPos, World world) { + int height = world.getMaxHeight() - world.getMinHeight(); + int width = 30; + Location loc = spawnLocation.clone().add(-15, 0, startPos); + loc.setY(world.getMinHeight()); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Block block = loc.clone().add(x, y, 0).getBlock(); + if (!block.isSolid()) { + block.setType(getRandomGlass()); + } + } + } + } + + private static Material getRandomGlass() { + int randomIndex = random.nextInt(ItemGroups.STAINED_GLASS.size()); + return new ArrayList<>(ItemGroups.STAINED_GLASS).get(randomIndex); + + } + + private void startStatsUpdateTask() { + plugin.getServer().getScheduler().runTaskTimer(plugin, this::updateScore, 1L, 20L); + } + + private void startBossBarUpdateTask() { + plugin.getServer().getScheduler().runTaskTimer(plugin, this::updateBossBar, 1L, 1L); + } + + private void startRollbackTask() { + plugin.getServer().getScheduler().runTaskTimer(plugin, () -> { + rollBackBlocks(); + rollBackEntities(); + }, 20 * 60L, 20 * 60L); + } + + private void updateScore() { + plugin.getVanish().getPlayerListWithoutVanishPlayers().forEach(player -> { + if (player.isDead()) { + return; + } + ChallengePlayer cp = new ChallengePlayer(player.getUniqueId()); + UUID playerUUID = player.getUniqueId(); + int spawnX = player.getWorld().getSpawnLocation().getBlockX(); + int playerX = player.getLocation().getBlockX(); + int distance = Math.subtractExact(playerX, spawnX); + ScoreManager scoreManager = plugin.getScoreManager(); + Statistics statistics = plugin.getStatistics(); + + if (distance > 1000) { + distance = distance - 1000; + if (currentScore.containsKey(playerUUID)) { + int score = currentScore.get(playerUUID); + if (distance > score) { + distance = distance - score; + } else { + distance = 0; + } + } + + int currentRun = Math.subtractExact(playerX, spawnX) - 1000; + if (!Double.isInfinite(distance) && distance > 0) { + scoreManager.updateScore(cp, distance); + statistics.setDeathrunTotaleStats(playerUUID, scoreManager.getScore(cp)); + + currentScore.put(playerUUID, currentRun); + statistics.setDeathrunCurrentStats(playerUUID, currentRun); + } + + int bestRun = currentBestRunScore.getOrDefault(playerUUID, 0); + if (currentRun > bestRun) { + plugin.getStatistics().setDeathrunBestRunStats(playerUUID, currentRun); + currentBestRunScore.put(playerUUID, currentRun); + } + } + }); + updatePlayerScoreBoard(); + } + + private void updatePlayerScoreBoard() { + ScoreManager scoreManager = plugin.getScoreManager(); + plugin.getServer().getOnlinePlayers().forEach(player -> { + ChallengePlayerScoreboard playerScoreboard = challengeScoreboard.getPlayerScoreboard(player); + int count = 0; + for (int i = 1; i < 5; i++) { + //TOP 5 + for (Scorable scorable : scoreManager.getByPositon(i)) { + if (count == 11) { + break; + } + + if (scorable != null) { + int score = scoreManager.getScore(scorable); + if (score > 0) { + int pos = scoreManager.getPosition(scorable); + Style style; + if (pos <= 3) { + style = Style.style(positionColors.getOrDefault(pos, NamedTextColor.WHITE), TextDecoration.BOLD); + } else { + style = Style.style(positionColors.getOrDefault(pos, NamedTextColor.WHITE)); + } + playerScoreboard.setSidebarLine(count, Component.text(pos + ". ").append(Component.text(scorable.getName() + " ", style)).append(Component.text(score, Color.BLUE))); + count++; + } + + } + } + } + + playerScoreboard.setSidebarLine(count, Component.empty()); + count++; + ChallengePlayer cp = new ChallengePlayer(player.getUniqueId()); + int ownPosition = scoreManager.getPosition(cp); + int beforePosition = ownPosition - 1; + int afterPosition = ownPosition + 1; + + Optional beforeOptionalScore = Optional.empty(); + if (beforePosition > 0) { + beforeOptionalScore = scoreManager.getByPositon(beforePosition).stream().findFirst(); + } + + Optional afterOptionalScore = scoreManager.getByPositon(afterPosition).stream().findFirst(); + + Scorable beforeScore = null; + if (beforeOptionalScore.isPresent()) { + beforeScore = beforeOptionalScore.get(); + } + + if (beforeScore != null) { + int pos = scoreManager.getPosition(beforeScore); + playerScoreboard.setSidebarLine(count, Component.text(pos + ". ").append(Component.text(beforeScore.getName() + " ", NamedTextColor.GRAY, TextDecoration.ITALIC)).append(Component.text(scoreManager.getScore(beforeScore), Color.BLUE))); + } else { + playerScoreboard.setSidebarLine(count, Component.text( "?. ").append(Component.text("niemand", NamedTextColor.GRAY, TextDecoration.ITALIC)).append(Component.text(" ???", Color.BLUE))); + } + count++; + + int ownPos = scoreManager.getPosition(cp); + playerScoreboard.setSidebarLine(count, Component.text(ownPos + ". ").append(Component.text(cp.getName() + " ", NamedTextColor.WHITE, TextDecoration.BOLD)).append(Component.text(scoreManager.getScore(cp), Color.BLUE))); + count++; + + Scorable afterScore = null; + if (afterOptionalScore.isPresent()) { + afterScore = afterOptionalScore.get(); + } + + if (afterScore != null) { + int pos = scoreManager.getPosition(afterScore); + playerScoreboard.setSidebarLine(count, Component.text(pos + ". ").append(Component.text(afterScore.getName() + " ", NamedTextColor.GRAY, TextDecoration.ITALIC)).append(Component.text(scoreManager.getScore(afterScore), Color.BLUE))); + } else { + playerScoreboard.setSidebarLine(count, Component.text( "?. ").append(Component.text("niemand", NamedTextColor.GRAY, TextDecoration.ITALIC)).append(Component.text(" ???", Color.BLUE))); + } + }); + } + + private void updateBossBar() { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth") && plugin.getTimer().isRunning()) { + ScoreManager scoreManager = plugin.getScoreManager(); + for (Player p : plugin.getVanish().getPlayerListWithoutVanishPlayers()) { + if (!plugin.getVanish().isVanish(p)) { + ChallengePlayer cp = new ChallengePlayer(p.getUniqueId()); + UUID uuid = p.getUniqueId(); + int currentRun = currentScore.getOrDefault(uuid, 0); + Component bossBarText = centerText(plugin.getTimer().formateRainbowTime(false), Component.text(CustomFontUtil.cupIcon + " ").append(Component.text(scoreManager.getScore(cp), Style.style(Color.GREEN, TextDecoration.BOLD))), Component.text(" " + CustomFontUtil.bootsIcon + " ").append(Component.text(currentRun + " ", Style.style(Color.GREEN, TextDecoration.BOLD))), Component.text(" " + CustomFontUtil.starIcon + " ").append(Component.text(currentBestRunScore.getOrDefault(uuid, 0) + " ", Style.style(Color.GREEN, TextDecoration.BOLD))), Component.text(CustomFontUtil.deathSkullIcon + " ").append(Component.text(deathScore.getOrDefault(uuid, 0), Style.style(Color.GREEN, TextDecoration.BOLD)))); + BossBar bossBar = bossBarMap.computeIfAbsent(p, player -> { + BossBar newBossBar = BossBar.bossBar(bossBarText, 1.0f, BossBar.Color.RED, BossBar.Overlay.PROGRESS); + newBossBar.addViewer(p); + return newBossBar; + }); + bossBar.name(bossBarText); + if (!Config.getBoolean("showtimer")) { + p.sendActionBar(Component.text("#" + scoreManager.getPosition(cp), Style.style(Color.GREEN, TextDecoration.BOLD))); + } + } + } + } + } + + public static Component centerText(Component central, Component left1, Component left2, Component right1, Component right2) { + // Berechne die Breite der einzelnen Teile + int centralWidth = getTextWidth(central); + int leftWidth = getTextWidth(left1, left2); + int rightWidth = getTextWidth(right1, right2); + + // Gesamtlänge der Texte (einschließlich der Lücken zwischen ihnen) + int totalWidth = centralWidth + leftWidth + rightWidth + 4; // 4 für die 2 Lücken zwischen den Texten + + // Berechne die Anzahl der Leerzeichen auf jeder Seite + int spacesOnLeft = (100 - totalWidth) / 2; + int spacesOnRight = 100 - totalWidth - spacesOnLeft; + + // Erstelle den zentrierten Text + Component spacesLeft = Component.text(" ".repeat(spacesOnLeft)); + Component spacesRight = Component.text(" ".repeat(spacesOnRight)); + Component formattedText = Component.text("") + .append(spacesLeft) + .append(left1) + .append(Component.text(" ")) + .append(left2) + .append(Component.text(" ")) + .append(central) + .append(Component.text(" ")) + .append(right1) + .append(Component.text(" ")) + .append(right2) + .append(spacesRight); + + return formattedText; + } + + private static int getTextWidth(Component... components) { + int width = 0; + for (Component component : components) { + width += getComponentWidth(component); + } + return width; + } + + private static int getComponentWidth(Component component) { + if (component instanceof TextComponent textComponent) { + String text = textComponent.content(); + int width = 0; + for (char c : text.toCharArray()) { + width += MinecraftTextUtils.getCharWidth(c); + } + return width; + } + // Falls der Component-Typ nicht unterstützt wird, default zu 0 Breite + return 0; + } + + public static void setCurrentRunScore(UUID uuid, int score) { + plugin.getLogger().severe("setCurrentRunScore: " + uuid.toString() + " " + score); + currentScore.put(uuid, score); + } + + public static void setBestRunScore(UUID uuid, int score) { + plugin.getLogger().severe("setBestRunScore: " + uuid.toString() + " " + score); + currentBestRunScore.put(uuid, score); + } + + public static void setDeathScore(UUID uuid, int score) { + plugin.getLogger().severe("setDeathScore: " + uuid.toString() + " " + score); + deathScore.put(uuid, score); + } + + private void rollBackBlocks() { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + + calendar.add(Calendar.HOUR_OF_DAY, -6); + calendar.add(Calendar.MINUTE, -2); + String since = sdf.format(calendar.getTime()); + + calendar.add(Calendar.MINUTE, 2); + String before = sdf.format(calendar.getTime()); + + String command = String.format("lb rb silent world world since %s before %s", since, before); + plugin.getLogger().info("RB Blocks: " + command); + + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + + private void rollBackEntities() { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + + calendar.add(Calendar.HOUR_OF_DAY, -1); + calendar.add(Calendar.MINUTE, -2); + String since = sdf.format(calendar.getTime()); + + calendar.add(Calendar.MINUTE, 2); + String before = sdf.format(calendar.getTime()); + + String command = String.format("lb rb entity silent world world since %s before %s", since, before); + plugin.getLogger().info("RB Entities: " + command); + + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DifferentItemsChallenge.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DifferentItemsChallenge.java index ad0b063..2493385 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DifferentItemsChallenge.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/DifferentItemsChallenge.java @@ -3,8 +3,8 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; import de.fanta.challenge.guis.eventgui.BingoItemsGui; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.ScoreManager; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.ScoreManager; import de.fanta.challenge.utils.Config; import de.fanta.challenge.utils.CubesideModUtils; import de.fanta.challengeutils.Color; diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/OreBattleChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/OreBattleChallengeEvent.java index 9902464..4994560 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/OreBattleChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/OreBattleChallengeEvent.java @@ -2,8 +2,8 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.Scorable; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; import de.fanta.challenge.teams.ChallengeTeam; import de.fanta.challenge.teams.TeamUtils; import de.fanta.challenge.utils.ChatSkullAPI.ChatSkull; diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/SammelFieberChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/SammelFieberChallengeEvent.java index faea954..83489bc 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/SammelFieberChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/SammelFieberChallengeEvent.java @@ -3,7 +3,7 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; import de.fanta.challenge.guis.eventgui.SammelFieberSettingsGui; -import de.fanta.challenge.scoreboard.ChallengePlayer; +import de.fanta.challenge.score.ChallengePlayer; import de.fanta.challenge.teams.ChallengeTeam; import de.fanta.challenge.teams.TeamUtils; import de.fanta.challenge.utils.Config; diff --git a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/forcequest/ForceQuestChallengeEvent.java b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/forcequest/ForceQuestChallengeEvent.java index b240215..1274a64 100644 --- a/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/forcequest/ForceQuestChallengeEvent.java +++ b/Challenge/src/main/java/de/fanta/challenge/challenges/ChallengeEvents/forcequest/ForceQuestChallengeEvent.java @@ -2,9 +2,9 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.TimerChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.Scorable; -import de.fanta.challenge.scoreboard.ScoreManager; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; +import de.fanta.challenge.score.ScoreManager; import de.fanta.challenge.utils.ChatSkullAPI.ChatSkull; import de.fanta.challenge.utils.Config; import de.fanta.challenge.utils.CoordsTargeter; diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/CommandRegistration.java b/Challenge/src/main/java/de/fanta/challenge/commands/CommandRegistration.java index 188b510..7689d6a 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/CommandRegistration.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/CommandRegistration.java @@ -38,8 +38,10 @@ import de.fanta.challenge.commands.hp.HPSetCommand; import de.fanta.challenge.commands.reset.ResetCommand; import de.fanta.challenge.commands.reset.ResetConfirmCommand; +import de.fanta.challenge.commands.restart.RestartConfirmCommand; import de.fanta.challenge.commands.settings.SettingsCommand; import de.fanta.challenge.commands.timer.TimerCommand; +import de.fanta.challenge.commands.timer.TimerDateCommand; import de.fanta.challenge.commands.timer.TimerGetCommand; import de.fanta.challenge.commands.timer.TimerPauseCommand; import de.fanta.challenge.commands.timer.TimerResetCommand; @@ -73,6 +75,9 @@ resetRouter.addCommandMapping(new ResetCommand(plugin)); resetRouter.addCommandMapping(new ResetConfirmCommand(plugin), "confirm"); + CommandRouter restartRouter = new CommandRouter(plugin.getCommand("restartserver")); + restartRouter.addCommandMapping(new RestartConfirmCommand(), "confirm"); + CommandRouter backpackRouter = new CommandRouter(plugin.getCommand("backpack")); backpackRouter.addCommandMapping(new BackpackCommand(plugin)); @@ -100,6 +105,7 @@ timerRouter.addCommandMapping(new TimerSetCommand(plugin), "set"); timerRouter.addCommandMapping(new TimerStartCommand(plugin), "start"); timerRouter.addCommandMapping(new TimerGetCommand(plugin), "get"); + timerRouter.addCommandMapping(new TimerDateCommand(plugin), "date"); CommandRouter forcemlgRouter = new CommandRouter(plugin.getCommand("forcemlg")); forcemlgRouter.addCommandMapping(new ForceMLGCommand(plugin)); diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventGetScoreCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventGetScoreCommand.java index 1c8ded8..dd4ba0e 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventGetScoreCommand.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventGetScoreCommand.java @@ -1,8 +1,8 @@ package de.fanta.challenge.commands.event; import de.fanta.challenge.Challenge; -import de.fanta.challenge.scoreboard.ChallengePlayer; -import de.fanta.challenge.scoreboard.Scorable; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.Scorable; import de.iani.cubesideutils.bukkit.commands.SubCommand; import de.iani.cubesideutils.commands.ArgsParser; import org.bukkit.Bukkit; diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventSaveScoresCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventSaveScoresCommand.java index aecd9de..e158567 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventSaveScoresCommand.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventSaveScoresCommand.java @@ -1,7 +1,7 @@ package de.fanta.challenge.commands.event; import de.fanta.challenge.Challenge; -import de.fanta.challenge.scoreboard.Scorable; +import de.fanta.challenge.score.Scorable; import de.iani.cubesideutils.bukkit.commands.SubCommand; import de.iani.cubesideutils.commands.ArgsParser; import de.iani.playerUUIDCache.CachedPlayer; diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventStartCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventStartCommand.java index 1ba43b5..7e475e4 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventStartCommand.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventStartCommand.java @@ -2,7 +2,7 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.events.ChallengeEventStatusChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; +import de.fanta.challenge.score.ChallengePlayer; import de.fanta.challenge.teams.ChallengeTeam; import de.fanta.challenge.teams.TeamUtils; import de.fanta.challenge.utils.Config; diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventToggleCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventToggleCommand.java index cac056c..c0196c0 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/event/EventToggleCommand.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/event/EventToggleCommand.java @@ -51,7 +51,7 @@ return true; } } - plugin.getSBManager().updateEventScoreboard(); + //TODO SCOREBORD plugin.getSBManager().updateEventScoreboard(); return true; } } diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/reset/ResetConfirmCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/reset/ResetConfirmCommand.java index 68ba078..2d8ae79 100644 --- a/Challenge/src/main/java/de/fanta/challenge/commands/reset/ResetConfirmCommand.java +++ b/Challenge/src/main/java/de/fanta/challenge/commands/reset/ResetConfirmCommand.java @@ -19,7 +19,7 @@ @Override public boolean onCommand(CommandSender sender, Command command, String alias, String commandString, ArgsParser args) { if ((sender instanceof Player && plugin.isEditor((Player) sender)) || sender.hasPermission("Challenges.editor.override")) { - SaveWorldUtils.restartServer(args.getNext(null)); + SaveWorldUtils.restartServer(args.getNext(null), true); } else if (plugin.getCurrentEditor() != null) { plugin.getComponentUtil().sendErrorMessage(sender, "Du bist kein Editor! Nur " + plugin.getCurrentEditor().getName() + " kann die Map zurücksetzen!"); return true; diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/restart/RestartConfirmCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/restart/RestartConfirmCommand.java new file mode 100644 index 0000000..b952392 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/commands/restart/RestartConfirmCommand.java @@ -0,0 +1,22 @@ +package de.fanta.challenge.commands.restart; + +import de.fanta.challenge.utils.SaveWorldUtils; +import de.iani.cubesideutils.bukkit.commands.SubCommand; +import de.iani.cubesideutils.commands.ArgsParser; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class RestartConfirmCommand extends SubCommand { + + @Override + public boolean onCommand(CommandSender sender, Command command, String alias, String commandString, ArgsParser args) { + SaveWorldUtils.saveConfigs(); + SaveWorldUtils.restartServer(args.getNext(null), false); + return true; + } + + @Override + public String getRequiredPermission() { + return "challenge.restart"; + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/commands/timer/TimerDateCommand.java b/Challenge/src/main/java/de/fanta/challenge/commands/timer/TimerDateCommand.java new file mode 100644 index 0000000..9dad7ae --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/commands/timer/TimerDateCommand.java @@ -0,0 +1,39 @@ +package de.fanta.challenge.commands.timer; + +import de.fanta.challenge.Challenge; +import de.iani.cubesideutils.bukkit.commands.SubCommand; +import de.iani.cubesideutils.commands.ArgsParser; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class TimerDateCommand extends SubCommand { + + private final Challenge plugin; + + public TimerDateCommand(Challenge plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String alias, String commandString, ArgsParser args) { + if (!(sender instanceof Player player)) { + plugin.getComponentUtil().sendErrorMessage(sender, "You are not a Player :>"); + return true; + } + if (args.hasNext()) { + if (plugin.getTimer().setDate(args.getAll(""))) { + plugin.getComponentUtil().sendNormalMessage(player, "Datum gesetzt!"); + } else { + plugin.getComponentUtil().sendErrorMessage(player, "Fehler im Datum-Format (dd-MM-yyy HH:mm:ss)"); + } + return true; + } + return false; + } + + @Override + public String getRequiredPermission() { + return "challenge.timer.date"; + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/guis/ResetGui.java b/Challenge/src/main/java/de/fanta/challenge/guis/ResetGui.java index 7fce73d..7a08a58 100644 --- a/Challenge/src/main/java/de/fanta/challenge/guis/ResetGui.java +++ b/Challenge/src/main/java/de/fanta/challenge/guis/ResetGui.java @@ -40,7 +40,7 @@ int slot = event.getSlot(); if (slot == RESET_INDEX) { - SaveWorldUtils.restartServer(null); + SaveWorldUtils.restartServer(null, true); getPlayer().closeInventory(); plugin.getComponentUtil().sendNormalMessage(getPlayer(), "Server wird nun neu gestartet!"); } diff --git a/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/EventGui.java b/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/EventGui.java index 8551471..5a0bcd2 100644 --- a/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/EventGui.java +++ b/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/EventGui.java @@ -3,6 +3,7 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.challenges.ChallengeEvents.BridgeRaceChallengeEvent; import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEvent; +import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEventMonth; import de.fanta.challenge.utils.Config; import de.fanta.challengeutils.ItemUtils; import de.fanta.challengeutils.Color; @@ -38,6 +39,7 @@ private static final int DIFFERENT_ITEMS_INDEX = 28; private static final int TIME_EVENT_INDEX = 29; + private static final int DEATHRUN_EVENT_MONTH_INDEX = 30; private static final int EVENT_SETTINGS_INDEX = 45; private static final int CLOSE_IDEX = 54; @@ -144,6 +146,13 @@ item = ItemUtils.createGuiItem(Material.CLOCK, Component.text("Time", Color.RED), Component.text("Zeigt wie lang ein Spieler mitgespielt hat.", Color.GREEN)); } } + case DEATHRUN_EVENT_MONTH_INDEX -> { + if (Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + item = ItemUtils.createGuiItem(Material.CHAINMAIL_BOOTS, Component.text("Deathrun Event Monat", Color.GREEN), true, Component.text("Laufe so weit wie möglich ohne zu sterben", Color.GREEN)); + } else { + item = ItemUtils.createGuiItem(Material.CHAINMAIL_BOOTS, Component.text("Deathrun Event Monat", Color.RED), Component.text("Laufe so weit wie möglich ohne zu sterben", Color.GREEN)); + } + } case EVENT_SETTINGS_INDEX -> item = ItemUtils.createGuiItem(Material.CHAIN_COMMAND_BLOCK, Component.text("Event Settings", Color.BLUE)); @@ -251,6 +260,15 @@ plugin.getComponentUtil().sendErrorMessage(p, "Diese Event läuft bereits"); } } + case DEATHRUN_EVENT_MONTH_INDEX -> { + if (!Objects.equals(Config.getString("event.type"), "deathrunMonth")) { + Config.setValue("event.type", "deathrunMonth"); + plugin.getComponentUtil().sendTitleToAll(Component.text("Event Monat"), Component.text("Laufe so weit wie möglich ohne zu sterben!", Color.GREEN)); + DeathrunChallengeEventMonth.load(p.getWorld()); + } else { + plugin.getComponentUtil().sendErrorMessage(p, "Diese Event läuft bereits"); + } + } } rebuildInventory(); diff --git a/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/TeamSettingsGUI.java b/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/TeamSettingsGUI.java index b8327b7..c1bfa54 100644 --- a/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/TeamSettingsGUI.java +++ b/Challenge/src/main/java/de/fanta/challenge/guis/eventgui/TeamSettingsGUI.java @@ -79,7 +79,7 @@ Config.setValue("event.teams", true); plugin.getComponentUtil().sendTitleToAll(Component.text("Event"), Component.text("Teams aktiviert", Color.GREEN)); plugin.getScoreManager().resetScores(); - plugin.getSBManager().updateEventScoreboard(); + //TODO SCOREBORD plugin.getSBManager().updateEventScoreboard(); } else { Config.setValue("event.teams", false); plugin.getComponentUtil().sendTitleToAll(Component.text("Event"), Component.text("Teams deaktiviert", Color.RED)); @@ -97,7 +97,7 @@ Config.setValue("event.teamselect", true); plugin.getComponentUtil().sendTitleToAll(Component.text("Event"), Component.text("Team auswahl aktiviert", Color.GREEN)); for (Player pp : Bukkit.getOnlinePlayers()) { - plugin.getSBManager().removeScoreboard(pp); + //TODO SCOREBORD plugin.getSBManager().removeScoreboard(pp); pp.getInventory().setItem(8, TeamUtils.selctItem()); } } else { diff --git a/Challenge/src/main/java/de/fanta/challenge/guis/settingsgui/OtherSettingsGui.java b/Challenge/src/main/java/de/fanta/challenge/guis/settingsgui/OtherSettingsGui.java index 097f4e4..720acf2 100644 --- a/Challenge/src/main/java/de/fanta/challenge/guis/settingsgui/OtherSettingsGui.java +++ b/Challenge/src/main/java/de/fanta/challenge/guis/settingsgui/OtherSettingsGui.java @@ -87,7 +87,7 @@ plugin.getComponentUtil().sendTitleToAll(Component.text("Einstellungen"), Component.text("Herzen in der Tablist anzeigen aktiviert", Color.GREEN)); Config.setValue("tabhp", true); } - plugin.getSBManager().updateTabHP(); + //TODO SCOREBORD plugin.getSBManager().updateTabHP(); } case SMELT_ORES_ON_BREAK_INDEX -> { if (Config.getBoolean("silkore")) { diff --git a/Challenge/src/main/java/de/fanta/challenge/listeners/EventRegistration.java b/Challenge/src/main/java/de/fanta/challenge/listeners/EventRegistration.java index 0809c58..4b2152d 100644 --- a/Challenge/src/main/java/de/fanta/challenge/listeners/EventRegistration.java +++ b/Challenge/src/main/java/de/fanta/challenge/listeners/EventRegistration.java @@ -6,6 +6,7 @@ import de.fanta.challenge.challenges.ChallengeEvents.BingoChallengeEvent; import de.fanta.challenge.challenges.ChallengeEvents.BridgeRaceChallengeEvent; import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEvent; +import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEventMonth; import de.fanta.challenge.challenges.ChallengeEvents.DifferentItemsChallenge; import de.fanta.challenge.challenges.ChallengeEvents.forcequest.ForceQuestChallengeEvent; import de.fanta.challenge.challenges.ChallengeEvents.OreBattleChallengeEvent; @@ -83,6 +84,7 @@ pM.registerEvents(new NoSneakChallenge(), plugin); pM.registerEvents(new BingoChallengeEvent(plugin), plugin); pM.registerEvents(new DeathrunChallengeEvent(), plugin); + pM.registerEvents(new DeathrunChallengeEventMonth(), plugin); pM.registerEvents(new IceRunnerChallenge(), plugin); pM.registerEvents(new RandomMobChallenge(), plugin); pM.registerEvents(new BedrockWallChallenge(), plugin); diff --git a/Challenge/src/main/java/de/fanta/challenge/listeners/PlayerListener.java b/Challenge/src/main/java/de/fanta/challenge/listeners/PlayerListener.java index f97d8fa..16acca9 100644 --- a/Challenge/src/main/java/de/fanta/challenge/listeners/PlayerListener.java +++ b/Challenge/src/main/java/de/fanta/challenge/listeners/PlayerListener.java @@ -4,7 +4,7 @@ import de.fanta.challenge.ServerType; import de.fanta.challenge.challenges.ChallengeEvents.BridgeRaceChallengeEvent; import de.fanta.challenge.events.PlayerCountChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; +import de.fanta.challenge.score.ChallengePlayer; import de.fanta.challenge.utils.Config; import de.fanta.challengeutils.Color; import net.kyori.adventure.text.Component; @@ -141,7 +141,7 @@ public void vanishToggle(VanishStatusChangeEvent e) { Player p = e.getPlayer(); if (e.isVanishing()) { - plugin.getSBManager().removeScoreboard(p); + //TODO SCOREBORD plugin.getSBManager().removeScoreboard(p); if (plugin.getCurrentEditor() == p) { if (plugin.getServerType() != ServerType.CHALLENGE_EVENT) { plugin.updateEditor(); @@ -149,7 +149,7 @@ } } else { if (plugin.getServerType() != ServerType.ADVENTURE) { - plugin.getSBManager().setScoreboardtoPlayer(p); + //TODO SCOREBORDplugin.getSBManager().setScoreboardtoPlayer(p); } if (plugin.getCurrentEditor() == null) { plugin.setCurrentEditor(p); diff --git a/Challenge/src/main/java/de/fanta/challenge/listeners/QuitJoinListener.java b/Challenge/src/main/java/de/fanta/challenge/listeners/QuitJoinListener.java index dd95796..7e392b2 100644 --- a/Challenge/src/main/java/de/fanta/challenge/listeners/QuitJoinListener.java +++ b/Challenge/src/main/java/de/fanta/challenge/listeners/QuitJoinListener.java @@ -6,7 +6,7 @@ import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEvent; import de.fanta.challenge.events.PlayerCountChangedEvent; import de.fanta.challenge.events.ServerStatusChangedEvent; -import de.fanta.challenge.scoreboard.ChallengePlayer; +import de.fanta.challenge.score.ChallengePlayer; import de.fanta.challenge.utils.Config; import de.fanta.challenge.utils.SaveWorldUtils; import de.fanta.challengeutils.Color; @@ -44,8 +44,8 @@ if (plugin.getServerType() != ServerType.ADVENTURE) { if (!DeathrunChallengeEvent.getDeadPlayer().contains(p.getUniqueId())) { plugin.getScoreManager().join(new ChallengePlayer(p.getUniqueId())); - plugin.getSBManager().setScoreboardtoPlayer(p); - plugin.getSBManager().updateEventScoreboard(); + //TODO SCOREBORDplugin.getSBManager().setScoreboardtoPlayer(p); + //TODO SCOREBORDplugin.getSBManager().updateEventScoreboard(); if (!Config.getBoolean("event.teams") && plugin.getScoreManager().getScores() != null && plugin.getScoreManager().getScore(new ChallengePlayer(p.getUniqueId())) == 0) { plugin.getScoreManager().updateScore(new ChallengePlayer(e.getPlayer().getUniqueId()), 0); } @@ -127,7 +127,7 @@ SaveWorldUtils.saveWorld(plugin.getFirstEditor().getUniqueId().toString(), SaveSlot.SLOT_AUTO); plugin.startResetTask(); } else { - SaveWorldUtils.restartServer(null); + SaveWorldUtils.restartServer(null, true); } } } @@ -139,7 +139,7 @@ if (!plugin.getVanish().isVanish(player)) { e.quitMessage(null); plugin.getComponentUtil().sendBrodCastMessage(plugin.getPrefixComponent().append(player.name().color(Color.BLUE).append(Component.text(" hat die Lobby verlassen! ", Color.RED).append(Component.text("[" + (Bukkit.getServer().getOnlinePlayers().size() - plugin.getVanish().countVanishPlayers() - 1) + "/" + Bukkit.getServer().getMaxPlayers() + "]", Color.YELLOW))))); - this.plugin.getSBManager().removeScoreboard(player); + //TODO SCOREBORDthis.plugin.getSBManager().removeScoreboard(player); Bukkit.getPluginManager().callEvent(new PlayerCountChangedEvent(Bukkit.getOnlinePlayers().size() - plugin.getVanish().countVanishPlayers() - 1)); diff --git a/Challenge/src/main/java/de/fanta/challenge/score/ChallengePlayer.java b/Challenge/src/main/java/de/fanta/challenge/score/ChallengePlayer.java new file mode 100644 index 0000000..3fb3479 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/score/ChallengePlayer.java @@ -0,0 +1,49 @@ +package de.fanta.challenge.score; + +import de.fanta.challenge.Challenge; +import de.iani.playerUUIDCache.CachedPlayer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.UUID; + +public class ChallengePlayer implements Scorable { + + private final UUID uuid; + + public ChallengePlayer(UUID uuid) { + this.uuid = uuid; + } + + public int hashCode() { + return uuid.hashCode(); + } + + public boolean equals(Object other) { + if (!(other instanceof ChallengePlayer cp)) { + return false; + } + return this.uuid.equals(cp.uuid); + } + + @Override + public void setScoreboard(Scoreboard scoreboard) { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + player.setScoreboard(scoreboard); + } + } + + @Override + public String getIdentifier() { + CachedPlayer player = Challenge.getPlugin().playerUUIDCache.getPlayer(uuid); + return player.getName(); + } + + @Override + public String getName() { + CachedPlayer player = Challenge.getPlugin().playerUUIDCache.getPlayer(uuid); + return player.getName(); + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/score/Scorable.java b/Challenge/src/main/java/de/fanta/challenge/score/Scorable.java new file mode 100644 index 0000000..66f1f78 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/score/Scorable.java @@ -0,0 +1,13 @@ +package de.fanta.challenge.score; + +import org.bukkit.scoreboard.Scoreboard; + +public interface Scorable { + + void setScoreboard(Scoreboard scoreboard); + + String getIdentifier(); + + String getName(); + +} diff --git a/Challenge/src/main/java/de/fanta/challenge/score/ScoreManager.java b/Challenge/src/main/java/de/fanta/challenge/score/ScoreManager.java new file mode 100644 index 0000000..4e78a68 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/score/ScoreManager.java @@ -0,0 +1,341 @@ +package de.fanta.challenge.score; + +import de.fanta.challenge.Challenge; +import de.fanta.challenge.challenges.ChallengeEvents.SammelFieberChallengeEvent; +import de.fanta.challenge.challenges.ChallengeEvents.TimeChallengeEvent; +import de.fanta.challenge.guis.eventgui.SammelFieberSettingsGui; +import de.fanta.challenge.teams.ChallengeTeam; +import de.fanta.challenge.teams.TeamUtils; +import de.fanta.challenge.utils.Config; +import de.fanta.challengeutils.Color; +import de.iani.cubesideutils.HastebinUtil; +import de.iani.cubesideutils.StringUtil; +import de.iani.playerUUIDCache.CachedPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Team; + +import javax.annotation.Nullable; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.IntPredicate; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public class ScoreManager { + + public static class ScoreData { + private final Scorable scorable; + private int score; + private int position; + private int index; + + public ScoreData(Scorable scorable, int index) { + this.scorable = scorable; + this.index = index; + + this.score = 0; + this.position = 1; + } + + public Scorable getScorable() { + return scorable; + } + + public int getPostition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + public void changeScore(int difference) { + this.score += difference; + } + } + + private final Challenge plugin; + private final Map scores; + private final List positions; + + public ScoreManager(Challenge plugin) { + this.plugin = plugin; + this.scores = new HashMap<>(); + this.positions = new ArrayList<>(); + } + + public void join(Scorable s) { + if (!scores.containsKey(s)) { + ScoreData data = new ScoreData(s, positions.size()); + scores.put(s, data); + positions.add(data); + } + } + + public void updateScore(Scorable s, int difference) { + //if (difference == 0) { + // return; + //} + + ScoreData data = scores.get(s); + data.changeScore(difference); + + int current = data.getIndex(); + int dir = (int) Math.signum(difference * -1); + + IntPredicate forCondition = (dir == -1) ? curr -> curr > 0 && positions.get(curr - 1).getScore() < data.getScore() : curr -> curr < positions.size() - 1 && positions.get(curr + 1).getScore() > data.getScore(); + + int startingIndex = data.getIndex(); + + // swap with neighbors as long as we are now better/worse then them + for (; forCondition.test(current); current += dir) { + ScoreData other = positions.get(current + dir); + + positions.set(current + dir, data); + positions.set(current, other); + data.setIndex(current + dir); + other.setIndex(current); + } + + // update positions + int endIndex = data.getIndex(); + int i = Math.min(startingIndex, endIndex); + + ScoreData curr; + int lastPosition; + int lastScore; + if (i == 0) { + curr = positions.getFirst(); + curr.setPosition(1); + lastPosition = 1; + lastScore = curr.getScore(); + i++; + } else { + curr = positions.get(i - 1); + lastPosition = curr.getPostition(); + lastScore = curr.getScore(); + } + + for (; i < positions.size(); i++) { + curr = positions.get(i); + int correctPosition = (curr.getScore() == lastScore) ? lastPosition : lastPosition + 1; + if (curr.getPostition() == correctPosition && i > Math.max(startingIndex, endIndex)) { + break; + } + + curr.setPosition(correctPosition); + lastPosition = correctPosition; + lastScore = curr.getScore(); + } + } + + public void setScore(Scorable s, int score) { + int diff = score - getScore(s); + updateScore(s, diff); + } + + public int getScore(Scorable s) { + return scores.get(s).getScore(); + } + + public int getPosition(Scorable s) { + return scores.get(s).getPostition(); + } + + public Set getByPositon(int position) { + if (positions.isEmpty() || positions.getLast().getPostition() < position) { + return Collections.emptySet(); + } + + int start = position - 1; + int end = positions.size(); + + int found; + while (true) { + int middle = start + (end - start) / 2; + ScoreData current = positions.get(middle); + if (current.getPostition() == position) { + found = middle; + break; + } else if (start >= end - 1) { + plugin.getLogger().log(Level.SEVERE, "position not found but expected to be present: " + position); + plugin.getLogger().log(Level.SEVERE, positions.toString()); + return Collections.emptySet(); + } else if (current.getPostition() > position) { + end = middle; + } else { + start = middle; + } + } + + start = end = found; + for (; start > 0 && positions.get(start - 1).getPostition() == position; start--) { + } + for (; end < positions.size() - 2 && positions.get(end + 1).getPostition() == position; end++) { + } + + return positions.subList(start, end + 1).stream().map(ScoreData::getScorable).collect(Collectors.toSet()); + } + + public void saveScores(@Nullable Player player) { + saveScores(player, 0); + } + + public void saveScores(@Nullable Player player, int minScore) { + StringBuilder sb = new StringBuilder(); + String ownerName = player != null ? player.getName() : "Console"; + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss"); + Date currentTime = new Date(); + + sb.append("Challenges Event -> ").append(StringUtil.capitalizeFirstLetter(Config.getString("event.type"), false)).append('\n'); + sb.append("=".repeat(20)).append('\n'); + sb.append("Erstellt von: ").append(ownerName).append('\n'); + sb.append("Erstellt am: ").append(formatter.format(currentTime)).append('\n'); + sb.append("Timer: ").append(plugin.getTimer().formatTime()).append('\n'); + if (Objects.equals(Config.getString("event.type"), "sammelfieber")) { + if (SammelFieberSettingsGui.getEventItem() != null) { + sb.append("Item: ").append(SammelFieberSettingsGui.getEventItem().getType().name()).append('\n'); + sb.append("Cubes pro Item: ").append(SammelFieberSettingsGui.MONEY).append('\n'); + sb.append("Items abgegeben: ").append(SammelFieberChallengeEvent.getCount()).append('\n'); + sb.append("Cubes gesammt: ").append(SammelFieberSettingsGui.MONEY * SammelFieberChallengeEvent.getCount()).append('\n'); + sb.append("Cubes pro Spieler: ").append(SammelFieberSettingsGui.MONEY * SammelFieberChallengeEvent.getCount() / scores.size()).append('\n'); + } + } + sb.append("=".repeat(20)).append('\n'); + sb.append("Teilnehmer (").append(this.scores.size()).append("):\n"); + + if (!Objects.equals(Config.getString("event.type"), "time")) { + if (this.scores.isEmpty()) { + sb.append(" Das Event hatte keine Teilnehmer!\n"); + } else { + if (Config.getBoolean("event.teams")) { + for (ScoreData entry : positions) { + ChallengeTeam challengeTeam = TeamUtils.getTeam(entry.getScorable().getName()); + if (challengeTeam != null) { + Team team = TeamUtils.getScoreboard().getTeam(challengeTeam.getName()); + if (team != null) { + sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" (").append(team.getEntries().toString().replace("[", "").replace("]", "")).append(")").append(" ").append(entry.getScore()).append("\n"); + } + } + } + } else { + if (Config.getBoolean("event.tournament")) { + HashMap tournamentScores = getTournamentScores(new ArrayList<>(positions), minScore); + for (ScoreData entry : positions) { + sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" ").append(entry.getScore()).append(" (").append(tournamentScores.getOrDefault(entry.getScorable(), 0)).append(")").append("\n"); + } + } else { + for (ScoreData entry : positions) { + sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" ").append(entry.getScore()).append("\n"); + } + } + } + } + } else { + HashMap times = TimeChallengeEvent.getPlayerPlayTimes(); + for (UUID uuid : times.keySet()) { + CachedPlayer cp = plugin.getPlayerUUIDCache().getPlayer(uuid); + sb.append(cp != null ? cp.getName() : uuid.toString()).append(": ").append(formatTime(times.get(uuid))).append("\n"); + } + } + + HastebinUtil.paste(sb.toString(), new HastebinUtil.PasteCompletedListener() { + @Override + public void onSuccess(String url) { + if (player != null) { + plugin.getComponentUtil().sendMessage(player, Component.text("Event Log gepastet: ", Color.GREEN).append(Component.text(url, Color.YELLOW).clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, url)))); + } + plugin.getLogger().log(Level.SEVERE, "Event Log gepastet: " + url); + } + + @Override + public void onError(Exception e) { + if (player != null) { + plugin.getComponentUtil().sendErrorMessage(player, "Paste konnte nicht erstellt werden"); + } + plugin.getLogger().log(Level.SEVERE, "Could not paste event log", e); + plugin.getLogger().log(Level.SEVERE, "Log Score String", sb.toString()); + } + }); + } + + public void resetScores() { + this.scores.clear(); + } + + public Map getScores() { + return scores; + } + + public List getPositions() { + return positions; + } + + public HashMap getTournamentScores(List scoreDataList, int minScore) { + HashMap tournamentScores = new HashMap<>(); + List newScoreDataList = new ArrayList<>(); + + for (ScoreData scoreData : scoreDataList) { + int score = scoreData.getScore(); + if (score >= minScore) { + newScoreDataList.add(scoreData); + } + } + + + int length = newScoreDataList.size(); + if (length > 0) { + int lastPostition = newScoreDataList.get(length - 1).getPostition() - 1; + int threePoints = Math.round((lastPostition + 1 - 3) / 3.0f + 3); + int twoPoints = Math.round((lastPostition + 1 - 3) / 3.0f * 2 + 3); + for (ScoreData scoreData : newScoreDataList) { + Scorable scorable = scoreData.getScorable(); + int pos = scoreData.getPostition() - 1; + if (pos < 3) { + tournamentScores.put(scorable, 6 - pos); + } else if (pos < threePoints) { + tournamentScores.put(scorable, 3); + } else if (pos < twoPoints) { + tournamentScores.put(scorable, 2); + } else { + tournamentScores.put(scorable, 1); + } + } + } + return tournamentScores; + } + + public String formatTime(long time) { + String formattime = StringUtil.formatTimespan((time / 1000) * 1000, " Tage, ", ":", "", "", "", ":", false, true); + if (formattime.startsWith("1 Tage")) { + return StringUtil.formatTimespan((time / 1000) * 1000, " Tag, ", ":", "", "", "", ":", false, true); + } + return formattime; + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/BukkitScoreBoardManager.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/BukkitScoreBoardManager.java deleted file mode 100644 index 79c1252..0000000 --- a/Challenge/src/main/java/de/fanta/challenge/scoreboard/BukkitScoreBoardManager.java +++ /dev/null @@ -1,167 +0,0 @@ -package de.fanta.challenge.scoreboard; - -import de.fanta.challenge.Challenge; -import de.fanta.challenge.ServerType; -import de.fanta.challenge.teams.ChallengeTeam; -import de.fanta.challenge.teams.TeamUtils; -import de.fanta.challenge.utils.Config; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Criteria; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.RenderType; -import org.bukkit.scoreboard.Score; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; - -public class BukkitScoreBoardManager implements ScoreBoardMananger { - - private final Challenge plugin; - private Scoreboard scoreboard; - private Team team; - - private Objective event; - private Objective tabHP; - - public BukkitScoreBoardManager(Challenge plugin) { - this.plugin = plugin; - } - - @Override - public void initScoreboard() { // only possible after first world has loaded - this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); - this.team = scoreboard.registerNewTeam("Player"); - - this.team.color(NamedTextColor.GREEN); - - updateTabHP(); - } - - @Override - public void setScoreboardtoPlayer(Player p) { - if (this.scoreboard == null) { - if (plugin.getServerType() != ServerType.ADVENTURE) { - initScoreboard(); - } - } - - team.addEntry(p.getName()); - - p.setScoreboard(scoreboard); - } - - @Override - public void setScoreboardtoTeam(ChallengeTeam challengeTeam) { - if (this.scoreboard == null) { - if (plugin.getServerType() != ServerType.ADVENTURE) { - initScoreboard(); - } - } - - team.addEntry(challengeTeam.getChatColor() + challengeTeam.getName()); - } - - @Override - public void removeScoreboard(Player p) { - if (team != null) { - if (plugin.getServerType() != ServerType.ADVENTURE) { - team.removeEntry(p.getName()); - p.setScoreboard(scoreboard); - } - } - } - - @Override - public void removeAllFromScoreboard() { - for (String s : team.getEntries()) { - team.removeEntry(s); - } - } - - @Override - public int countScoreboardPlayers() { - return team.getEntries().size(); - } - - @Override - public void updateTabHP() { - if (plugin.getServerType() == ServerType.ADVENTURE) { - return; - } - if (Config.getBoolean("tabhp")) { - if (this.tabHP == null) { - tabHP = scoreboard.registerNewObjective("health", Criteria.HEALTH, Component.empty()); - } - tabHP.setRenderType(RenderType.HEARTS); - tabHP.setDisplaySlot(DisplaySlot.PLAYER_LIST); - } else { - if (tabHP != null) { - tabHP.unregister(); - tabHP = null; - } - } - } - - @Override - public void updateEventScoreboard() { - if (plugin.getServerType() == ServerType.ADVENTURE) { - return; - } - if (Config.getBoolean("event.enabled")) { - if (!Config.getBoolean("event.teams")) { - this.team.color(NamedTextColor.BLUE); - this.team.displayName(Component.text("Event")); - - if (this.event == null) { - event = this.scoreboard.registerNewObjective("event", Criteria.DUMMY, Component.text("Challenges", NamedTextColor.GOLD)); - } - event.setDisplaySlot(DisplaySlot.SIDEBAR); - event.displayName(team.prefix().append(team.displayName()).color(team.color())); - event.setRenderType(RenderType.INTEGER); - - for (String entry : team.getEntries()) { - if (!event.getScore(entry).isScoreSet()) { - event.getScore(entry).setScore(0); - } - } - } else { - this.team.color(NamedTextColor.BLUE); - this.team.displayName(Component.text("Team Event")); - - event = TeamUtils.getTeamscoreboardObjective(); - - event.setDisplaySlot(DisplaySlot.SIDEBAR); - event.displayName(team.prefix().append(team.displayName()).color(team.color())); - event.setRenderType(RenderType.INTEGER); - } - - - } else { - if (event != null) { - event.unregister(); - event = null; - } - this.team.color(NamedTextColor.GREEN); - this.team.displayName(Component.text("Player")); - } - } - - @Override - public void updateEventScore(Scorable s) { - if (plugin.getServerType() == ServerType.ADVENTURE) { - return; - } - if (this.event != null) { - Score score = event.getScore(s.getIdentifier()); - score.setScore(plugin.getScoreManager().getScore(s)); - } - } - - @Override - public Scoreboard getScoreboard() { - return scoreboard; - } -} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayer.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayer.java deleted file mode 100644 index 5ce9b31..0000000 --- a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayer.java +++ /dev/null @@ -1,48 +0,0 @@ -package de.fanta.challenge.scoreboard; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Scoreboard; - -import java.util.UUID; - -public class ChallengePlayer implements Scorable { - - private final UUID uuid; - - public ChallengePlayer(UUID uuid) { - this.uuid = uuid; - } - - public int hashCode() { - return uuid.hashCode(); - } - - public boolean equals(Object other) { - if (!(other instanceof ChallengePlayer cp)) { - return false; - } - return this.uuid.equals(cp.uuid); - } - - @Override - public void setScoreboard(Scoreboard scoreboard) { - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - player.setScoreboard(scoreboard); - } - } - - @Override - public String getIdentifier() { - OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); - return player.getName(); - } - - @Override - public String getName() { - OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); - return player.getName(); - } -} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayerScoreboard.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayerScoreboard.java new file mode 100644 index 0000000..ba51c72 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengePlayerScoreboard.java @@ -0,0 +1,125 @@ +package de.fanta.challenge.scoreboard; + +import com.google.common.base.Preconditions; +import io.papermc.paper.scoreboard.numbers.NumberFormat; +import net.kyori.adventure.text.Component; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.Arrays; + +public class ChallengePlayerScoreboard { + private final Player player; + private final ChallengeScoreboard scoreboard; + private final Scoreboard bukkitScoreboard; + private final Objective sidebarObjective; + + private Component[] sidebarLines; + + ChallengePlayerScoreboard(ChallengeScoreboard scoreboard, Player player) { + this.player = player; + this.scoreboard = scoreboard; + + bukkitScoreboard = player.getServer().getScoreboardManager().getNewScoreboard(); + player.setScoreboard(bukkitScoreboard); + + sidebarObjective = bukkitScoreboard.registerNewObjective("sidebar", "dummy", scoreboard.getSidebarTitle()); + sidebarObjective.setDisplaySlot(DisplaySlot.SIDEBAR); + sidebarObjective.setDisplayName(scoreboard.getSidebarTitle()); + sidebarObjective.numberFormat(NumberFormat.blank()); + + Component[] lines = scoreboard.getSidebarLines(); + if (lines != null) { + for (int i = 0; i < lines.length; i++) { + setSidebarLine(i, lines[i]); + } + } + } + + Player getPlayer() { + return player; + } + + Scoreboard getBukkitScoreboard() { + return bukkitScoreboard; + } + + ChallengeScoreboard getMultiScoreboard() { + return scoreboard; + } + + void disable() { + if (player.getScoreboard() == bukkitScoreboard) { + player.setScoreboard(player.getServer().getScoreboardManager().getMainScoreboard()); + } + } + + void resetScores(String entry) { + bukkitScoreboard.resetScores(entry); + } + + public void setSidebarLine(int line, Component component) { + Preconditions.checkArgument(line >= 0 && line < 15, "line >= 0 && line < 15"); + Preconditions.checkNotNull(component, "component may not be null"); + int oldLength = sidebarLines == null ? 0 : sidebarLines.length; + if (line >= oldLength) { + sidebarLines = sidebarLines == null ? new Component[line + 1] : Arrays.copyOf(sidebarLines, line + 1); + for (int i = oldLength; i < line; i++) { + internalSetSidebarLine(i, Component.empty()); + } + } + internalSetSidebarLine(line, component); + } + + private void internalSetSidebarLine(int line, Component component) { + Component old = sidebarLines[line]; + if (old != null) { + if (old.equals(component)) { + return; + } + String l = getSidebarLineMarker(line); + bukkitScoreboard.resetScores(l); + } + sidebarLines[line] = component; + Score score = sidebarObjective.getScore(getSidebarLineMarker(line)); + score.setScore(15 - line); + score.customName(component); + } + + private String getSidebarLineMarker(int line) { + if (line <= 9) { + return ChatColor.COLOR_CHAR + Integer.toString(line) + " "; + } + return ChatColor.COLOR_CHAR + Integer.toString(line - 10) + " "; + } + + public void limitSidebarLines(int maxlines) { + if (sidebarLines != null) { + int lines = sidebarLines.length; + for (int line = maxlines; line < lines; line++) { + String l = sidebarLines[line] + getSidebarLineMarker(line); + bukkitScoreboard.resetScores(l); + } + sidebarLines = maxlines == 0 ? null : Arrays.copyOf(sidebarLines, maxlines); + } + } + + public void clearSidebar() { + if (sidebarLines != null) { + int lines = sidebarLines.length; + for (int line = 0; line < lines; line++) { + String l = sidebarLines[line] + getSidebarLineMarker(line); + bukkitScoreboard.resetScores(l); + } + sidebarLines = null; + } + } + + Objective getSidebarObjective() { + return sidebarObjective; + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboard.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboard.java new file mode 100644 index 0000000..6362fa7 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboard.java @@ -0,0 +1,117 @@ +package de.fanta.challenge.scoreboard; + +import com.google.common.base.Preconditions; +import net.kyori.adventure.text.Component; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; + +public class ChallengeScoreboard { + private final static String DEFAULT_SIDEBAR_TITLE = ChatColor.BOLD.toString() + ChatColor.BLUE + "Event"; + private final HashMap playerScoreboards; + + private final HashMap teams; + + private String sidebarTitle; + private Component[] sidebarLines; + + public ChallengeScoreboard() { + playerScoreboards = new HashMap<>(); + teams = new HashMap<>(); + sidebarTitle = DEFAULT_SIDEBAR_TITLE; + } + + public void addPlayer(Player player) { + ChallengePlayerScoreboard ps = new ChallengePlayerScoreboard(this, player); + playerScoreboards.put(player, ps); + for (ChallengeScoreboardTeam team : teams.values()) { + team.addVisibleForPlayer(ps); + } + } + + public void removePlayer(Player player) { + ChallengePlayerScoreboard old = playerScoreboards.remove(player); + if (old != null) { + old.disable(); + for (ChallengeScoreboardTeam team : teams.values()) { + team.removeVisibleForPlayer(old); + } + } + } + + Collection getPlayerScoreboards() { + return playerScoreboards.values(); + } + + public ChallengePlayerScoreboard getPlayerScoreboard(Player player) { + return playerScoreboards.get(player); + } + + public void setSidebarLine(int line, Component s) { + Preconditions.checkArgument(line >= 0 && line < 15, "line >= 0 && line < 15"); + Preconditions.checkNotNull(s, "s may not be null"); + int oldLength = sidebarLines == null ? 0 : sidebarLines.length; + if (line >= oldLength) { + sidebarLines = sidebarLines == null ? new Component[line + 1] : Arrays.copyOf(sidebarLines, line + 1); + for (int i = oldLength; i < line; i++) { + sidebarLines[i] = Component.empty(); + } + } + sidebarLines[line] = s; + + for (ChallengePlayerScoreboard ps : getPlayerScoreboards()) { + ps.setSidebarLine(line, s); + } + } + + public void limitSidebarLines(int maxlines) { + if (sidebarLines != null) { + sidebarLines = maxlines == 0 ? null : Arrays.copyOf(sidebarLines, maxlines); + } + for (ChallengePlayerScoreboard ps : getPlayerScoreboards()) { + ps.limitSidebarLines(maxlines); + } + } + + public void clearSidebar() { + if (sidebarLines != null) { + sidebarLines = null; + } + sidebarTitle = DEFAULT_SIDEBAR_TITLE; + for (ChallengePlayerScoreboard ps : getPlayerScoreboards()) { + ps.clearSidebar(); + ps.getSidebarObjective().setDisplayName(sidebarTitle); + } + } + + public void setSidebarTitle(String sidebarTitle) { + this.sidebarTitle = sidebarTitle; + for (ChallengePlayerScoreboard ps : getPlayerScoreboards()) { + ps.getSidebarObjective().setDisplayName(sidebarTitle); + } + } + + public String getSidebarTitle() { + return sidebarTitle; + } + + Component[] getSidebarLines() { + return sidebarLines; + } + + public ChallengeScoreboardTeam registerNewTeam(String name) { + Preconditions.checkNotNull(name); + Preconditions.checkArgument(!teams.containsKey(name), "Team " + name + " already exists"); + ChallengeScoreboardTeam team = new ChallengeScoreboardTeam(this, name); + teams.put(name, team); + + return team; + } + + void unregisterTeam(String name) { + teams.remove(name); + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboardTeam.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboardTeam.java new file mode 100644 index 0000000..2116f4e --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ChallengeScoreboardTeam.java @@ -0,0 +1,173 @@ +package de.fanta.challenge.scoreboard; + +import com.google.common.base.Preconditions; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Team; +import org.bukkit.scoreboard.Team.Option; +import org.bukkit.scoreboard.Team.OptionStatus; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map.Entry; + +public class ChallengeScoreboardTeam { + + private ChallengeScoreboard scoreboard; + private final String name; + + private OptionStatus nameTagVisiblity = OptionStatus.ALWAYS; + private boolean canSeeFriendlyInvisibles; + private boolean allowFriendlyFire; + private String prefix; + private ChatColor color = ChatColor.RESET; + private EnumMap options; + private HashSet entries; + + private final HashMap playerTeams; + + public ChallengeScoreboardTeam(ChallengeScoreboard scoreboard, String name) { + this.scoreboard = scoreboard; + this.name = name; + this.options = new EnumMap<>(Option.class); + this.entries = new HashSet<>(); + this.playerTeams = new HashMap<>(); + + for (ChallengePlayerScoreboard ps : scoreboard.getPlayerScoreboards()) { + addVisibleForPlayer(ps); + } + } + + void addVisibleForPlayer(ChallengePlayerScoreboard player) { + Team team = player.getBukkitScoreboard().registerNewTeam(name); + playerTeams.put(player.getPlayer(), team); + + if (prefix != null) { + team.setPrefix(prefix); + } + team.setColor(color); + team.setCanSeeFriendlyInvisibles(canSeeFriendlyInvisibles); + team.setAllowFriendlyFire(allowFriendlyFire); + team.setOption(Option.NAME_TAG_VISIBILITY, nameTagVisiblity); + for (Entry e : options.entrySet()) { + team.setOption(e.getKey(), e.getValue()); + } + for (String e : entries) { + team.addEntry(e); + } + } + + void removeVisibleForPlayer(ChallengePlayerScoreboard player) { + Team old = playerTeams.remove(player.getPlayer()); + if (old != null) { + old.unregister(); + } + } + + public void unregister() { + if (scoreboard != null) { + scoreboard.unregisterTeam(name); + scoreboard = null; + } + + for (Team t : playerTeams.values()) { + t.unregister(); + } + playerTeams.clear(); + } + + public String getName() { + return name; + } + + public void setCanSeeFriendlyInvisibles(boolean canSee) { + canSeeFriendlyInvisibles = canSee; + + for (Team t : playerTeams.values()) { + t.setCanSeeFriendlyInvisibles(canSee); + } + } + + public boolean getCanSeeFriendlyInvisibles() { + return canSeeFriendlyInvisibles; + } + + public void setAllowFriendlyFire(boolean allow) { + allowFriendlyFire = allow; + + for (Team t : playerTeams.values()) { + t.setAllowFriendlyFire(allow); + } + } + + public boolean getAllowFriendlyFire() { + return allowFriendlyFire; + } + + public OptionStatus getNameTagVisiblity() { + return nameTagVisiblity; + } + + public void setNameTagVisiblity(OptionStatus nameTagVisiblity) { + Preconditions.checkNotNull(nameTagVisiblity, "nameTagVisiblity"); + this.nameTagVisiblity = nameTagVisiblity; + + for (Team t : playerTeams.values()) { + t.setOption(Option.NAME_TAG_VISIBILITY, nameTagVisiblity); + } + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + + for (Team t : playerTeams.values()) { + t.setPrefix(prefix); + } + } + + public String getPrefix() { + return prefix; + } + + public void setColor(ChatColor color) { + this.color = color == null ? ChatColor.RESET : color; + + for (Team t : playerTeams.values()) { + t.setColor(color); + } + } + + public ChatColor getColor() { + return color; + } + + public void setOption(Option option, OptionStatus status) { + this.options.put(option, status); + + for (Team t : playerTeams.values()) { + t.setOption(option, status); + } + } + + public void addEntry(String entry) { + this.entries.add(entry); + + for (Team t : playerTeams.values()) { + t.addEntry(entry); + } + } + + public void removeEntry(String entry) { + this.entries.remove(entry); + + for (Team t : playerTeams.values()) { + t.removeEntry(entry); + } + } + + public ArrayList getEntries() { + return new ArrayList<>(this.entries); + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/Scorable.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/Scorable.java deleted file mode 100644 index 8efc73d..0000000 --- a/Challenge/src/main/java/de/fanta/challenge/scoreboard/Scorable.java +++ /dev/null @@ -1,13 +0,0 @@ -package de.fanta.challenge.scoreboard; - -import org.bukkit.scoreboard.Scoreboard; - -public interface Scorable { - - void setScoreboard(Scoreboard scoreboard); - - String getIdentifier(); - - String getName(); - -} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreBoardMananger.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreBoardMananger.java deleted file mode 100644 index 91e199e..0000000 --- a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreBoardMananger.java +++ /dev/null @@ -1,19 +0,0 @@ -package de.fanta.challenge.scoreboard; - -import de.fanta.challenge.teams.ChallengeTeam; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Scoreboard; - -public interface ScoreBoardMananger { - - void initScoreboard(); - void setScoreboardtoPlayer(Player p); - void setScoreboardtoTeam(ChallengeTeam challengeTeam); - void removeScoreboard(Player p); - void removeAllFromScoreboard(); - int countScoreboardPlayers(); - void updateTabHP(); - void updateEventScoreboard(); - void updateEventScore(Scorable s); - Scoreboard getScoreboard(); -} diff --git a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreManager.java b/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreManager.java deleted file mode 100644 index f77cc21..0000000 --- a/Challenge/src/main/java/de/fanta/challenge/scoreboard/ScoreManager.java +++ /dev/null @@ -1,344 +0,0 @@ -package de.fanta.challenge.scoreboard; - -import de.fanta.challenge.Challenge; -import de.fanta.challenge.challenges.ChallengeEvents.SammelFieberChallengeEvent; -import de.fanta.challenge.challenges.ChallengeEvents.TimeChallengeEvent; -import de.fanta.challenge.guis.eventgui.SammelFieberSettingsGui; -import de.fanta.challenge.teams.ChallengeTeam; -import de.fanta.challenge.teams.TeamUtils; -import de.fanta.challenge.utils.Config; -import de.fanta.challengeutils.Color; -import de.iani.cubesideutils.HastebinUtil; -import de.iani.cubesideutils.StringUtil; -import de.iani.playerUUIDCache.CachedPlayer; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.event.ClickEvent; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Team; - -import javax.annotation.Nullable; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.function.IntPredicate; -import java.util.logging.Level; -import java.util.stream.Collectors; - -public class ScoreManager { - - public static class ScoreData { - private final Scorable scorable; - private int score; - private int position; - private int index; - - public ScoreData(Scorable scorable, int index) { - this.scorable = scorable; - this.index = index; - - this.score = 0; - this.position = 1; - } - - public Scorable getScorable() { - return scorable; - } - - public int getPostition() { - return position; - } - - public void setPosition(int position) { - this.position = position; - } - - public int getIndex() { - return index; - } - - public void setIndex(int index) { - this.index = index; - } - - public int getScore() { - return score; - } - - public void setScore(int score) { - this.score = score; - } - - public void changeScore(int difference) { - this.score += difference; - } - } - - private final Challenge plugin; - private final Map scores; - private final List positions; - - public ScoreManager(Challenge plugin) { - this.plugin = plugin; - this.scores = new HashMap<>(); - this.positions = new ArrayList<>(); - } - - public void join(Scorable s) { - if (!scores.containsKey(s)) { - ScoreData data = new ScoreData(s, positions.size()); - scores.put(s, data); - positions.add(data); - } - } - - public void updateScore(Scorable s, int difference) { - if (difference == 0) { - return; - } - - ScoreData data = scores.get(s); - data.changeScore(difference); - - int current = data.getIndex(); - int dir = (int) Math.signum(difference * -1); - - IntPredicate forCondition = (dir == -1) ? curr -> curr > 0 && positions.get(curr - 1).getScore() < data.getScore() : curr -> curr < positions.size() - 1 && positions.get(curr + 1).getScore() > data.getScore(); - - int startingIndex = data.getIndex(); - - // swap with neighbors as long as we are now better/worse then them - for (; forCondition.test(current); current += dir) { - ScoreData other = positions.get(current + dir); - - positions.set(current + dir, data); - positions.set(current, other); - data.setIndex(current + dir); - other.setIndex(current); - } - - // update positions - int endIndex = data.getIndex(); - int i = Math.min(startingIndex, endIndex); - - ScoreData curr; - int lastPosition; - int lastScore; - if (i == 0) { - curr = positions.getFirst(); - curr.setPosition(1); - lastPosition = 1; - lastScore = curr.getScore(); - i++; - } else { - curr = positions.get(i - 1); - lastPosition = curr.getPostition(); - lastScore = curr.getScore(); - } - - for (; i < positions.size(); i++) { - curr = positions.get(i); - int correctPosition = (curr.getScore() == lastScore) ? lastPosition : lastPosition + 1; - if (curr.getPostition() == correctPosition && i > Math.max(startingIndex, endIndex)) { - break; - } - - curr.setPosition(correctPosition); - lastPosition = correctPosition; - lastScore = curr.getScore(); - } - - this.plugin.getSBManager().updateEventScore(s); - } - - public void setScore(Scorable s, int score) { - int diff = score - getScore(s); - updateScore(s, diff); - } - - public int getScore(Scorable s) { - return scores.get(s).getScore(); - } - - public int getPosition(Scorable s) { - return scores.get(s).getPostition(); - } - - public Set getByPositon(int position) { - if (positions.isEmpty() || positions.getLast().getPostition() < position) { - return Collections.emptySet(); - } - - int start = position - 1; - int end = positions.size(); - - int found; - while (true) { - int middle = start + (end - start) / 2; - ScoreData current = positions.get(middle); - if (current.getPostition() == position) { - found = middle; - break; - } else if (start >= end - 1) { - plugin.getLogger().log(Level.SEVERE, "position not found but expected to be present: " + position); - plugin.getLogger().log(Level.SEVERE, positions.toString()); - return Collections.emptySet(); - } else if (current.getPostition() > position) { - end = middle; - } else { - start = middle; - } - } - - start = end = found; - for (; start > 0 && positions.get(start - 1).getPostition() == position; start--) { - } - for (; end < positions.size() - 2 && positions.get(end + 1).getPostition() == position; end++) { - } - - return positions.subList(start, end + 1).stream().map(ScoreData::getScorable).collect(Collectors.toSet()); - } - - public void saveScores(@Nullable Player player) { - saveScores(player, 0); - } - - public void saveScores(@Nullable Player player, int minScore) { - StringBuilder sb = new StringBuilder(); - String ownerName = player != null ? player.getName() : "Console"; - SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss"); - Date currentTime = new Date(); - - sb.append("Challenges Event -> ").append(StringUtil.capitalizeFirstLetter(Config.getString("event.type"), false)).append('\n'); - sb.append("=".repeat(20)).append('\n'); - sb.append("Erstellt von: ").append(ownerName).append('\n'); - sb.append("Erstellt am: ").append(formatter.format(currentTime)).append('\n'); - sb.append("Timer: ").append(plugin.getTimer().formatTime()).append('\n'); - if (Objects.equals(Config.getString("event.type"), "sammelfieber")) { - if (SammelFieberSettingsGui.getEventItem() != null) { - sb.append("Item: ").append(SammelFieberSettingsGui.getEventItem().getType().name()).append('\n'); - sb.append("Cubes pro Item: ").append(SammelFieberSettingsGui.MONEY).append('\n'); - sb.append("Items abgegeben: ").append(SammelFieberChallengeEvent.getCount()).append('\n'); - sb.append("Cubes gesammt: ").append(SammelFieberSettingsGui.MONEY * SammelFieberChallengeEvent.getCount()).append('\n'); - sb.append("Cubes pro Spieler: ").append(SammelFieberSettingsGui.MONEY * SammelFieberChallengeEvent.getCount() / scores.size()).append('\n'); - } - } - sb.append("=".repeat(20)).append('\n'); - sb.append("Teilnehmer (").append(this.scores.size()).append("):\n"); - - if (!Objects.equals(Config.getString("event.type"), "time")) { - if (this.scores.isEmpty()) { - sb.append(" Das Event hatte keine Teilnehmer!\n"); - } else { - if (Config.getBoolean("event.teams")) { - for (ScoreData entry : positions) { - ChallengeTeam challengeTeam = TeamUtils.getTeam(entry.getScorable().getName()); - if (challengeTeam != null) { - Team team = TeamUtils.getScoreboard().getTeam(challengeTeam.getName()); - if (team != null) { - sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" (").append(team.getEntries().toString().replace("[", "").replace("]", "")).append(")").append(" ").append(entry.getScore()).append("\n"); - } - } - } - } else { - if (Config.getBoolean("event.tournament")) { - HashMap tournamentScores = getTournamentScores(new ArrayList<>(positions), minScore); - for (ScoreData entry : positions) { - sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" ").append(entry.getScore()).append(" (").append(tournamentScores.getOrDefault(entry.getScorable(), 0)).append(")").append("\n"); - } - } else { - for (ScoreData entry : positions) { - sb.append(entry.getPostition()).append(". ").append(entry.getScorable().getName()).append(" ").append(entry.getScore()).append("\n"); - } - } - } - } - } else { - HashMap times = TimeChallengeEvent.getPlayerPlayTimes(); - for (UUID uuid : times.keySet()) { - CachedPlayer cp = plugin.getPlayerUUIDCache().getPlayer(uuid); - sb.append(cp != null ? cp.getName() : uuid.toString()).append(": ").append(formatTime(times.get(uuid))).append("\n"); - } - } - - HastebinUtil.paste(sb.toString(), new HastebinUtil.PasteCompletedListener() { - @Override - public void onSuccess(String url) { - if (player != null) { - plugin.getComponentUtil().sendMessage(player, Component.text("Event Log gepastet: ", Color.GREEN).append(Component.text(url, Color.YELLOW).clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, url)))); - } - plugin.getLogger().log(Level.SEVERE, "Event Log gepastet: " + url); - } - - @Override - public void onError(Exception e) { - if (player != null) { - plugin.getComponentUtil().sendErrorMessage(player, "Paste konnte nicht erstellt werden"); - } - plugin.getLogger().log(Level.SEVERE, "Could not paste event log", e); - plugin.getLogger().log(Level.SEVERE, "Log Score String", sb.toString()); - } - }); - } - - public void resetScores() { - this.scores.clear(); - plugin.getSBManager().updateEventScoreboard(); - } - - public Map getScores() { - return scores; - } - - public List getPositions() { - return positions; - } - - public HashMap getTournamentScores(List scoreDataList, int minScore) { - HashMap tournamentScores = new HashMap<>(); - List newScoreDataList = new ArrayList<>(); - - for (ScoreData scoreData : scoreDataList) { - int score = scoreData.getScore(); - if (score >= minScore) { - newScoreDataList.add(scoreData); - } - } - - - int length = newScoreDataList.size(); - if (length > 0) { - int lastPostition = newScoreDataList.get(length - 1).getPostition() - 1; - int threePoints = Math.round((lastPostition + 1 - 3) / 3.0f + 3); - int twoPoints = Math.round((lastPostition + 1 - 3) / 3.0f * 2 + 3); - for (ScoreData scoreData : newScoreDataList) { - Scorable scorable = scoreData.getScorable(); - int pos = scoreData.getPostition() - 1; - if (pos < 3) { - tournamentScores.put(scorable, 6 - pos); - } else if (pos < threePoints) { - tournamentScores.put(scorable, 3); - } else if (pos < twoPoints) { - tournamentScores.put(scorable, 2); - } else { - tournamentScores.put(scorable, 1); - } - } - } - return tournamentScores; - } - - public String formatTime(long time) { - String formattime = StringUtil.formatTimespan((time / 1000) * 1000, " Tage, ", ":", "", "", "", ":", false, true); - if (formattime.startsWith("1 Tage")) { - return StringUtil.formatTimespan((time / 1000) * 1000, " Tag, ", ":", "", "", "", ":", false, true); - } - return formattime; - } -} diff --git a/Challenge/src/main/java/de/fanta/challenge/teams/ChallengeTeam.java b/Challenge/src/main/java/de/fanta/challenge/teams/ChallengeTeam.java index 179342c..19d541d 100644 --- a/Challenge/src/main/java/de/fanta/challenge/teams/ChallengeTeam.java +++ b/Challenge/src/main/java/de/fanta/challenge/teams/ChallengeTeam.java @@ -2,7 +2,7 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.guis.BackpackGui; -import de.fanta.challenge.scoreboard.Scorable; +import de.fanta.challenge.score.Scorable; import de.fanta.challenge.utils.Config; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; diff --git a/Challenge/src/main/java/de/fanta/challenge/teams/TeamUtils.java b/Challenge/src/main/java/de/fanta/challenge/teams/TeamUtils.java index 54690af..96368ab 100644 --- a/Challenge/src/main/java/de/fanta/challenge/teams/TeamUtils.java +++ b/Challenge/src/main/java/de/fanta/challenge/teams/TeamUtils.java @@ -183,7 +183,8 @@ } public static void createScoreBoardTeams() { - if (Challenge.getPlugin().getSBManager().getScoreboard() instanceof Scoreboard currentScore) { + //TODO SCOREBORD + /*if (Challenge.getPlugin().getSBManager().getScoreboard() instanceof Scoreboard currentScore) { scoreboard = currentScore; if (teamscoreboardObjective == null) { teamscoreboardObjective = scoreboard.registerNewObjective("teams", Criteria.DUMMY, Component.text("Event")); @@ -203,7 +204,7 @@ } } } - } + }*/ } public static void selectTeam(Player player, ChallengeTeam team) { @@ -234,7 +235,7 @@ scoreboard.getTeam(team.getName()).addPlayer(player); TeamSelectGUI.updateTeamSelectGui(); - Challenge.getPlugin().getSBManager().setScoreboardtoTeam(team); + //TODO SCOREBORDChallenge.getPlugin().getSBManager().setScoreboardtoTeam(team); } public static void setAllPlayerWithoutTeamToTeam() { diff --git a/Challenge/src/main/java/de/fanta/challenge/utils/CustomFontUtil.java b/Challenge/src/main/java/de/fanta/challenge/utils/CustomFontUtil.java new file mode 100644 index 0000000..6b81ed9 --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/utils/CustomFontUtil.java @@ -0,0 +1,9 @@ +package de.fanta.challenge.utils; + +public class CustomFontUtil { + public static String deathRunLogo = "ꚥ"; + public static String bootsIcon = "ꚷ"; + public static String starIcon = "ꚴ"; + public static String cupIcon = "ꚶ"; + public static String deathSkullIcon = "ꚵ"; +} diff --git a/Challenge/src/main/java/de/fanta/challenge/utils/MinecraftTextUtils.java b/Challenge/src/main/java/de/fanta/challenge/utils/MinecraftTextUtils.java new file mode 100644 index 0000000..3d424ea --- /dev/null +++ b/Challenge/src/main/java/de/fanta/challenge/utils/MinecraftTextUtils.java @@ -0,0 +1,125 @@ +package de.fanta.challenge.utils; + +import java.util.HashMap; +import java.util.Map; + +public class MinecraftTextUtils { + + private static final Map charWidths = new HashMap<>(); + + static { + charWidths.put('A', 5); + charWidths.put('B', 5); + charWidths.put('C', 5); + charWidths.put('D', 5); + charWidths.put('E', 5); + charWidths.put('F', 5); + charWidths.put('G', 5); + charWidths.put('H', 5); + charWidths.put('I', 3); + charWidths.put('J', 5); + charWidths.put('K', 5); + charWidths.put('L', 5); + charWidths.put('M', 5); + charWidths.put('N', 5); + charWidths.put('O', 5); + charWidths.put('P', 5); + charWidths.put('Q', 5); + charWidths.put('R', 5); + charWidths.put('S', 5); + charWidths.put('T', 5); + charWidths.put('U', 5); + charWidths.put('V', 5); + charWidths.put('W', 5); + charWidths.put('X', 5); + charWidths.put('Y', 5); + charWidths.put('Z', 5); + charWidths.put('a', 4); + charWidths.put('b', 4); + charWidths.put('c', 4); + charWidths.put('d', 4); + charWidths.put('e', 4); + charWidths.put('f', 3); + charWidths.put('g', 4); + charWidths.put('h', 4); + charWidths.put('i', 2); + charWidths.put('j', 3); + charWidths.put('k', 4); + charWidths.put('l', 2); + charWidths.put('m', 5); + charWidths.put('n', 4); + charWidths.put('o', 4); + charWidths.put('p', 4); + charWidths.put('q', 4); + charWidths.put('r', 3); + charWidths.put('s', 4); + charWidths.put('t', 3); + charWidths.put('u', 4); + charWidths.put('v', 4); + charWidths.put('w', 5); + charWidths.put('x', 4); + charWidths.put('y', 4); + charWidths.put('z', 4); + charWidths.put('0', 5); + charWidths.put('1', 3); + charWidths.put('2', 5); + charWidths.put('3', 5); + charWidths.put('4', 5); + charWidths.put('5', 5); + charWidths.put('6', 5); + charWidths.put('7', 5); + charWidths.put('8', 5); + charWidths.put('9', 5); + + charWidths.put(' ', 3); + charWidths.put('!', 2); + charWidths.put('"', 4); + charWidths.put('#', 5); + charWidths.put('$', 5); + charWidths.put('%', 5); + charWidths.put('&', 5); + charWidths.put('\'', 2); + charWidths.put('(', 3); + charWidths.put(')', 3); + charWidths.put('*', 5); + charWidths.put('+', 5); + charWidths.put(',', 2); + charWidths.put('-', 4); + charWidths.put('.', 2); + charWidths.put('/', 3); + charWidths.put(':', 2); + charWidths.put(';', 2); + charWidths.put('<', 5); + charWidths.put('=', 5); + charWidths.put('>', 5); + charWidths.put('?', 5); + charWidths.put('@', 5); + charWidths.put('[', 3); + charWidths.put('\\', 3); + charWidths.put(']', 3); + charWidths.put('^', 5); + charWidths.put('_', 5); + charWidths.put('`', 3); + charWidths.put('{', 4); + charWidths.put('|', 2); + charWidths.put('}', 4); + charWidths.put('~', 5); + + charWidths.put('ä', 4); + charWidths.put('ö', 4); + charWidths.put('ü', 4); + charWidths.put('ß', 5); + } + + public static int getCharWidth(char c) { + return charWidths.getOrDefault(c, 4); + } + + public static int getTextWidth(String text) { + int width = 0; + for (char c : text.toCharArray()) { + width += getCharWidth(c); + } + return width; + } +} diff --git a/Challenge/src/main/java/de/fanta/challenge/utils/SaveWorldUtils.java b/Challenge/src/main/java/de/fanta/challenge/utils/SaveWorldUtils.java index e94f082..e690e77 100644 --- a/Challenge/src/main/java/de/fanta/challenge/utils/SaveWorldUtils.java +++ b/Challenge/src/main/java/de/fanta/challenge/utils/SaveWorldUtils.java @@ -60,11 +60,7 @@ } isSavingWorld = true; plugin.getLogger().info("Start Saving"); - plugin.getServerConfig().set("saveTime", System.currentTimeMillis()); - plugin.saveServerConfig(); - Config.setValue("timertime", Challenge.getPlugin().getTimer().getTime()); - Config.setValue("backpack_size", Challenge.getPlugin().getBackpack().getSize() / 9); - Challenge.getPlugin().getBackpack().saveInventoryToConfig(); + saveConfigs(); plugin.getLogger().info("Save Player Data"); for (Player p : Bukkit.getOnlinePlayers()) { @@ -84,6 +80,19 @@ } } + public static void saveConfigs() { + plugin.getServerConfig().set("saveTime", System.currentTimeMillis()); + plugin.saveServerConfig(); + Config.setValue("timertime", Challenge.getPlugin().getTimer().getTime()); + Config.setValue("timermode", Challenge.getPlugin().getTimer().getMode().toString()); + if (Challenge.getPlugin().getTimer().getTargetDateTimestamp() != null) { + Config.setValue("timerdate", Challenge.getPlugin().getTimer().getTargetDateTimestamp()); + } + + Config.setValue("backpack_size", Challenge.getPlugin().getBackpack().getSize() / 9); + Challenge.getPlugin().getBackpack().saveInventoryToConfig(); + } + private static void copyWorldAsync(Player player, String saveID, SaveSlot saveSlot) { File dir = new File(saveID); File configs = new File("plugins/Challenge"); @@ -147,7 +156,7 @@ plugin.getLogger().info("isServerRestartRequested: " + isServerRestartRequested); if (isServerRestartRequested) { - restartServerInternal(restartSeed); + restartServerInternal(restartSeed, true); } else if (restart) { Config.setValue("World_Reset", true); Bukkit.shutdown(); @@ -169,7 +178,7 @@ } } - public static void restartServer(@Nullable String seed) { + public static void restartServer(@Nullable String seed, boolean reset) { plugin.getLogger().info("run restart server"); if (plugin.isWaitingForShutdown()) { return; @@ -180,11 +189,11 @@ isServerRestartRequested = true; } else { plugin.getLogger().info("run restart server else"); - restartServerInternal(seed); + restartServerInternal(seed, reset); } } - private static void restartServerInternal(@Nullable String seed) { + private static void restartServerInternal(@Nullable String seed, boolean reset) { plugin.setWaitingForShutdown(true); Bukkit.getPluginManager().callEvent(new EventStatusChangedEvent(false)); @@ -195,16 +204,21 @@ plugin.portPlayerToLobby(p); } - Config.setValue("editsettings", true, false); + if (reset) { + Config.setValue("editsettings", true, false); - setSeedInServerProperties(seed); + setSeedInServerProperties(seed); - plugin.getTimer().stopTimer(); + for (String key : Config.getConfigurationSection("Saved_Locations").getKeys(false)) { + Config.setValue("Saved_Locations." + key, null, false); + } - for (String key : Config.getConfigurationSection("Saved_Locations").getKeys(false)) { - Config.setValue("Saved_Locations." + key, null, false); + if (Config.getBoolean("event.enabled")) { + Config.setValue("event.enabled", false); + } } + plugin.getTimer().stopTimer(); plugin.saveConfig(); plugin.getBackpack().saveInventoryToConfig(); @@ -212,7 +226,8 @@ restart = true; SaveWorldUtils.saveWorld(plugin.getFirstEditor().getUniqueId().toString(), SaveSlot.SLOT_AUTO); } else { - Config.setValue("World_Reset", true); + restart = true; + Config.setValue("World_Reset", reset); Bukkit.shutdown(); } } diff --git a/Challenge/src/main/java/de/fanta/challenge/utils/Statistics.java b/Challenge/src/main/java/de/fanta/challenge/utils/Statistics.java index ae40121..9900237 100644 --- a/Challenge/src/main/java/de/fanta/challenge/utils/Statistics.java +++ b/Challenge/src/main/java/de/fanta/challenge/utils/Statistics.java @@ -2,8 +2,13 @@ import de.fanta.challenge.Challenge; import de.fanta.challenge.ServerType; +import de.fanta.challenge.challenges.ChallengeEvents.DeathrunChallengeEventMonth; +import de.fanta.challenge.score.ChallengePlayer; +import de.fanta.challenge.score.ScoreManager; import de.iani.cubesidestats.api.CubesideStatisticsAPI; +import de.iani.cubesidestats.api.Ordering; import de.iani.cubesidestats.api.StatisticKey; +import de.iani.cubesidestats.api.TimeFrame; import java.util.UUID; @@ -26,6 +31,12 @@ private final StatisticKey challengeWeekStats; + + private final StatisticKey deathRunTotalScore; + private final StatisticKey deathRunCurrentRunScore; + private final StatisticKey deathRunBestRunScore; + private final StatisticKey deathRunDeathScore; + public Statistics(Challenge plugin) { this.plugin = plugin; statistics = plugin.getCubesideStatistics(); @@ -72,6 +83,77 @@ challengeWeekStats = statistics.getStatisticKey("challenge.challengeweek"); challengeWeekStats.setDisplayName("Beste Spieler Challenge Woche"); challengeWeekStats.setIsMonthlyStats(false); + + deathRunTotalScore = statistics.getStatisticKey("deathrun.totalscore"); + deathRunTotalScore.setDisplayName("Deathrun Monat"); + deathRunTotalScore.setIsMonthlyStats(true); + + deathRunCurrentRunScore = statistics.getStatisticKey("deathrun.currentrunscore"); + deathRunCurrentRunScore.setDisplayName("Deathrun Monat aktueller Versuch"); + deathRunCurrentRunScore.setIsMonthlyStats(true); + + deathRunBestRunScore = statistics.getStatisticKey("deathrun.bestscore"); + deathRunBestRunScore.setDisplayName("Deathrun Monat bester Versuch"); + deathRunBestRunScore.setIsMonthlyStats(true); + + deathRunDeathScore = statistics.getStatisticKey("deathrun.deathscore"); + deathRunDeathScore.setDisplayName("Deathrun Monat Tode"); + deathRunDeathScore.setIsMonthlyStats(true); + } + + public void setDeathrunTotaleStats(UUID uuid, int points) { + statistics.getStatistics(uuid).setScore(deathRunTotalScore, points); + } + + public void setAllTotaleScores() { + StatisticKey key = statistics.getStatisticKey("deathrun.totalscore"); + ScoreManager manager = plugin.getScoreManager(); + key.getTop(0, 10000, Ordering.ASCENDING, TimeFrame.MONTH, playerWithScores -> playerWithScores.forEach(playerWithScore -> { + ChallengePlayer cp = new ChallengePlayer(playerWithScore.getPlayer().getOwner()); + manager.join(cp); + manager.setScore(cp, playerWithScore.getScore()); + plugin.getLogger().severe("setAllTotaleScores: " + playerWithScore.getPlayer().getOwner() + " " + playerWithScore.getScore()); + })); + } + + public void setDeathrunCurrentStats(UUID uuid, int points) { + statistics.getStatistics(uuid).setScore(deathRunCurrentRunScore, points); + } + + public void setAllCurrentRunScores() { + StatisticKey key = statistics.getStatisticKey("deathrun.currentrunscore"); + key.getTop(0, 10000, Ordering.ASCENDING, TimeFrame.MONTH, playerWithScores -> playerWithScores.forEach(playerWithScore -> { + UUID uuid = playerWithScore.getPlayer().getOwner(); + DeathrunChallengeEventMonth.setCurrentRunScore(uuid, playerWithScore.getScore()); + })); + } + + public void resetDeathrunCurrentStats(UUID uuid) { + statistics.getStatistics(uuid).setScore(deathRunCurrentRunScore, 0); + } + + public void setDeathrunBestRunStats(UUID uuid, int points) { + statistics.getStatistics(uuid).setScore(deathRunBestRunScore, points); + } + + public void setAllBestRunScores() { + StatisticKey key = statistics.getStatisticKey("deathrun.bestscore"); + key.getTop(0, 10000, Ordering.ASCENDING, TimeFrame.MONTH, playerWithScores -> playerWithScores.forEach(playerWithScore -> { + UUID uuid = playerWithScore.getPlayer().getOwner(); + DeathrunChallengeEventMonth.setBestRunScore(uuid, playerWithScore.getScore()); + })); + } + + public void increaseDeathrunDeathStats(UUID uuid) { + statistics.getStatistics(uuid).increaseScore(deathRunDeathScore, 1); + } + + public void setAllDeathScores() { + StatisticKey key = statistics.getStatisticKey("deathrun.deathscore"); + key.getTop(0, 10000, Ordering.ASCENDING, TimeFrame.MONTH, playerWithScores -> playerWithScores.forEach(playerWithScore -> { + UUID uuid = playerWithScore.getPlayer().getOwner(); + DeathrunChallengeEventMonth.setDeathScore(uuid, playerWithScore.getScore()); + })); } public void increaseChallengeWeekStats(UUID uuid, int points) { diff --git a/Challenge/src/main/resources/plugin.yml b/Challenge/src/main/resources/plugin.yml index c844dcd..cbd9599 100644 --- a/Challenge/src/main/resources/plugin.yml +++ b/Challenge/src/main/resources/plugin.yml @@ -38,6 +38,9 @@ usage: Benutze /Reset aliases: - stop + restartserver: + description: Startet server Neu ohne welt zu löschen + usage: Benutze /restart forcemlg: description: Triggert einen MLG usage: Use /forcemlg diff --git a/Lobby/src/main/java/de/fanta/lobby/commands/ChallengesCommand/ChallengeSetStatsCommand.java b/Lobby/src/main/java/de/fanta/lobby/commands/ChallengesCommand/ChallengeSetStatsCommand.java index bac47ab..f6eed20 100644 --- a/Lobby/src/main/java/de/fanta/lobby/commands/ChallengesCommand/ChallengeSetStatsCommand.java +++ b/Lobby/src/main/java/de/fanta/lobby/commands/ChallengesCommand/ChallengeSetStatsCommand.java @@ -80,9 +80,7 @@ if (args.remaining() == 2) { Collection keyList = new ArrayList<>(); for (StatisticKey statisticKey : plugin.getCubesideStatistics().getAllStatisticKeys()) { - if (statisticKey.getName().startsWith("challenge")) { - keyList.add(statisticKey.getName()); - } + keyList.add(statisticKey.getName()); } return keyList; }