From 608528fba124864a12af3025b6f7bc7d4f7fa54a Mon Sep 17 00:00:00 2001 From: Theo Gastinel Date: Fri, 9 Oct 2026 21:59:28 +0200 Subject: [PATCH] GastinelTpa 1.2.0 : /tpacancel, homes (/sethome /home /delhome /homes), protection 15 s apres /rtp, message de mort prive Co-Authored-By: Claude Sonnet 5.5 --- README.md | 6 +- envoyer-et-compiler.sh | 2 +- gradle.properties | 2 +- .../java/com/gastineltpa/ClaimsBridge.java | 27 ++ .../java/com/gastineltpa/GastinelTpa.java | 5 +- .../java/com/gastineltpa/HomesCommands.java | 321 ++++++++++++++++++ src/main/java/com/gastineltpa/MortEvents.java | 50 +++ .../java/com/gastineltpa/ProtectionRtp.java | 80 +++++ .../com/gastineltpa/SpawnRtpCommands.java | 18 +- src/main/java/com/gastineltpa/TpConfig.java | 20 ++ .../java/com/gastineltpa/TpaCommands.java | 43 +++ .../java/com/gastineltpa/core/HomeBook.java | 81 +++++ .../java/com/gastineltpa/core/HomeStore.java | 92 +++++ .../com/gastineltpa/core/Protections.java | 62 ++++ .../java/com/gastineltpa/core/Textes.java | 28 ++ .../com/gastineltpa/core/TpaRegistry.java | 27 ++ .../resources/META-INF/neoforge.mods.toml | 2 +- .../gastineltpa/core/Nouveautes120Test.java | 241 +++++++++++++ 18 files changed, 1098 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/gastineltpa/HomesCommands.java create mode 100644 src/main/java/com/gastineltpa/MortEvents.java create mode 100644 src/main/java/com/gastineltpa/ProtectionRtp.java create mode 100644 src/main/java/com/gastineltpa/core/HomeBook.java create mode 100644 src/main/java/com/gastineltpa/core/HomeStore.java create mode 100644 src/main/java/com/gastineltpa/core/Protections.java create mode 100644 src/main/java/com/gastineltpa/core/Textes.java create mode 100644 src/test/java/com/gastineltpa/core/Nouveautes120Test.java diff --git a/README.md b/README.md index 3454072..01a62ff 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ Téléportations pour NeoForge 1.21.1 (21.1.234). **Mod côté serveur uniquemen - `/rtp` : endroit aléatoire dans la zone **déjà générée**, jamais de nouveau chunk. Délai 3 s (annulable), recharge 300 s. Atterrissage sûr : sol solide, pas d'eau (ni profonde à côté), pas de lave/feu/magma/cactus/baies/neige poudreuse/stalactite/rose du wither autour, pas de falaise > 3 blocs, pas sur les feuilles. Évite les claims GastinelClaims des autres (par réflexion, sans dépendance). - `/rtp spawn [joueurs]` : **blocs de commande uniquement** (plaque de pression de l'entrée) ; joueur ou console -> refus avec un message clair. Sans argument : le joueur le plus proche du bloc (4 blocs). Choisit un « beau spot » de `beaux-spots.json` parmi les N meilleurs, tirage pondéré par le score (repli sur la zone /rtp si fichier absent). - `/rtp diagnostic [spawn]` (op 2) : cherche un point comme /rtp sans téléporter personne et affiche les motifs de rejet. `/rtp recharger` (op 2) : relit `beaux-spots.json`. +- `/tpacancel [joueur]` : annule la dernière demande /tpa ou /tpahere envoyée (ou celle vers ce joueur) ; la cible est prévenue. +- `/sethome [nom]`, `/home [nom]`, `/delhome [nom]`, `/homes` : 3 homes par joueur (`homes.maximum`). Nom = lettres sans accent, chiffres, tiret (16 max, insensible à la casse) ; sans nom, premier libre parmi 1, 2, 3. Refusé dans un chunk claimé par un autre (ami autorisé), dans une zone protégée de GastinelClaims (spawn) et hors Overworld/Nether/End. `/home` : même délai que /spawn, annulé si on bouge ou est blessé ; l'arrivée est vérifiée (pas de bloc plein, lave, feu, vide). Fichier : `/gastineltpa-homes.json` (écriture atomique). +- Protection après /rtp et /rtp spawn : `rtp.protectionSecondes` (15), invulnérable sauf vide et /kill, arrêtée si le joueur attaque (`rtp.protectionFinSiAttaque`). +- Message de mort privé « Tu es mort en X Y Z (Overworld). » (cliquable : copie les coordonnées), envoyé à la réapparition. ## Comment /rtp évite toute génération Un point n'est examiné que si le chunk **et ses 8 voisins** sont déjà chargés, ou présents sur le disque avec le statut `minecraft:full` (lecture asynchrone du NBT). Fichier région absent -> pas lu du tout (sinon Minecraft crée un `r.X.Z.mca` vide). Charger un chunk dont un voisin manque créerait un proto-chunk voisin pour l'éclairage, d'où la règle des voisins. Vérifié sur une copie du monde : 115 925 chunks avant/après, aucun fichier créé. @@ -19,4 +23,4 @@ Un point n'est examiné que si le chunk **et ses 8 voisins** sont déjà chargé `outils/beaux_spots.py` (+ `nbt_anvil.py`, `beaux-spots-config.json`) : lit une **copie** des fichiers région (jamais le monde en service), note chaque chunk complet (relief, vue, eau 5-30 %, végétation, variété/rareté des biomes, Terralith, sûreté ; pénalités océan profond, désert plat, danger), garde 300 spots espacés d'au moins 96 blocs, score 0-10. Lancer sur cornafserver : `nice -n 19 python3 -I beaux_spots.py --monde --config beaux-spots-config.json --sortie beaux-spots.json` (82 s pour 89 397 chunks). Limite : les scores saturent près de 10 en tête (42 spots ≥ 9,5), le tirage pondéré du top 60 est donc presque uniforme. ## Build (sur cornafserver) -`sh envoyer-et-compiler.sh` depuis le PC, ou `sh build-sur-cornafserver.sh` sur le serveur (JDK 21 jetable, `nice`, 4 Go max). Tests JUnit (`core/`) puis `build/libs/gastineltpa-neoforge-1.21.1-1.1.1.jar`. +`sh envoyer-et-compiler.sh` depuis le PC, ou `sh build-sur-cornafserver.sh` sur le serveur (JDK 21 jetable, `nice`, 4 Go max). Tests JUnit (`core/`) puis `build/libs/gastineltpa-neoforge-1.21.1-1.2.0.jar`. diff --git a/envoyer-et-compiler.sh b/envoyer-et-compiler.sh index 4a5fd96..34c3c3c 100644 --- a/envoyer-et-compiler.sh +++ b/envoyer-et-compiler.sh @@ -6,5 +6,5 @@ tar czf /tmp/gastineltpa-src.tgz --exclude=build --exclude=.gradle --exclude=bui scp /tmp/gastineltpa-src.tgz cornafserver:gastineltpa-src.tgz ssh cornafserver 'set -e; rm -rf "$HOME/staging/GastinelTpa"; mkdir -p "$HOME/staging/GastinelTpa"; tar xzf "$HOME/gastineltpa-src.tgz" -C "$HOME/staging/GastinelTpa"; rm "$HOME/gastineltpa-src.tgz"; cd "$HOME/staging/GastinelTpa" && sh build-sur-cornafserver.sh' mkdir -p build-out -scp 'cornafserver:staging/GastinelTpa/build/libs/gastineltpa-neoforge-1.21.1-1.1.1.jar' build-out/ +scp 'cornafserver:staging/GastinelTpa/build/libs/gastineltpa-neoforge-1.21.1-1.2.0.jar' build-out/ ls -l build-out diff --git a/gradle.properties b/gradle.properties index 9075378..5ed80e4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ org.gradle.jvmargs=-Xmx2G org.gradle.parallel=true -mod_version=1.1.1 +mod_version=1.2.0 mod_group_id=com.gastineltpa mod_id=gastineltpa diff --git a/src/main/java/com/gastineltpa/ClaimsBridge.java b/src/main/java/com/gastineltpa/ClaimsBridge.java index 101f302..86dbd8d 100644 --- a/src/main/java/com/gastineltpa/ClaimsBridge.java +++ b/src/main/java/com/gastineltpa/ClaimsBridge.java @@ -51,4 +51,31 @@ final class ClaimsBridge { return true; } } + + private static boolean zonesInit; + private static Method zoneDe; + + /** Zones protégées (spawn…) de GastinelClaims : vrai si la position est dans l'une d'elles. Absent = faux. */ + static boolean zoneProtegee(net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) { + synchronized (ClaimsBridge.class) { + if (!zonesInit) { + zonesInit = true; + if (ModList.get().isLoaded("gastinelclaims")) { + try { + Class zp = Class.forName("com.gastinelclaims.ZonesProtegees"); + zoneDe = zp.getMethod("zoneDe", net.minecraft.world.level.Level.class, net.minecraft.core.BlockPos.class); + } catch (ReflectiveOperationException e) { + GastinelTpa.LOGGER.warn("[GastinelTpa] API des zones protégées de GastinelClaims introuvable : " + + "/sethome ne peut pas refuser la zone de spawn ({}).", e.toString()); + } + } + } + } + if (zoneDe == null) return false; + try { + return zoneDe.invoke(null, level, pos) != null; + } catch (ReflectiveOperationException | RuntimeException e) { + return false; + } + } } diff --git a/src/main/java/com/gastineltpa/GastinelTpa.java b/src/main/java/com/gastineltpa/GastinelTpa.java index 9fc95a5..9b40866 100644 --- a/src/main/java/com/gastineltpa/GastinelTpa.java +++ b/src/main/java/com/gastineltpa/GastinelTpa.java @@ -19,6 +19,9 @@ public class GastinelTpa { modContainer.registerConfig(ModConfig.Type.SERVER, TpConfig.SPEC); NeoForge.EVENT_BUS.register(TpaCommands.class); NeoForge.EVENT_BUS.register(SpawnRtpCommands.class); - LOGGER.info("[GastinelTpa] Téléportations chargées (/tpa, /spawn, /rtp)."); + NeoForge.EVENT_BUS.register(HomesCommands.class); + NeoForge.EVENT_BUS.register(ProtectionRtp.class); + NeoForge.EVENT_BUS.register(MortEvents.class); + LOGGER.info("[GastinelTpa] Téléportations chargées (/tpa, /tpacancel, /spawn, /rtp, /home)."); } } diff --git a/src/main/java/com/gastineltpa/HomesCommands.java b/src/main/java/com/gastineltpa/HomesCommands.java new file mode 100644 index 0000000..494340d --- /dev/null +++ b/src/main/java/com/gastineltpa/HomesCommands.java @@ -0,0 +1,321 @@ +package com.gastineltpa; + +import com.gastineltpa.core.HomeBook; +import com.gastineltpa.core.HomeBook.Home; +import com.gastineltpa.core.HomeStore; +import com.gastineltpa.core.Textes; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.event.server.ServerStartedEvent; + +import java.io.IOException; +import java.util.Set; + +/** /sethome [nom], /home [nom], /delhome [nom], /homes. Stockage : /gastineltpa-homes.json. */ +public final class HomesCommands { + + private static final String PREFIXE = "[Home] "; + /** Blocs qui blessent quand on se tient dedans ou dessus. */ + private static final Set DANGER = Set.of("minecraft:fire", "minecraft:soul_fire", "minecraft:magma_block", + "minecraft:cactus", "minecraft:sweet_berry_bush", "minecraft:campfire", "minecraft:soul_campfire", + "minecraft:powder_snow", "minecraft:pointed_dripstone", "minecraft:wither_rose"); + + private static volatile HomeStore store; + + private HomesCommands() {} + + @SubscribeEvent + public static void onStarted(ServerStartedEvent event) { + charger(event.getServer()); + } + + private static synchronized HomeStore store(MinecraftServer server) { + if (store == null) charger(server); + return store; + } + + private static synchronized void charger(MinecraftServer server) { + HomeStore s = new HomeStore(server.getWorldPath(LevelResource.ROOT).resolve("gastineltpa-homes.json")); + try { + s.charger(); + } catch (IOException e) { + GastinelTpa.LOGGER.error("[GastinelTpa] Homes : {}", e.toString()); + } + store = s; + } + + private static boolean sauver(CommandContext ctx) { + try { + store.sauver(); + return true; + } catch (IOException e) { + GastinelTpa.LOGGER.error("[GastinelTpa] Écriture des homes impossible : {}", e.toString()); + echec(ctx, "Impossible d'enregistrer ton home pour le moment. Préviens un admin."); + return false; + } + } + + @SubscribeEvent + public static void onRegister(RegisterCommandsEvent event) { + CommandDispatcher d = event.getDispatcher(); + d.register(Commands.literal("sethome") + .executes(ctx -> definir(ctx, null)) + .then(Commands.argument("nom", StringArgumentType.word()) + .executes(ctx -> definir(ctx, StringArgumentType.getString(ctx, "nom"))))); + d.register(Commands.literal("home") + .executes(ctx -> aller(ctx, null)) + .then(Commands.argument("nom", StringArgumentType.word()) + .suggests(HomesCommands::suggererNoms) + .executes(ctx -> aller(ctx, StringArgumentType.getString(ctx, "nom"))))); + d.register(Commands.literal("delhome") + .executes(ctx -> supprimer(ctx, null)) + .then(Commands.argument("nom", StringArgumentType.word()) + .suggests(HomesCommands::suggererNoms) + .executes(ctx -> supprimer(ctx, StringArgumentType.getString(ctx, "nom"))))); + d.register(Commands.literal("homes").executes(ctx -> { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + return lister(p); + })); + } + + // --- /sethome --- + + private static int definir(CommandContext ctx, String nomArg) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + HomeBook livre = store(p.server).livre(p.getUUID()); + int max = TpConfig.get(TpConfig.HOMES_MAX); + + String nom; + if (nomArg == null) { + nom = HomeBook.nomLibre(livre.noms(), max); + if (nom == null || livre.taille() >= max) return limite(ctx, max); + } else { + if (!HomeBook.nomValide(nomArg)) { + return echec(ctx, "Nom de home invalide : lettres, chiffres et tirets seulement, " + + HomeBook.NOM_MAX + " caractères maximum."); + } + nom = HomeBook.normaliser(nomArg); + } + + ServerLevel niveau = p.serverLevel(); + String dim = niveau.dimension().location().toString(); + if (!HomeBook.dimensionGeree(dim)) { + return echec(ctx, "Tu ne peux pas définir de home dans cette dimension."); + } + BlockPos pos = p.blockPosition(); + if (!ClaimsBridge.autorise(niveau, p.getUUID(), pos.getX(), pos.getZ())) { + return echec(ctx, "Tu ne peux pas définir de home dans le territoire protégé d'un autre joueur."); + } + if (ClaimsBridge.zoneProtegee(niveau, pos) || ClaimsBridge.zoneProtegee(niveau, pos.above())) { + return echec(ctx, "Tu ne peux pas définir de home dans la zone de spawn protégée."); + } + + HomeBook.Resultat r = livre.definir(nom, new Home(dim, p.getX(), p.getY(), p.getZ(), p.getYRot(), p.getXRot()), max); + switch (r) { + case LIMITE: + return limite(ctx, max); + case NOM_INVALIDE: + return echec(ctx, "Nom de home invalide."); + default: + if (!sauver(ctx)) return 0; + final String n = nom; + ctx.getSource().sendSuccess(() -> succes("Home \"" + n + "\" défini."), false); + return 1; + } + } + + private static int limite(CommandContext ctx, int max) { + return echec(ctx, "Tu as déjà " + max + " homes. Supprime-en un avec /delhome " + + "(liste avec /homes), ou redéfinis-en un en donnant son nom."); + } + + // --- /home --- + + private static int aller(CommandContext ctx, String nomArg) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + HomeBook livre = store(p.server).livre(p.getUUID()); + if (livre.taille() == 0) return echec(ctx, "Tu n'as aucun home. Utilise /sethome pour en définir un."); + + String nom; + if (nomArg == null) { + if (livre.taille() > 1) return lister(p); + nom = livre.noms().get(0); + } else { + nom = HomeBook.normaliser(nomArg); + } + Home home = livre.get(nom); + if (home == null) { + echec(ctx, "Home \"" + nom + "\" introuvable."); + lister(p); + return 0; + } + if (!SpawnRtpCommands.disponible(ctx, p, "home")) return 0; + final String n = nom; + SpawnRtpCommands.demarrer(p, "home", TpConfig.get(TpConfig.HOMES_DELAI), () -> partir(p, n, home), PREFIXE); + return 1; + } + + /** Fin du délai : vérifie que l'arrivée est sûre, puis téléporte. */ + private static void partir(ServerPlayer p, String nom, Home home) { + ServerLevel niveau = p.server.getLevel(ResourceKey.create(Registries.DIMENSION, ResourceLocation.parse(home.dimension()))); + if (niveau == null) { + p.sendSystemMessage(erreur("La dimension du home \"" + nom + "\" n'est plus disponible.")); + return; + } + String probleme = verifierSur(niveau, BlockPos.containing(home.x(), home.y(), home.z())); + if (probleme != null) { + p.sendSystemMessage(erreur("Téléportation annulée : " + probleme + " Redéfinis-le avec /sethome " + nom + ".")); + return; + } + p.stopRiding(); + p.teleportTo(niveau, home.x(), home.y(), home.z(), home.yaw(), home.pitch()); + p.fallDistance = 0; + SpawnRtpCommands.RECHARGES.start(p.getUUID(), "home", TpConfig.get(TpConfig.HOMES_RECHARGE)); + p.sendSystemMessage(succes("Téléporté vers le home \"" + nom + "\".")); + } + + /** Null si l'endroit est sûr, sinon la raison (phrase française). */ + static String verifierSur(ServerLevel n, BlockPos pieds) { + if (pieds.getY() <= n.getMinBuildHeight() + 1 || pieds.getY() >= n.getMaxBuildHeight() - 1) { + return "le home est hors des limites du monde."; + } + for (BlockPos b : new BlockPos[]{pieds, pieds.above()}) { + BlockState s = n.getBlockState(b); + if (s.isCollisionShapeFullBlock(n, b)) return "le home est dans un bloc plein."; + if (dangereux(s)) return "un danger (lave, feu…) se trouve au home."; + } + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + for (int dy = 0; dy <= 1; dy++) { + BlockState s = n.getBlockState(pieds.offset(dx, dy, dz)); + String id = BuiltInRegistries.BLOCK.getKey(s.getBlock()).getPath(); + if (s.getFluidState().is(FluidTags.LAVA) || id.equals("fire") || id.equals("soul_fire")) { + return "de la lave ou du feu se trouve à côté du home."; + } + } + } + } + boolean sol = false; + for (int i = 1; i <= 4 && !sol; i++) { + BlockPos b = pieds.below(i); + BlockState s = n.getBlockState(b); + if (dangereux(s)) return "un danger (lave, feu…) se trouve sous le home."; + sol = !s.getCollisionShape(n, b).isEmpty() || !s.getFluidState().isEmpty(); + } + if (!sol) return "il n'y a plus de sol sous le home (vide)."; + return null; + } + + private static boolean dangereux(BlockState s) { + return s.getFluidState().is(FluidTags.LAVA) || DANGER.contains(BuiltInRegistries.BLOCK.getKey(s.getBlock()).toString()); + } + + // --- /delhome --- + + private static int supprimer(CommandContext ctx, String nomArg) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + HomeBook livre = store(p.server).livre(p.getUUID()); + if (livre.taille() == 0) return echec(ctx, "Tu n'as aucun home à supprimer."); + String nom; + if (nomArg == null) { + if (livre.taille() > 1) { + echec(ctx, "Précise quel home supprimer : /delhome ."); + lister(p); + return 0; + } + nom = livre.noms().get(0); + } else { + nom = HomeBook.normaliser(nomArg); + } + if (!livre.supprimer(nom)) return echec(ctx, "Home \"" + nom + "\" introuvable."); + if (!sauver(ctx)) return 0; + ctx.getSource().sendSuccess(() -> succes("Home \"" + nom + "\" supprimé."), false); + return 1; + } + + // --- /homes --- + + private static int lister(ServerPlayer p) { + HomeBook livre = store(p.server).livre(p.getUUID()); + int max = TpConfig.get(TpConfig.HOMES_MAX); + if (livre.taille() == 0) { + p.sendSystemMessage(info("Tu n'as aucun home. Utilise /sethome pour en définir un.")); + return 0; + } + MutableComponent ligne = Component.literal(PREFIXE).withStyle(ChatFormatting.GOLD) + .append(Component.literal("Tes homes (" + livre.taille() + "/" + max + ") : ").withStyle(ChatFormatting.YELLOW)); + for (String nom : livre.noms()) { + Home h = livre.get(nom); + String detail = Textes.dimensionFr(h.dimension()) + " " + Textes.coordonnees((int) Math.floor(h.x()), + (int) Math.floor(h.y()), (int) Math.floor(h.z())); + ligne.append(Component.literal("[" + nom + "]").withStyle(Style.EMPTY + .withColor(ChatFormatting.GREEN).withBold(true) + .withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/home " + nom)) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, + Component.literal("Aller à ce home (" + detail + ")"))))); + ligne.append(Component.literal("[x]").withStyle(Style.EMPTY + .withColor(ChatFormatting.RED) + .withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/delhome " + nom)) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, + Component.literal("Supprimer ce home (tu devras valider la commande)"))))); + ligne.append(Component.literal(" ")); + } + p.sendSystemMessage(ligne); + return livre.taille(); + } + + private static java.util.concurrent.CompletableFuture suggererNoms( + CommandContext ctx, com.mojang.brigadier.suggestion.SuggestionsBuilder b) + throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + return SharedSuggestionProvider.suggest(store(p.server).livre(p.getUUID()).noms(), b); + } + + // --- Messages --- + + private static int echec(CommandContext ctx, String message) { + ctx.getSource().sendFailure(Component.literal(PREFIXE).withStyle(ChatFormatting.GOLD) + .append(Component.literal(message).withStyle(ChatFormatting.RED))); + return 0; + } + + private static Component info(String s) { + return Component.literal(PREFIXE).withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.YELLOW)); + } + + private static Component succes(String s) { + return Component.literal(PREFIXE).withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.GREEN)); + } + + private static Component erreur(String s) { + return Component.literal(PREFIXE).withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.RED)); + } +} diff --git a/src/main/java/com/gastineltpa/MortEvents.java b/src/main/java/com/gastineltpa/MortEvents.java new file mode 100644 index 0000000..0cd28da --- /dev/null +++ b/src/main/java/com/gastineltpa/MortEvents.java @@ -0,0 +1,50 @@ +package com.gastineltpa; + +import com.gastineltpa.core.Textes; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.Style; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.entity.living.LivingDeathEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Message de mort privé : « Tu es mort en X Y Z (dimension). » envoyé uniquement au joueur mort, à sa + * réapparition (il reste ensuite dans son historique de chat). Cliquable : copie les coordonnées. + * Ne modifie ni n'annule rien (compatible Gravestone). + */ +public final class MortEvents { + + private record Mort(int x, int y, int z, String dimension) {} + + private static final Map EN_ATTENTE = new ConcurrentHashMap<>(); + + private MortEvents() {} + + @SubscribeEvent + public static void onDeath(LivingDeathEvent event) { + if (!(event.getEntity() instanceof ServerPlayer sp)) return; + EN_ATTENTE.put(sp.getUUID(), new Mort(sp.getBlockX(), sp.getBlockY(), sp.getBlockZ(), + sp.level().dimension().location().toString())); + } + + @SubscribeEvent + public static void onRespawn(PlayerEvent.PlayerRespawnEvent event) { + if (event.isEndConquered() || !(event.getEntity() instanceof ServerPlayer sp)) return; + Mort m = EN_ATTENTE.remove(sp.getUUID()); + if (m == null) return; + String coords = Textes.coordonnees(m.x(), m.y(), m.z()); + sp.sendSystemMessage(Component.literal(Textes.messageMort(m.x(), m.y(), m.z(), m.dimension())) + .withStyle(Style.EMPTY.withColor(ChatFormatting.RED) + .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, coords)) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, + Component.literal("Cliquer pour copier " + coords))))); + } +} diff --git a/src/main/java/com/gastineltpa/ProtectionRtp.java b/src/main/java/com/gastineltpa/ProtectionRtp.java new file mode 100644 index 0000000..bcf24b6 --- /dev/null +++ b/src/main/java/com/gastineltpa/ProtectionRtp.java @@ -0,0 +1,80 @@ +package com.gastineltpa; + +import com.gastineltpa.core.Protections; +import com.gastineltpa.core.Textes; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.DamageTypeTags; +import net.minecraft.world.entity.player.Player; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.entity.living.LivingDeathEvent; +import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent; +import net.neoforged.neoforge.event.entity.player.AttackEntityEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.tick.ServerTickEvent; + +/** + * Protection après /rtp et /rtp spawn : aucun dégât (sauf vide et /kill, tag bypasses_invulnerability) pendant + * {@code rtp.protectionSecondes}. Suivi par UUID, horloge serveur, aucun effet de potion. + */ +public final class ProtectionRtp { + + private static final Protections PROTECTIONS = new Protections(System::currentTimeMillis); + + private ProtectionRtp() {} + + /** Appelé après la téléportation d'un /rtp ou /rtp spawn. */ + static void demarrer(ServerPlayer p) { + int s = TpConfig.get(TpConfig.PROTECTION_SECONDES); + if (PROTECTIONS.demarrer(p.getUUID(), s)) { + p.sendSystemMessage(message(Textes.messageProtectionDebut(s))); + } + } + + @SubscribeEvent + public static void onDamage(LivingIncomingDamageEvent event) { + // L'attaquant protégé perd sa protection (projectiles compris), puis la victime protégée annule le coup. + if (TpConfig.get(TpConfig.PROTECTION_FIN_ATTAQUE) && event.getSource().getEntity() instanceof ServerPlayer att + && PROTECTIONS.arreter(att.getUUID())) { + att.sendSystemMessage(message("Protection terminée.")); + } + if (event.getEntity() instanceof ServerPlayer victime && PROTECTIONS.active(victime.getUUID()) + && !event.getSource().is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { + event.setCanceled(true); + } + } + + @SubscribeEvent + public static void onAttack(AttackEntityEvent event) { + Player p = event.getEntity(); + if (p instanceof ServerPlayer sp && TpConfig.get(TpConfig.PROTECTION_FIN_ATTAQUE) + && PROTECTIONS.arreter(sp.getUUID())) { + sp.sendSystemMessage(message("Protection terminée.")); + } + } + + @SubscribeEvent + public static void onTick(ServerTickEvent.Post event) { + if (event.getServer().getTickCount() % 10 != 0) return; + for (java.util.UUID id : PROTECTIONS.purger()) { + ServerPlayer sp = event.getServer().getPlayerList().getPlayer(id); + if (sp != null) sp.sendSystemMessage(message("Protection terminée.")); + } + } + + @SubscribeEvent + public static void onLogout(PlayerEvent.PlayerLoggedOutEvent event) { + PROTECTIONS.oublier(event.getEntity().getUUID()); + } + + @SubscribeEvent + public static void onDeath(LivingDeathEvent event) { + if (event.getEntity() instanceof ServerPlayer sp) PROTECTIONS.oublier(sp.getUUID()); + } + + private static Component message(String s) { + return Component.literal("[TP] ").withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.GRAY)); + } +} diff --git a/src/main/java/com/gastineltpa/SpawnRtpCommands.java b/src/main/java/com/gastineltpa/SpawnRtpCommands.java index b1873f2..eca0040 100644 --- a/src/main/java/com/gastineltpa/SpawnRtpCommands.java +++ b/src/main/java/com/gastineltpa/SpawnRtpCommands.java @@ -57,7 +57,7 @@ import java.util.function.Supplier; /** /spawn, /rtp, /rtp spawn (blocs de commande), /rtp recharger (op). */ public final class SpawnRtpCommands { - private static final Cooldowns RECHARGES = new Cooldowns(System::currentTimeMillis); + static final Cooldowns RECHARGES = new Cooldowns(System::currentTimeMillis); private static final Warmups ATTENTES = new Warmups(); /** Action à lancer quand l'attente d'un joueur se termine. */ private static final Map ACTIONS = new HashMap<>(); @@ -125,6 +125,7 @@ public final class SpawnRtpCommands { return xz == null ? null : new BlockPos(xz[0], 0, xz[1]); }, pos -> { RECHARGES.start(p.getUUID(), "rtp", TpConfig.get(TpConfig.RTP_RECHARGE)); + ProtectionRtp.demarrer(p); p.sendSystemMessage(succes("Téléporté en " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + ". Bonne exploration !")); }); }); @@ -173,7 +174,10 @@ public final class SpawnRtpCommands { if (s != null) return new BlockPos(s.x() + r.nextInt(-2, 3), 0, s.z() + r.nextInt(-2, 3)); int[] xz = zone.tirer(r); // aucun spot : repli sur la zone /rtp return xz == null ? null : new BlockPos(xz[0], 0, xz[1]); - }, pos -> p.sendSystemMessage(succes("Bienvenue ! Tape /guide si tu veux de l'aide."))); + }, pos -> { + ProtectionRtp.demarrer(p); + p.sendSystemMessage(succes("Bienvenue ! Tape /guide si tu veux de l'aide.")); + }); n++; } return n; @@ -385,7 +389,7 @@ public final class SpawnRtpCommands { // --- Délai, annulation, recharge --- - private static boolean disponible(CommandContext ctx, ServerPlayer p, String cmd) { + static boolean disponible(CommandContext ctx, ServerPlayer p, String cmd) { int reste = RECHARGES.remaining(p.getUUID(), cmd); if (reste > 0) { // Recharge courte : appel ignoré en silence, sauf si afficherMessageRecharge = true. @@ -398,13 +402,19 @@ public final class SpawnRtpCommands { } private static void demarrer(ServerPlayer p, String cmd, int delaiSecondes, Runnable action) { + demarrer(p, cmd, delaiSecondes, action, "[TP] "); + } + + /** Délai avant téléportation (annulé si le joueur bouge ou est blessé) ; {@code prefixe} = préfixe du message. */ + static void demarrer(ServerPlayer p, String cmd, int delaiSecondes, Runnable action, String prefixe) { if (delaiSecondes <= 0) { action.run(); return; } ATTENTES.start(p.getUUID(), cmd, p.getX(), p.getY(), p.getZ(), delaiSecondes * 20); ACTIONS.put(p.getUUID(), action); - p.sendSystemMessage(info(Cooldowns.messageAttente(delaiSecondes))); + p.sendSystemMessage(Component.literal(prefixe).withStyle(ChatFormatting.GOLD) + .append(Component.literal(Cooldowns.messageAttente(delaiSecondes)).withStyle(ChatFormatting.YELLOW))); } @SubscribeEvent diff --git a/src/main/java/com/gastineltpa/TpConfig.java b/src/main/java/com/gastineltpa/TpConfig.java index e165d53..2dc7ea2 100644 --- a/src/main/java/com/gastineltpa/TpConfig.java +++ b/src/main/java/com/gastineltpa/TpConfig.java @@ -16,6 +16,10 @@ public final class TpConfig { public static final ModConfigSpec.IntValue ZONE_X_MIN, ZONE_X_MAX, ZONE_Z_MIN, ZONE_Z_MAX; public static final ModConfigSpec.IntValue ZONE_CENTRE_X, ZONE_CENTRE_Z, ZONE_RAYON; + public static final ModConfigSpec.IntValue PROTECTION_SECONDES; + public static final ModConfigSpec.BooleanValue PROTECTION_FIN_ATTAQUE; + public static final ModConfigSpec.IntValue HOMES_MAX, HOMES_RECHARGE, HOMES_DELAI; + public static final ModConfigSpec.BooleanValue AFFICHER_MSG_RECHARGE; public static final ModConfigSpec.IntValue TPA_DELAI; public static final ModConfigSpec.IntValue SPAWN_RTP_RECHARGE; @@ -49,6 +53,10 @@ public final class TpConfig { RTP_RECHARGE = b.comment("Temps de recharge entre deux /rtp, en secondes.") .defineInRange("rechargeSecondes", 1, 0, 86400); RTP_ESSAIS = b.comment("Nombre d'endroits essayés avant d'abandonner.").defineInRange("essais", 100, 1, 300); + PROTECTION_SECONDES = b.comment("Protection après /rtp et /rtp spawn : invulnérable (sauf vide) pendant N secondes. 0 = désactivée.") + .defineInRange("protectionSecondes", 15, 0, 300); + PROTECTION_FIN_ATTAQUE = b.comment("La protection s'arrête dès que le joueur attaque une entité ou un joueur.") + .define("protectionFinSiAttaque", true); b.comment("Zone de tirage (blocs). Mesuré le 09/10/2026 sur une copie de neW512 (outils/beaux_spots.py) :", "89 397 chunks complets, de x -512..6831 et z -5632..1167 (pas un rectangle plein : beaucoup", "d'océan). Pas de worldborder (vanilla). Les chunks absents du disque sont toujours refusés."); @@ -72,6 +80,14 @@ public final class TpConfig { .define("fichierSpots", "config/gastineltpa/beaux-spots.json"); b.pop(); + b.comment("/sethome, /home, /delhome, /homes").push("homes"); + HOMES_MAX = b.comment("Nombre maximum de homes par joueur.").defineInRange("maximum", 3, 1, 50); + HOMES_RECHARGE = b.comment("Recharge entre deux /home, en secondes (silencieuse comme /spawn).") + .defineInRange("rechargeSecondes", 1, 0, 86400); + HOMES_DELAI = b.comment("Délai avant téléportation, en secondes (annulé si le joueur bouge ou est blessé).") + .defineInRange("delaiSecondes", 3, 0, 60); + b.pop(); + SPEC = b.build(); } @@ -79,6 +95,10 @@ public final class TpConfig { return SPEC.isLoaded() ? v.get() : v.getDefault(); } + static boolean get(ModConfigSpec.BooleanValue v) { + return SPEC.isLoaded() ? v.get() : v.getDefault(); + } + static boolean afficherMessageRecharge() { return SPEC.isLoaded() ? AFFICHER_MSG_RECHARGE.get() : AFFICHER_MSG_RECHARGE.getDefault(); } diff --git a/src/main/java/com/gastineltpa/TpaCommands.java b/src/main/java/com/gastineltpa/TpaCommands.java index 420ed5d..31d99cd 100644 --- a/src/main/java/com/gastineltpa/TpaCommands.java +++ b/src/main/java/com/gastineltpa/TpaCommands.java @@ -62,6 +62,12 @@ public final class TpaCommands { .suggests(TpaCommands::suggererDemandeurs) .executes(ctx -> repondre(ctx, StringArgumentType.getString(ctx, "joueur"), true)))); + d.register(Commands.literal("tpacancel") + .executes(ctx -> annuler(ctx, null)) + .then(Commands.argument("joueur", StringArgumentType.word()) + .suggests(TpaCommands::suggererCibles) + .executes(ctx -> annuler(ctx, StringArgumentType.getString(ctx, "joueur"))))); + d.register(Commands.literal("tpadeny") .executes(ctx -> repondre(ctx, null, false)) .then(Commands.argument("joueur", StringArgumentType.word()) @@ -198,6 +204,43 @@ public final class TpaCommands { return 1; } + /** /tpacancel [joueur] : annule la dernière demande envoyée (ou celle vers ce joueur) et prévient la cible. */ + private static int annuler(CommandContext ctx, String nomCible) throws CommandSyntaxException { + ServerPlayer moi = ctx.getSource().getPlayerOrException(); + MinecraftServer server = moi.server; + nettoyerExpirees(server); + + Optional annulee; + if (nomCible == null) { + annulee = REGISTRE.cancel(moi.getUUID(), null); + if (annulee.isEmpty()) return echec(ctx, "Tu n'as aucune demande de téléportation en cours à annuler."); + } else { + ServerPlayer cible = server.getPlayerList().getPlayerByName(nomCible); + annulee = cible == null ? Optional.empty() : REGISTRE.cancel(moi.getUUID(), cible.getUUID()); + if (annulee.isEmpty()) return echec(ctx, "Tu n'as aucune demande en cours vers " + nomCible + "."); + } + + ServerPlayer cible = server.getPlayerList().getPlayer(annulee.get().to()); + String nomVers = cible != null ? cible.getGameProfile().getName() : "?"; + ctx.getSource().sendSuccess(() -> info("Demande de téléportation à " + nomVers + " annulée."), false); + if (cible != null) { + cible.sendSystemMessage(info(moi.getGameProfile().getName() + " a annulé sa demande de téléportation.")); + } + return 1; + } + + private static java.util.concurrent.CompletableFuture + suggererCibles(CommandContext ctx, com.mojang.brigadier.suggestion.SuggestionsBuilder b) + throws CommandSyntaxException { + ServerPlayer moi = ctx.getSource().getPlayerOrException(); + List noms = new ArrayList<>(); + for (Request r : REGISTRE.pendingFrom(moi.getUUID())) { + ServerPlayer p = moi.server.getPlayerList().getPlayer(r.to()); + if (p != null) noms.add(p.getGameProfile().getName()); + } + return SharedSuggestionProvider.suggest(noms, b); + } + // --- Utilitaires --- /** Téléporte vers la position de la destination (même dimension ou non), en gardant le regard du voyageur. */ diff --git a/src/main/java/com/gastineltpa/core/HomeBook.java b/src/main/java/com/gastineltpa/core/HomeBook.java new file mode 100644 index 0000000..4545c7e --- /dev/null +++ b/src/main/java/com/gastineltpa/core/HomeBook.java @@ -0,0 +1,81 @@ +package com.gastineltpa.core; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Homes d'un joueur (logique pure) : noms, limite, premier nom libre. */ +public final class HomeBook { + + public static final int NOM_MAX = 16; + private static final Pattern NOM = Pattern.compile("[A-Za-z0-9-]{1,16}"); + /** Dimensions où l'on peut définir un home. */ + public static final Set DIMENSIONS_GEREES = + Set.of("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end"); + + public record Home(String dimension, double x, double y, double z, float yaw, float pitch) {} + + public enum Resultat { NOUVEAU, REMPLACE, NOM_INVALIDE, LIMITE } + + private final Map homes = new LinkedHashMap<>(); + + /** Lettres (sans accent), chiffres, tiret ; 1 à 16 caractères. */ + public static boolean nomValide(String nom) { + return nom != null && NOM.matcher(nom).matches(); + } + + /** Les noms ne tiennent pas compte de la casse : tout est stocké en minuscules. */ + public static String normaliser(String nom) { + return nom.toLowerCase(Locale.ROOT); + } + + public static boolean dimensionGeree(String dimension) { + return DIMENSIONS_GEREES.contains(dimension); + } + + /** Premier nom libre parmi « 1 », « 2 », … « max » ; null s'ils sont tous pris. */ + public static String nomLibre(Collection pris, int max) { + for (int i = 1; i <= max; i++) { + String n = String.valueOf(i); + if (!pris.contains(n)) return n; + } + return null; + } + + /** Définit un home. Redéfinir un nom existant ne compte pas dans la limite. */ + public Resultat definir(String nom, Home home, int maximum) { + if (!nomValide(nom)) return Resultat.NOM_INVALIDE; + String cle = normaliser(nom); + boolean existe = homes.containsKey(cle); + if (!existe && homes.size() >= maximum) return Resultat.LIMITE; + homes.put(cle, home); + return existe ? Resultat.REMPLACE : Resultat.NOUVEAU; + } + + public boolean supprimer(String nom) { + return nom != null && homes.remove(normaliser(nom)) != null; + } + + public Home get(String nom) { + return nom == null ? null : homes.get(normaliser(nom)); + } + + public List noms() { + return new ArrayList<>(homes.keySet()); + } + + public int taille() { + return homes.size(); + } + + /** Pour la sauvegarde (ordre de création conservé). */ + public Map tout() { + return Collections.unmodifiableMap(homes); + } +} diff --git a/src/main/java/com/gastineltpa/core/HomeStore.java b/src/main/java/com/gastineltpa/core/HomeStore.java new file mode 100644 index 0000000..10d8e90 --- /dev/null +++ b/src/main/java/com/gastineltpa/core/HomeStore.java @@ -0,0 +1,92 @@ +package com.gastineltpa.core; + +import com.gastineltpa.core.HomeBook.Home; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** Homes de tous les joueurs, par UUID, dans un fichier JSON du dossier du monde (écriture atomique). */ +public final class HomeStore { + + private final Path fichier; + private final Map livres = new HashMap<>(); + + public HomeStore(Path fichier) { + this.fichier = fichier; + } + + public HomeBook livre(UUID joueur) { + return livres.computeIfAbsent(joueur, k -> new HomeBook()); + } + + /** Charge le fichier s'il existe. Fichier illisible : renommé en .corrompu (jamais écrasé), on repart de zéro. */ + public void charger() throws IOException { + livres.clear(); + if (!Files.isRegularFile(fichier)) return; + try { + JsonObject racine = JsonParser.parseString(Files.readString(fichier, StandardCharsets.UTF_8)).getAsJsonObject(); + JsonObject joueurs = racine.getAsJsonObject("joueurs"); + for (Map.Entry e : joueurs.entrySet()) { + HomeBook livre = new HomeBook(); + for (Map.Entry h : e.getValue().getAsJsonObject().entrySet()) { + JsonObject o = h.getValue().getAsJsonObject(); + livre.definir(h.getKey(), new Home(o.get("dim").getAsString(), o.get("x").getAsDouble(), + o.get("y").getAsDouble(), o.get("z").getAsDouble(), + o.get("yaw").getAsFloat(), o.get("pitch").getAsFloat()), Integer.MAX_VALUE); + } + livres.put(UUID.fromString(e.getKey()), livre); + } + } catch (RuntimeException e) { + Path corrompu = fichier.resolveSibling(fichier.getFileName() + ".corrompu"); + Files.move(fichier, corrompu, StandardCopyOption.REPLACE_EXISTING); + livres.clear(); + throw new IOException("fichier de homes illisible, renommé en " + corrompu.getFileName() + " : " + e, e); + } + } + + public String versJson() { + JsonObject joueurs = new JsonObject(); + for (Map.Entry e : livres.entrySet()) { + if (e.getValue().taille() == 0) continue; + JsonObject homes = new JsonObject(); + for (Map.Entry h : e.getValue().tout().entrySet()) { + JsonObject o = new JsonObject(); + Home v = h.getValue(); + o.addProperty("dim", v.dimension()); + o.addProperty("x", v.x()); + o.addProperty("y", v.y()); + o.addProperty("z", v.z()); + o.addProperty("yaw", v.yaw()); + o.addProperty("pitch", v.pitch()); + homes.add(h.getKey(), o); + } + joueurs.add(e.getKey().toString(), homes); + } + JsonObject racine = new JsonObject(); + racine.addProperty("version", 1); + racine.add("joueurs", joueurs); + return new GsonBuilder().setPrettyPrinting().create().toJson(racine); + } + + /** Écrit dans un fichier temporaire voisin puis le déplace atomiquement sur le fichier final. */ + public void sauver() throws IOException { + Path tmp = fichier.resolveSibling(fichier.getFileName() + ".tmp"); + Files.writeString(tmp, versJson(), StandardCharsets.UTF_8); + try { + Files.move(tmp, fichier, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(tmp, fichier, StandardCopyOption.REPLACE_EXISTING); + } + } +} diff --git a/src/main/java/com/gastineltpa/core/Protections.java b/src/main/java/com/gastineltpa/core/Protections.java new file mode 100644 index 0000000..c1c8e96 --- /dev/null +++ b/src/main/java/com/gastineltpa/core/Protections.java @@ -0,0 +1,62 @@ +package com.gastineltpa.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.LongSupplier; + +/** + * Protection temporaire (après un /rtp) suivie par UUID. Logique pure, horloge injectable. + * Une protection expirée n'est plus « active » mais reste en mémoire jusqu'à {@link #purger()}, + * qui sert à envoyer le message de fin. + */ +public final class Protections { + + private final LongSupplier clock; + private final Map fin = new HashMap<>(); + + public Protections(LongSupplier clockMs) { + this.clock = clockMs; + } + + /** Démarre (ou relance) la protection ; 0 seconde ou moins = désactivée. Renvoie vrai si démarrée. */ + public boolean demarrer(UUID joueur, int secondes) { + if (secondes <= 0) return false; + fin.put(joueur, clock.getAsLong() + secondes * 1000L); + return true; + } + + /** Vrai si la protection existe et n'est pas expirée. */ + public boolean active(UUID joueur) { + Long f = fin.get(joueur); + return f != null && clock.getAsLong() < f; + } + + /** Arrête la protection ; vrai si elle était active (donc si un message de fin est à envoyer). */ + public boolean arreter(UUID joueur) { + Long f = fin.remove(joueur); + return f != null && clock.getAsLong() < f; + } + + /** Oublie le joueur sans message (déconnexion, mort). */ + public void oublier(UUID joueur) { + fin.remove(joueur); + } + + /** Retire et renvoie les protections arrivées à expiration. */ + public List purger() { + long now = clock.getAsLong(); + List out = new ArrayList<>(); + for (Iterator> it = fin.entrySet().iterator(); it.hasNext(); ) { + Map.Entry e = it.next(); + if (now >= e.getValue()) { + out.add(e.getKey()); + it.remove(); + } + } + return out; + } +} diff --git a/src/main/java/com/gastineltpa/core/Textes.java b/src/main/java/com/gastineltpa/core/Textes.java new file mode 100644 index 0000000..c28206f --- /dev/null +++ b/src/main/java/com/gastineltpa/core/Textes.java @@ -0,0 +1,28 @@ +package com.gastineltpa.core; + +/** Textes purs (testables sans Minecraft). */ +public final class Textes { + + private Textes() {} + + public static String dimensionFr(String id) { + return switch (id) { + case "minecraft:overworld" -> "Overworld"; + case "minecraft:the_nether" -> "Nether"; + case "minecraft:the_end" -> "End"; + default -> id.contains(":") ? id.substring(id.indexOf(':') + 1) : id; + }; + } + + public static String coordonnees(int x, int y, int z) { + return x + " " + y + " " + z; + } + + public static String messageMort(int x, int y, int z, String dimension) { + return "Tu es mort en " + coordonnees(x, y, z) + " (" + dimensionFr(dimension) + ")."; + } + + public static String messageProtectionDebut(int secondes) { + return "Protection de " + secondes + " s active."; + } +} diff --git a/src/main/java/com/gastineltpa/core/TpaRegistry.java b/src/main/java/com/gastineltpa/core/TpaRegistry.java index b5f1cf2..3ca187b 100644 --- a/src/main/java/com/gastineltpa/core/TpaRegistry.java +++ b/src/main/java/com/gastineltpa/core/TpaRegistry.java @@ -69,6 +69,33 @@ public final class TpaRegistry { return out; } + /** Dernière invitation valide envoyée par ce demandeur. */ + public Optional latestFrom(UUID from) { + long now = clock.getAsLong(); + Request best = null; + for (Request r : requests) { + if (r.from().equals(from) && !r.expiree(now)) best = r; + } + return Optional.ofNullable(best); + } + + /** Invitations valides envoyées par ce demandeur (suggestions de /tpacancel). */ + public List pendingFrom(UUID from) { + long now = clock.getAsLong(); + List out = new ArrayList<>(); + for (Request r : requests) { + if (r.from().equals(from) && !r.expiree(now)) out.add(r); + } + return out; + } + + /** Annule une demande envoyée : vers {@code toOuNull} si précisé, sinon la dernière. Renvoie la demande retirée. */ + public Optional cancel(UUID from, UUID toOuNull) { + Optional r = toOuNull == null ? latestFrom(from) : find(toOuNull, from); + r.ifPresent(requests::remove); + return r; + } + public boolean remove(Request r) { return requests.remove(r); } diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 5b7a389..9557bd9 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -4,7 +4,7 @@ license="MIT" [[mods]] modId="gastineltpa" -version="1.1.1" +version="1.2.0" displayName="GastinelTpa" authors="Théo Gastinel" description='''Demandes de téléportation entre joueurs (/tpa, /tpahere, /tpaccept, /tpadeny), /spawn, /rtp et /rtp spawn (blocs de commande). Mod côté serveur uniquement.''' diff --git a/src/test/java/com/gastineltpa/core/Nouveautes120Test.java b/src/test/java/com/gastineltpa/core/Nouveautes120Test.java new file mode 100644 index 0000000..d7b3ecd --- /dev/null +++ b/src/test/java/com/gastineltpa/core/Nouveautes120Test.java @@ -0,0 +1,241 @@ +package com.gastineltpa.core; + +import com.gastineltpa.core.HomeBook.Home; +import com.gastineltpa.core.HomeBook.Resultat; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +/** Tests de la 1.2.0 : homes, protection RTP, /tpacancel, textes. */ +class Nouveautes120Test { + + private long now; + private final UUID a = UUID.randomUUID(); + private final UUID b = UUID.randomUUID(); + private final UUID c = UUID.randomUUID(); + + @BeforeEach + void init() { + now = 5_000_000L; + } + + private static Home home(double x) { + return new Home("minecraft:overworld", x, 64, 10, 90f, 5f); + } + + // --- Homes : noms --- + + @Test + void nomLibrePrendLePremierDe1A3() { + assertEquals("1", HomeBook.nomLibre(List.of(), 3)); + assertEquals("2", HomeBook.nomLibre(List.of("1"), 3)); + assertEquals("1", HomeBook.nomLibre(List.of("2", "3", "maison"), 3)); + assertEquals("3", HomeBook.nomLibre(List.of("1", "2", "maison"), 3)); + assertNull(HomeBook.nomLibre(List.of("1", "2", "3"), 3)); + } + + @Test + void nomLibreSuitLeMaximumConfigure() { + assertEquals("4", HomeBook.nomLibre(List.of("1", "2", "3"), 5)); + } + + @Test + void validationDesNoms() { + assertTrue(HomeBook.nomValide("maison")); + assertTrue(HomeBook.nomValide("Base-2")); + assertTrue(HomeBook.nomValide("1")); + assertTrue(HomeBook.nomValide("a".repeat(16))); + assertFalse(HomeBook.nomValide("a".repeat(17))); + assertFalse(HomeBook.nomValide("")); + assertFalse(HomeBook.nomValide(null)); + assertFalse(HomeBook.nomValide("mon home")); + assertFalse(HomeBook.nomValide("café")); + assertFalse(HomeBook.nomValide("a_b")); + assertFalse(HomeBook.nomValide("../x")); + assertFalse(HomeBook.nomValide("a/b")); + } + + // --- Homes : limite --- + + @Test + void limiteDeTroisHomes() { + HomeBook l = new HomeBook(); + assertEquals(Resultat.NOUVEAU, l.definir("1", home(1), 3)); + assertEquals(Resultat.NOUVEAU, l.definir("2", home(2), 3)); + assertEquals(Resultat.NOUVEAU, l.definir("maison", home(3), 3)); + assertEquals(Resultat.LIMITE, l.definir("4", home(4), 3)); + assertEquals(3, l.taille()); + } + + @Test + void redefinirNeCompteQuUneFoisEtSupprimerLibere() { + HomeBook l = new HomeBook(); + l.definir("1", home(1), 3); + l.definir("2", home(2), 3); + l.definir("3", home(3), 3); + assertEquals(Resultat.REMPLACE, l.definir("2", home(9), 3)); + assertEquals(9, l.get("2").x()); + assertEquals(3, l.taille()); + assertTrue(l.supprimer("1")); + assertFalse(l.supprimer("1")); + assertEquals(Resultat.NOUVEAU, l.definir("autre", home(5), 3)); + } + + @Test + void nomInvalideRefuseEtCasseIgnoree() { + HomeBook l = new HomeBook(); + assertEquals(Resultat.NOM_INVALIDE, l.definir("mon home", home(1), 3)); + assertEquals(Resultat.NOUVEAU, l.definir("Maison", home(1), 3)); + assertNotNull(l.get("MAISON")); + assertEquals(List.of("maison"), l.noms()); + assertEquals(Resultat.REMPLACE, l.definir("MAISON", home(2), 3)); + } + + @Test + void dimensionsGerees() { + assertTrue(HomeBook.dimensionGeree("minecraft:overworld")); + assertTrue(HomeBook.dimensionGeree("minecraft:the_nether")); + assertTrue(HomeBook.dimensionGeree("minecraft:the_end")); + assertFalse(HomeBook.dimensionGeree("create:autre")); + } + + @Test + void sauvegardePuisRechargement(@TempDir Path dir) throws IOException { + Path f = dir.resolve("homes.json"); + HomeStore s = new HomeStore(f); + s.livre(a).definir("maison", new Home("minecraft:the_nether", 1.5, 70, -3.25, 123.5f, -10f), 3); + s.livre(a).definir("2", home(2), 3); + s.livre(b).definir("x", home(7), 3); + s.sauver(); + assertFalse(Files.exists(dir.resolve("homes.json.tmp"))); + + HomeStore t = new HomeStore(f); + t.charger(); + assertEquals(List.of("maison", "2"), t.livre(a).noms()); + Home h = t.livre(a).get("maison"); + assertEquals("minecraft:the_nether", h.dimension()); + assertEquals(1.5, h.x()); + assertEquals(-3.25, h.z()); + assertEquals(123.5f, h.yaw()); + assertEquals(-10f, h.pitch()); + assertEquals(1, t.livre(b).taille()); + assertEquals(0, t.livre(c).taille()); + } + + @Test + void fichierIllisibleRenommeSansEtreEcrase(@TempDir Path dir) throws IOException { + Path f = dir.resolve("homes.json"); + Files.writeString(f, "{ pas du json"); + HomeStore s = new HomeStore(f); + assertThrows(IOException.class, s::charger); + assertTrue(Files.exists(dir.resolve("homes.json.corrompu"))); + assertEquals(0, s.livre(a).taille()); + } + + // --- Protection RTP --- + + @Test + void protectionExpireApresLaDuree() { + Protections p = new Protections(() -> now); + assertTrue(p.demarrer(a, 15)); + assertTrue(p.active(a)); + now += 14_999; + assertTrue(p.active(a)); + assertTrue(p.purger().isEmpty()); + now += 1; + assertFalse(p.active(a)); + assertEquals(List.of(a), p.purger()); + assertTrue(p.purger().isEmpty()); + } + + @Test + void protectionDesactiveeSiDureeNulle() { + Protections p = new Protections(() -> now); + assertFalse(p.demarrer(a, 0)); + assertFalse(p.active(a)); + } + + @Test + void protectionArreteeParAttaqueUneSeuleFois() { + Protections p = new Protections(() -> now); + p.demarrer(a, 15); + assertTrue(p.arreter(a)); + assertFalse(p.active(a)); + assertFalse(p.arreter(a)); + assertTrue(p.purger().isEmpty()); + } + + @Test + void protectionParJoueurEtOubliSansMessage() { + Protections p = new Protections(() -> now); + p.demarrer(a, 15); + assertFalse(p.active(b)); + p.oublier(a); + assertFalse(p.active(a)); + assertTrue(p.purger().isEmpty()); + } + + @Test + void relancerLaProtectionProloge() { + Protections p = new Protections(() -> now); + p.demarrer(a, 15); + now += 10_000; + p.demarrer(a, 15); + now += 10_000; + assertTrue(p.active(a)); + } + + // --- /tpacancel --- + + @Test + void annulerLaDerniereDemande() { + TpaRegistry r = new TpaRegistry(() -> now); + r.add(a, b, TpaRegistry.Type.TPA); + now += 1000; + r.add(a, c, TpaRegistry.Type.TPAHERE); + var annulee = r.cancel(a, null); + assertTrue(annulee.isPresent()); + assertEquals(c, annulee.get().to()); + assertTrue(r.find(c, a).isEmpty()); + assertTrue(r.find(b, a).isPresent()); + } + + @Test + void annulerVersUneCibleCiblee() { + TpaRegistry r = new TpaRegistry(() -> now); + r.add(a, b, TpaRegistry.Type.TPA); + r.add(a, c, TpaRegistry.Type.TPA); + assertEquals(b, r.cancel(a, b).get().to()); + assertEquals(1, r.pendingFrom(a).size()); + assertEquals(c, r.pendingFrom(a).get(0).to()); + } + + @Test + void annulerSansDemandeOuExpireeOuDunAutre() { + TpaRegistry r = new TpaRegistry(() -> now); + assertTrue(r.cancel(a, null).isEmpty()); + r.add(a, b, TpaRegistry.Type.TPA); + assertTrue(r.cancel(b, null).isEmpty()); // b n'a rien envoye (a lui a envoye) + assertTrue(r.cancel(a, c).isEmpty()); + now += TpaRegistry.EXPIRATION_MS; + assertTrue(r.cancel(a, null).isEmpty()); + } + + // --- Textes --- + + @Test + void messageDeMort() { + assertEquals("Tu es mort en 12 -5 340 (Overworld).", Textes.messageMort(12, -5, 340, "minecraft:overworld")); + assertEquals("Tu es mort en 1 2 3 (Nether).", Textes.messageMort(1, 2, 3, "minecraft:the_nether")); + assertEquals("Tu es mort en 1 2 3 (End).", Textes.messageMort(1, 2, 3, "minecraft:the_end")); + assertEquals("Protection de 15 s active.", Textes.messageProtectionDebut(15)); + } +}