commit 3b34a463768b34d0f0a13ce8037c07dc2880ece1 Author: Theo Gastinel Date: Thu Oct 8 11:28:01 2026 +0200 Mod GastinelTpa : /tpa, /tpahere, /tpaccept, /tpadeny (expiration 1 min) Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cb3b3a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build/ +build-out/ +.gradle/ +run/ +*.jar +!gradle/wrapper/gradle-wrapper.jar diff --git a/build-sur-cornafserver.sh b/build-sur-cornafserver.sh new file mode 100644 index 0000000..243bdc2 --- /dev/null +++ b/build-sur-cornafserver.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Compile GastinelTpa dans un conteneur JDK 21 jetable (rien n'est installé sur l'hôte). +# Usage (sur cornafserver) : sh build-sur-cornafserver.sh -> build/libs/*.jar +set -e +cd "$(dirname "$0")" +mkdir -p "$HOME/.cache/gastineltpa-gradle" +docker run --rm \ + -u "$(id -u):$(id -g)" \ + -e GRADLE_USER_HOME=/gradle-home \ + -v "$HOME/.cache/gastineltpa-gradle:/gradle-home" \ + -v "$(pwd):/src" -w /src \ + eclipse-temurin:21-jdk \ + sh ./gradlew --no-daemon clean test build +ls -l build/libs diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6a34c99 --- /dev/null +++ b/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'java' + id 'net.neoforged.moddev' version '2.0.142' +} + +version = project.mod_version +group = project.mod_group_id +base { archivesName = "${project.mod_id}-neoforge-1.21.1" } + +java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } + +repositories { + mavenCentral() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } +} + +neoForge { + version = project.neoforge_version + runs { + server { + server() + } + } + mods { + "${project.mod_id}" { + sourceSet sourceSets.main + } + } + // Minecraft sur le classpath des tests + unitTest { + enable() + testedMod = mods."${project.mod_id}" + } +} + +dependencies { + // Tests de la logique pure (package core, sans Minecraft) + testImplementation platform('org.junit:junit-bom:5.11.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() + testLogging { events 'passed', 'failed'; exceptionFormat 'full' } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = 21 +} diff --git a/envoyer-et-compiler.sh b/envoyer-et-compiler.sh new file mode 100644 index 0000000..7785e77 --- /dev/null +++ b/envoyer-et-compiler.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Depuis le PC : envoie les sources sur cornafserver (~/staging/GastinelTpa), compile, rapatrie le jar dans build-out/. +set -e +cd "$(dirname "$0")" +tar czf /tmp/gastineltpa-src.tgz --exclude=build --exclude=.gradle --exclude=build-out --exclude=run . +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.0.0.jar' build-out/ +ls -l build-out diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3a3a188 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true + +mod_version=1.0.0 +mod_group_id=com.gastineltpa +mod_id=gastineltpa + +minecraft_version=1.21.1 +neoforge_version=21.1.234 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5dd3c01 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..522f0db --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } + } +} +rootProject.name = 'gastineltpa-neoforge-1.21.1' diff --git a/src/main/java/com/gastineltpa/GastinelTpa.java b/src/main/java/com/gastineltpa/GastinelTpa.java new file mode 100644 index 0000000..b34b6e3 --- /dev/null +++ b/src/main/java/com/gastineltpa/GastinelTpa.java @@ -0,0 +1,19 @@ +package com.gastineltpa; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Mod(GastinelTpa.MOD_ID) +public class GastinelTpa { + + public static final String MOD_ID = "gastineltpa"; + public static final Logger LOGGER = LoggerFactory.getLogger(GastinelTpa.class); + + public GastinelTpa(IEventBus modEventBus) { + NeoForge.EVENT_BUS.register(TpaCommands.class); + LOGGER.info("[GastinelTpa] Demandes de téléportation chargées."); + } +} diff --git a/src/main/java/com/gastineltpa/TpaCommands.java b/src/main/java/com/gastineltpa/TpaCommands.java new file mode 100644 index 0000000..92d8eaf --- /dev/null +++ b/src/main/java/com/gastineltpa/TpaCommands.java @@ -0,0 +1,242 @@ +package com.gastineltpa; + +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 static final TpaRegistry REGISTRE = new TpaRegistry(System::currentTimeMillis); + + @SubscribeEvent + public static void onRegister(RegisterCommandsEvent event) { + CommandDispatcher d = event.getDispatcher(); + + d.register(Commands.literal("tpa") + .then(Commands.argument("joueur", StringArgumentType.word()) + .suggests((ctx, b) -> SharedSuggestionProvider.suggest( + 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( + 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("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); + } + } + + /** 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; + 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 ctx, Type type) throws CommandSyntaxException { + ServerPlayer moi = ctx.getSource().getPlayerOrException(); + MinecraftServer server = moi.server; + nettoyerExpirees(server); + + String nom = StringArgumentType.getString(ctx, "joueur"); + ServerPlayer cible = server.getPlayerList().getPlayerByName(nom); + 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 " + nomMoi, ChatFormatting.GREEN, "Accepter la demande")) + .append(Component.literal(" ")) + .append(bouton("[Refuser]", "/tpadeny " + 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 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 trouvee; + if (nomDemandeur == null) { + trouvee = REGISTRE.latest(moi.getUUID()); + if (trouvee.isEmpty()) { + return echec(ctx, "Aucune demande de téléportation en attente."); + } + } else { + ServerPlayer demandeur = server.getPlayerList().getPlayerByName(nomDemandeur); + 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; + teleporter(voyageur, destination); + + ctx.getSource().sendSuccess(() -> succes("Demande de " + nomDem + " acceptée."), false); + demandeur.sendSystemMessage(succes(nomMoi + " a accepté ta demande de téléportation.")); + return 1; + } + + // --- Utilitaires --- + + /** 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 + suggererDemandeurs(CommandContext ctx, com.mojang.brigadier.suggestion.SuggestionsBuilder b) + throws CommandSyntaxException { + ServerPlayer moi = ctx.getSource().getPlayerOrException(); + List 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(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 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)); + } +} diff --git a/src/main/java/com/gastineltpa/core/TpaRegistry.java b/src/main/java/com/gastineltpa/core/TpaRegistry.java new file mode 100644 index 0000000..b5f1cf2 --- /dev/null +++ b/src/main/java/com/gastineltpa/core/TpaRegistry.java @@ -0,0 +1,106 @@ +package com.gastineltpa.core; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongSupplier; + +/** + * Registre des invitations de téléportation en attente. + * Logique pure (sans Minecraft) : l'horloge est injectable pour les tests. + */ +public final class TpaRegistry { + + /** Durée de vie d'une invitation : 60 secondes. */ + public static final long EXPIRATION_MS = 60_000L; + + /** TPA : le demandeur va vers la cible. TPAHERE : la cible vient vers le demandeur. */ + public enum Type { TPA, TPAHERE } + + public record Request(UUID from, UUID to, Type type, long createdAtMs) { + public boolean expiree(long nowMs) { + return nowMs - createdAtMs >= EXPIRATION_MS; + } + } + + private final LongSupplier clock; + // Ordre d'insertion = ordre chronologique (la plus récente est en dernier). + private final List requests = new ArrayList<>(); + + public TpaRegistry(LongSupplier clockMs) { + this.clock = clockMs; + } + + /** Ajoute une invitation ; remplace l'ancienne du même demandeur vers la même cible. */ + public Request add(UUID from, UUID to, Type type) { + requests.removeIf(r -> r.from().equals(from) && r.to().equals(to)); + Request r = new Request(from, to, type, clock.getAsLong()); + requests.add(r); + return r; + } + + /** Invitation valide (non expirée) d'un demandeur précis vers un destinataire. */ + public Optional find(UUID to, UUID from) { + long now = clock.getAsLong(); + return requests.stream() + .filter(r -> r.to().equals(to) && r.from().equals(from) && !r.expiree(now)) + .findFirst(); + } + + /** Dernière invitation valide reçue par ce destinataire. */ + public Optional latest(UUID to) { + long now = clock.getAsLong(); + Request best = null; + for (Request r : requests) { + if (r.to().equals(to) && !r.expiree(now)) best = r; + } + return Optional.ofNullable(best); + } + + /** Invitations valides reçues par ce destinataire (pour les suggestions). */ + public List pendingFor(UUID to) { + long now = clock.getAsLong(); + List out = new ArrayList<>(); + for (Request r : requests) { + if (r.to().equals(to) && !r.expiree(now)) out.add(r); + } + return out; + } + + public boolean remove(Request r) { + return requests.remove(r); + } + + /** Retire et renvoie les invitations expirées. */ + public List purgeExpired() { + long now = clock.getAsLong(); + List out = new ArrayList<>(); + for (Iterator it = requests.iterator(); it.hasNext(); ) { + Request r = it.next(); + if (r.expiree(now)) { + out.add(r); + it.remove(); + } + } + return out; + } + + /** Retire et renvoie toutes les invitations où ce joueur est demandeur ou destinataire. */ + public List removeInvolving(UUID player) { + List out = new ArrayList<>(); + for (Iterator it = requests.iterator(); it.hasNext(); ) { + Request r = it.next(); + if (r.from().equals(player) || r.to().equals(player)) { + out.add(r); + it.remove(); + } + } + return out; + } + + public int size() { + return requests.size(); + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..0f4bdc0 --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,26 @@ +modLoader="javafml" +loaderVersion="[1,)" +license="MIT" + +[[mods]] +modId="gastineltpa" +version="1.0.0" +displayName="GastinelTpa" +authors="Théo Gastinel" +description='''Demandes de téléportation entre joueurs (/tpa, /tpahere, /tpaccept, /tpadeny). Mod côté serveur uniquement.''' +# Les clients n'ont pas besoin du mod : ne pas exiger sa présence côté client. +displayTest="IGNORE_ALL_VERSION" + +[[dependencies.gastineltpa]] + modId="neoforge" + type="required" + versionRange="[21.1,)" + ordering="NONE" + side="SERVER" + +[[dependencies.gastineltpa]] + modId="minecraft" + type="required" + versionRange="[1.21.1,1.21.2)" + ordering="NONE" + side="SERVER" diff --git a/src/test/java/com/gastineltpa/core/TpaRegistryTest.java b/src/test/java/com/gastineltpa/core/TpaRegistryTest.java new file mode 100644 index 0000000..21826cd --- /dev/null +++ b/src/test/java/com/gastineltpa/core/TpaRegistryTest.java @@ -0,0 +1,100 @@ +package com.gastineltpa.core; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +class TpaRegistryTest { + + private long now; + private TpaRegistry reg; + private final UUID a = UUID.randomUUID(); + private final UUID b = UUID.randomUUID(); + private final UUID c = UUID.randomUUID(); + + @BeforeEach + void init() { + now = 1_000_000L; + reg = new TpaRegistry(() -> now); + } + + @Test + void invitationValideAvantExpiration() { + reg.add(a, b, TpaRegistry.Type.TPA); + now += 59_999; + assertTrue(reg.find(b, a).isPresent()); + assertTrue(reg.purgeExpired().isEmpty()); + } + + @Test + void expireApres60Secondes() { + reg.add(a, b, TpaRegistry.Type.TPA); + now += 60_000; + assertTrue(reg.find(b, a).isEmpty()); + assertTrue(reg.latest(b).isEmpty()); + List exp = reg.purgeExpired(); + assertEquals(1, exp.size()); + assertEquals(0, reg.size()); + } + + @Test + void derniereInvitation() { + reg.add(a, b, TpaRegistry.Type.TPA); + now += 1000; + reg.add(c, b, TpaRegistry.Type.TPAHERE); + assertEquals(c, reg.latest(b).orElseThrow().from()); + now += 59_000; // a : 60 s -> expirée ; c : 59 s -> valide + assertEquals(c, reg.latest(b).orElseThrow().from()); + now += 1000; + assertTrue(reg.latest(b).isEmpty()); + } + + @Test + void remplacementMemeDemandeurMemeCible() { + reg.add(a, b, TpaRegistry.Type.TPA); + now += 30_000; + reg.add(a, b, TpaRegistry.Type.TPAHERE); + assertEquals(1, reg.size()); + assertEquals(TpaRegistry.Type.TPAHERE, reg.find(b, a).orElseThrow().type()); + now += 40_000; // le délai repart de zéro + assertTrue(reg.find(b, a).isPresent()); + } + + @Test + void remplacementRedonneLaPlaceDeDerniere() { + reg.add(a, b, TpaRegistry.Type.TPA); + reg.add(c, b, TpaRegistry.Type.TPA); + reg.add(a, b, TpaRegistry.Type.TPA); + assertEquals(a, reg.latest(b).orElseThrow().from()); + } + + @Test + void annulationALaDeconnexion() { + reg.add(a, b, TpaRegistry.Type.TPA); + reg.add(b, c, TpaRegistry.Type.TPAHERE); + reg.add(a, c, TpaRegistry.Type.TPA); + List out = reg.removeInvolving(b); + assertEquals(2, out.size()); + assertEquals(1, reg.size()); + assertTrue(reg.find(c, a).isPresent()); + } + + @Test + void retraitApresUtilisation() { + TpaRegistry.Request r = reg.add(a, b, TpaRegistry.Type.TPA); + assertTrue(reg.remove(r)); + assertTrue(reg.find(b, a).isEmpty()); + assertFalse(reg.remove(r)); + } + + @Test + void pendingForIgnoreLesAutres() { + reg.add(a, b, TpaRegistry.Type.TPA); + reg.add(a, c, TpaRegistry.Type.TPA); + assertEquals(1, reg.pendingFor(b).size()); + } +}