Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
347 lignes
17 KiB
Java
347 lignes
17 KiB
Java
package com.gastineltpa;
|
|
|
|
import com.gastineltpa.core.PseudoMatcher;
|
|
import com.gastineltpa.core.PseudoMatcher.Profil;
|
|
import com.gastineltpa.core.TpaRegistry;
|
|
import com.gastineltpa.core.TpaRegistry.Request;
|
|
import com.gastineltpa.core.TpaRegistry.Type;
|
|
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.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.server.MinecraftServer;
|
|
import net.minecraft.server.level.ServerLevel;
|
|
import net.minecraft.server.level.ServerPlayer;
|
|
import net.neoforged.bus.api.SubscribeEvent;
|
|
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
|
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
import java.util.UUID;
|
|
|
|
/** /tpa, /tpahere, /tpaccept, /tpadeny */
|
|
public final class TpaCommands {
|
|
|
|
private record Depart(UUID voyageur, UUID destination, boolean tpa, int[] ticks) {
|
|
Depart(UUID v, UUID d, boolean tpa, int t) { this(v, d, tpa, new int[]{t}); }
|
|
}
|
|
|
|
private static final List<Depart> EN_COURS = new ArrayList<>();
|
|
|
|
private static final TpaRegistry REGISTRE = new TpaRegistry(System::currentTimeMillis);
|
|
|
|
@SubscribeEvent
|
|
public static void onRegister(RegisterCommandsEvent event) {
|
|
CommandDispatcher<CommandSourceStack> d = event.getDispatcher();
|
|
|
|
d.register(Commands.literal("tpa")
|
|
.then(Commands.argument("joueur", StringArgumentType.word())
|
|
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(
|
|
PseudoMatcher.suggestions(List.of(ctx.getSource().getServer().getPlayerNames())), b))
|
|
.executes(ctx -> demander(ctx, Type.TPA))));
|
|
|
|
d.register(Commands.literal("tpahere")
|
|
.then(Commands.argument("joueur", StringArgumentType.word())
|
|
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(
|
|
PseudoMatcher.suggestions(List.of(ctx.getSource().getServer().getPlayerNames())), b))
|
|
.executes(ctx -> demander(ctx, Type.TPAHERE))));
|
|
|
|
d.register(Commands.literal("tpaccept")
|
|
.executes(ctx -> repondre(ctx, null, true))
|
|
.then(Commands.argument("joueur", StringArgumentType.word())
|
|
.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())
|
|
.suggests(TpaCommands::suggererDemandeurs)
|
|
.executes(ctx -> repondre(ctx, StringArgumentType.getString(ctx, "joueur"), false))));
|
|
}
|
|
|
|
// --- Événements ---
|
|
|
|
/** Une fois par seconde : prévient les deux joueurs des invitations expirées. */
|
|
@SubscribeEvent
|
|
public static void onTick(ServerTickEvent.Post event) {
|
|
MinecraftServer server = event.getServer();
|
|
if (server.getTickCount() % 20 == 0) {
|
|
nettoyerExpirees(server);
|
|
}
|
|
for (java.util.Iterator<Depart> it = EN_COURS.iterator(); it.hasNext(); ) {
|
|
Depart d = it.next();
|
|
if (d.ticks()[0]-- > 0) continue;
|
|
it.remove();
|
|
ServerPlayer v = server.getPlayerList().getPlayer(d.voyageur());
|
|
ServerPlayer dest = server.getPlayerList().getPlayer(d.destination());
|
|
if (v == null || dest == null) {
|
|
ServerPlayer reste = v != null ? v : dest;
|
|
if (reste != null) reste.sendSystemMessage(erreur("Téléportation annulée : l'autre joueur s'est déconnecté."));
|
|
continue;
|
|
}
|
|
teleporter(v, dest);
|
|
String nv = v.getGameProfile().getName(), nd = dest.getGameProfile().getName();
|
|
v.sendSystemMessage(succes(d.tpa() ? "Tu te téléportes vers " + nd + "." : "Tu es téléporté vers " + nd + "."));
|
|
dest.sendSystemMessage(succes(nv + " arrive vers toi."));
|
|
}
|
|
}
|
|
|
|
/** Un joueur qui se déconnecte annule toutes ses invitations (envoyées et reçues). */
|
|
@SubscribeEvent
|
|
public static void onLogout(PlayerEvent.PlayerLoggedOutEvent event) {
|
|
if (!(event.getEntity() instanceof ServerPlayer parti)) return;
|
|
MinecraftServer server = parti.server;
|
|
EN_COURS.removeIf(d -> d.voyageur().equals(parti.getUUID()) || d.destination().equals(parti.getUUID()));
|
|
for (Request r : REGISTRE.removeInvolving(parti.getUUID())) {
|
|
UUID autreId = r.from().equals(parti.getUUID()) ? r.to() : r.from();
|
|
ServerPlayer autre = server.getPlayerList().getPlayer(autreId);
|
|
if (autre != null) {
|
|
autre.sendSystemMessage(info("Demande de téléportation annulée : "
|
|
+ parti.getGameProfile().getName() + " s'est déconnecté."));
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- Commandes ---
|
|
|
|
private static int demander(CommandContext<CommandSourceStack> ctx, Type type) throws CommandSyntaxException {
|
|
ServerPlayer moi = ctx.getSource().getPlayerOrException();
|
|
MinecraftServer server = moi.server;
|
|
nettoyerExpirees(server);
|
|
|
|
String nom = StringArgumentType.getString(ctx, "joueur");
|
|
Cherche c = chercherEnLigne(server, nom);
|
|
if (c.ambigu != null) return echec(ctx, c.ambigu);
|
|
ServerPlayer cible = c.joueur;
|
|
if (cible == null) {
|
|
return echec(ctx, "Joueur introuvable ou hors ligne : " + nom);
|
|
}
|
|
if (cible.getUUID().equals(moi.getUUID())) {
|
|
return echec(ctx, "Tu ne peux pas t'envoyer une demande à toi-même.");
|
|
}
|
|
|
|
REGISTRE.add(moi.getUUID(), cible.getUUID(), type);
|
|
String nomCible = cible.getGameProfile().getName();
|
|
String nomMoi = moi.getGameProfile().getName();
|
|
|
|
ctx.getSource().sendSuccess(() -> info(type == Type.TPA
|
|
? "Demande envoyée à " + nomCible + " : tu iras le rejoindre s'il accepte (60 s)."
|
|
: "Demande envoyée à " + nomCible + " : il viendra te rejoindre s'il accepte (60 s)."), false);
|
|
|
|
MutableComponent msg = Component.literal("[TPA] ").withStyle(ChatFormatting.GOLD)
|
|
.append(Component.literal(type == Type.TPA
|
|
? nomMoi + " souhaite se téléporter vers toi. "
|
|
: nomMoi + " souhaite que tu te téléportes vers lui. ").withStyle(ChatFormatting.YELLOW))
|
|
.append(bouton("[Accepter]", "/tpaccept " + PseudoMatcher.argumentBouton(moi.getUUID(), nomMoi), ChatFormatting.GREEN, "Accepter la demande"))
|
|
.append(Component.literal(" "))
|
|
.append(bouton("[Refuser]", "/tpadeny " + PseudoMatcher.argumentBouton(moi.getUUID(), nomMoi), ChatFormatting.RED, "Refuser la demande"))
|
|
.append(Component.literal(" (expire dans 60 s)").withStyle(ChatFormatting.GRAY));
|
|
cible.sendSystemMessage(msg);
|
|
return 1;
|
|
}
|
|
|
|
private static int repondre(CommandContext<CommandSourceStack> ctx, String nomDemandeur, boolean accepter)
|
|
throws CommandSyntaxException {
|
|
ServerPlayer moi = ctx.getSource().getPlayerOrException();
|
|
MinecraftServer server = moi.server;
|
|
// On prévient d'abord les expirées, pour que le message d'expiration passe avant tout.
|
|
nettoyerExpirees(server);
|
|
|
|
Optional<Request> trouvee;
|
|
if (nomDemandeur == null) {
|
|
trouvee = REGISTRE.latest(moi.getUUID());
|
|
if (trouvee.isEmpty()) {
|
|
return echec(ctx, "Aucune demande de téléportation en attente.");
|
|
}
|
|
} else if (PseudoMatcher.parseUuidStrict(nomDemandeur).isPresent()) {
|
|
// Bouton / UUID : recherche directe dans le registre des demandes, jamais par pseudo.
|
|
UUID id = PseudoMatcher.parseUuidStrict(nomDemandeur).get();
|
|
trouvee = REGISTRE.find(moi.getUUID(), id);
|
|
if (trouvee.isEmpty()) {
|
|
return echec(ctx, "Aucune demande en attente de la part de ce joueur (peut-être expirée).");
|
|
}
|
|
} else {
|
|
Cherche c = chercherEnLigne(server, nomDemandeur);
|
|
if (c.ambigu != null) return echec(ctx, c.ambigu);
|
|
ServerPlayer demandeur = c.joueur;
|
|
if (demandeur == null) {
|
|
return echec(ctx, "Joueur introuvable ou hors ligne : " + nomDemandeur);
|
|
}
|
|
trouvee = REGISTRE.find(moi.getUUID(), demandeur.getUUID());
|
|
if (trouvee.isEmpty()) {
|
|
return echec(ctx, "Aucune demande en attente de la part de "
|
|
+ demandeur.getGameProfile().getName() + " (peut-être expirée).");
|
|
}
|
|
}
|
|
|
|
Request r = trouvee.get();
|
|
REGISTRE.remove(r);
|
|
ServerPlayer demandeur = server.getPlayerList().getPlayer(r.from());
|
|
if (demandeur == null) {
|
|
return echec(ctx, "Le demandeur s'est déconnecté, demande annulée.");
|
|
}
|
|
String nomDem = demandeur.getGameProfile().getName();
|
|
String nomMoi = moi.getGameProfile().getName();
|
|
|
|
if (!accepter) {
|
|
ctx.getSource().sendSuccess(() -> info("Demande de " + nomDem + " refusée."), false);
|
|
demandeur.sendSystemMessage(erreur(nomMoi + " a refusé ta demande de téléportation."));
|
|
return 1;
|
|
}
|
|
|
|
// TPA : le demandeur va vers moi. TPAHERE : je vais vers le demandeur.
|
|
ServerPlayer voyageur = r.type() == Type.TPA ? demandeur : moi;
|
|
ServerPlayer destination = r.type() == Type.TPA ? moi : demandeur;
|
|
ctx.getSource().sendSuccess(() -> succes("Demande de " + nomDem + " acceptée."), false);
|
|
// Délai technique caché (pas de message ni de compte à rebours) ; les messages partent à l'arrivée.
|
|
EN_COURS.add(new Depart(voyageur.getUUID(), destination.getUUID(), r.type() == Type.TPA,
|
|
Math.max(0, TpConfig.get(TpConfig.TPA_DELAI)) * 20));
|
|
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<CommandSourceStack> ctx, String nomCible) throws CommandSyntaxException {
|
|
ServerPlayer moi = ctx.getSource().getPlayerOrException();
|
|
MinecraftServer server = moi.server;
|
|
nettoyerExpirees(server);
|
|
|
|
Optional<Request> 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 if (PseudoMatcher.parseUuidStrict(nomCible).isPresent()) {
|
|
annulee = REGISTRE.cancel(moi.getUUID(), PseudoMatcher.parseUuidStrict(nomCible).get());
|
|
if (annulee.isEmpty()) return echec(ctx, "Tu n'as aucune demande en cours vers ce joueur.");
|
|
} else {
|
|
Cherche c = chercherEnLigne(server, nomCible);
|
|
if (c.ambigu != null) return echec(ctx, c.ambigu);
|
|
ServerPlayer cible = c.joueur;
|
|
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<com.mojang.brigadier.suggestion.Suggestions>
|
|
suggererCibles(CommandContext<CommandSourceStack> ctx, com.mojang.brigadier.suggestion.SuggestionsBuilder b)
|
|
throws CommandSyntaxException {
|
|
ServerPlayer moi = ctx.getSource().getPlayerOrException();
|
|
List<String> 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(PseudoMatcher.suggestions(noms), b);
|
|
}
|
|
|
|
// --- Utilitaires ---
|
|
|
|
/** Résultat de la recherche d'un joueur en ligne : soit un joueur, soit un message d'ambiguïté, soit rien. */
|
|
private record Cherche(ServerPlayer joueur, String ambigu) { }
|
|
|
|
/**
|
|
* Pseudo exact d'abord, puis forme normalisée (sans guillemet etc.) parmi les joueurs en ligne.
|
|
* Si plusieurs comptes ressemblent à la saisie, on ne choisit pas : message avec les candidats.
|
|
*/
|
|
private static Cherche chercherEnLigne(MinecraftServer server, String saisie) {
|
|
List<Profil> enLigne = new ArrayList<>();
|
|
for (ServerPlayer sp : server.getPlayerList().getPlayers()) {
|
|
enLigne.add(new Profil(sp.getUUID(), sp.getGameProfile().getName()));
|
|
}
|
|
PseudoMatcher.Resultat r = PseudoMatcher.resoudreParmi(saisie, enLigne);
|
|
if (r.statut() == PseudoMatcher.Statut.AMBIGU) {
|
|
return new Cherche(null, PseudoMatcher.messageAmbigu(saisie, r.candidats()));
|
|
}
|
|
if (r.trouve()) return new Cherche(server.getPlayerList().getPlayer(r.profil().id()), null);
|
|
return new Cherche(null, null);
|
|
}
|
|
|
|
/** Téléporte vers la position de la destination (même dimension ou non), en gardant le regard du voyageur. */
|
|
private static void teleporter(ServerPlayer voyageur, ServerPlayer destination) {
|
|
ServerLevel niveau = destination.serverLevel();
|
|
voyageur.stopRiding();
|
|
voyageur.teleportTo(niveau, destination.getX(), destination.getY(), destination.getZ(),
|
|
voyageur.getYRot(), voyageur.getXRot());
|
|
}
|
|
|
|
private static void nettoyerExpirees(MinecraftServer server) {
|
|
for (Request r : REGISTRE.purgeExpired()) {
|
|
ServerPlayer de = server.getPlayerList().getPlayer(r.from());
|
|
ServerPlayer vers = server.getPlayerList().getPlayer(r.to());
|
|
String nomDe = de != null ? de.getGameProfile().getName() : "?";
|
|
String nomVers = vers != null ? vers.getGameProfile().getName() : "?";
|
|
if (de != null) {
|
|
de.sendSystemMessage(erreur("Ta demande de téléportation à " + nomVers + " a expiré."));
|
|
}
|
|
if (vers != null) {
|
|
vers.sendSystemMessage(erreur("La demande de téléportation de " + nomDe + " a expiré."));
|
|
}
|
|
}
|
|
}
|
|
|
|
private static java.util.concurrent.CompletableFuture<com.mojang.brigadier.suggestion.Suggestions>
|
|
suggererDemandeurs(CommandContext<CommandSourceStack> ctx, com.mojang.brigadier.suggestion.SuggestionsBuilder b)
|
|
throws CommandSyntaxException {
|
|
ServerPlayer moi = ctx.getSource().getPlayerOrException();
|
|
List<String> noms = new ArrayList<>();
|
|
for (Request r : REGISTRE.pendingFor(moi.getUUID())) {
|
|
ServerPlayer p = moi.server.getPlayerList().getPlayer(r.from());
|
|
if (p != null) noms.add(p.getGameProfile().getName());
|
|
}
|
|
return SharedSuggestionProvider.suggest(PseudoMatcher.suggestions(noms), b);
|
|
}
|
|
|
|
private static MutableComponent bouton(String texte, String commande, ChatFormatting couleur, String survol) {
|
|
return Component.literal(texte).withStyle(Style.EMPTY
|
|
.withColor(couleur)
|
|
.withBold(true)
|
|
.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, commande))
|
|
.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(survol))));
|
|
}
|
|
|
|
private static int echec(CommandContext<CommandSourceStack> ctx, String message) {
|
|
ctx.getSource().sendFailure(Component.literal(message));
|
|
return 0;
|
|
}
|
|
|
|
private static Component info(String s) {
|
|
return Component.literal("[TPA] ").withStyle(ChatFormatting.GOLD)
|
|
.append(Component.literal(s).withStyle(ChatFormatting.YELLOW));
|
|
}
|
|
|
|
private static Component succes(String s) {
|
|
return Component.literal("[TPA] ").withStyle(ChatFormatting.GOLD)
|
|
.append(Component.literal(s).withStyle(ChatFormatting.GREEN));
|
|
}
|
|
|
|
private static Component erreur(String s) {
|
|
return Component.literal("[TPA] ").withStyle(ChatFormatting.GOLD)
|
|
.append(Component.literal(s).withStyle(ChatFormatting.RED));
|
|
}
|
|
}
|