Mod GastinelClaims : /claim, /unclaim, /friend (NeoForge 1.21.1, serveur seul)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Theo GastineletClaude Opus 5.5 a révisé 2026-10-08 11:28:00 +02:00
révision f7ea72ed99
20 fichiers modifiés
+1267

Aucun fichier ne correspond à votre recherche

+6
Voir le fichier
@@ -0,0 +1,6 @@
build/
build-out/
.gradle/
run/
*.jar
!gradle/wrapper/gradle-wrapper.jar
+26
Voir le fichier
@@ -0,0 +1,26 @@
# GastinelClaims
Protection de terrains par chunk pour NeoForge 1.21.1 (21.1.234). **Mod côté serveur uniquement** : les clients n'ont rien à installer (`displayTest="IGNORE_ALL_VERSION"`, aucun bloc/objet/paquet réseau, messages en texte brut).
## Commandes
- `/claim` : protège le chunk courant (toute la hauteur). Refus si déjà pris (avec le nom du propriétaire) ou limite atteinte.
- `/claim info` : à qui est le chunk + claims restants.
- `/unclaim` : libère le chunk courant s'il est à toi.
- `/friend`, `/friend add <pseudo>`, `/friend unadd <pseudo>` : un ami a accès à tous tes claims. Le pseudo doit être connu du serveur (en ligne ou déjà venu). Stocké par UUID.
## Config
`config/gastinelclaims-server.toml` : `maxClaimsParJoueur = 25`.
## Protections (si ni propriétaire, ni ami, ni op niveau 2+)
Casser/poser des blocs, clic droit sur un bloc (coffres, portes, leviers, boutons, machines Create...), case voisine du clic quand on tient un objet (feu, liquide), seaux visant le claim, piétinement des cultures, perles de l'Ender qui atterrissent dans le claim, frapper ou interagir avec les entités non hostiles (animaux, cadres, supports d'armure). Commerce avec les villageois autorisé. Les explosions ne cassent pas les blocs claimés ni les entités non hostiles dedans. Marcher reste autorisé.
## Données
`<monde>/data/gastinelclaims.dat` (overworld, toutes dimensions dedans).
## Limites connues
- **FakePlayer (Create deployer...)** : la machine agit pour le propriétaire du chunk où elle se trouve. Machine dans ton claim (ou celui d'un joueur dont tu es l'ami) -> OK ; machine hors claim -> refus dans un claim. Ne marche que pour les actions qui passent par les événements NeoForge avec un FakePlayer. Les perceuses/scies Create, les contraptions en mouvement et les pistons ne passent pas par là : **ils peuvent casser/déplacer des blocs d'un claim voisin**.
- **Propagation du feu** : pas bloquée (pas d'événement NeoForge simple). Allumer est bloqué. Conseil : `gamerule doFireTick false`.
- Lave/eau qui coule d'un chunk voisin, flèches/projectiles sur les cadres, dispensers : non bloqués.
## Build (sur cornafserver, pas sur le PC)
Copier le dossier puis `sh build-sur-cornafserver.sh` (conteneur `eclipse-temurin:21-jdk` jetable, cache Gradle dans `~/.cache/gastinelclaims-gradle`). Lance les tests JUnit puis produit `build/libs/gastinelclaims-neoforge-1.21.1-1.0.0.jar`.
+14
Voir le fichier
@@ -0,0 +1,14 @@
#!/bin/sh
# Compile GastinelClaims 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/gastinelclaims-gradle"
docker run --rm \
-u "$(id -u):$(id -g)" \
-e GRADLE_USER_HOME=/gradle-home \
-v "$HOME/.cache/gastinelclaims-gradle:/gradle-home" \
-v "$(pwd):/src" -w /src \
eclipse-temurin:21-jdk \
sh ./gradlew --no-daemon clean test build
ls -l build/libs
+51
Voir le fichier
@@ -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 (pour le test NBT de ClaimsData)
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
}
+9
Voir le fichier
@@ -0,0 +1,9 @@
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
mod_version=1.0.0
mod_group_id=com.gastinelclaims
mod_id=gastinelclaims
minecraft_version=1.21.1
neoforge_version=21.1.234
BIN
Voir le fichier
Fichier binaire non affiché.
+7
Voir le fichier
@@ -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
Externe
+248
Voir le fichier
@@ -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" "$@"
+82
Voir le fichier
@@ -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%
+8
Voir le fichier
@@ -0,0 +1,8 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' }
}
}
rootProject.name = 'gastinelclaims-neoforge-1.21.1'
+197
Voir le fichier
@@ -0,0 +1,197 @@
package com.gastinelclaims;
import com.gastinelclaims.core.ChunkKey;
import com.gastinelclaims.core.ClaimRegistry;
import com.mojang.authlib.GameProfile;
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.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/** /claim, /claim info, /unclaim, /friend [add|unadd <pseudo>] */
public final class ClaimCommands {
@SubscribeEvent
public static void onRegister(RegisterCommandsEvent event) {
CommandDispatcher<CommandSourceStack> d = event.getDispatcher();
d.register(Commands.literal("claim")
.executes(ClaimCommands::claim)
.then(Commands.literal("info").executes(ClaimCommands::info)));
d.register(Commands.literal("unclaim").executes(ClaimCommands::unclaim));
d.register(Commands.literal("friend")
.executes(ClaimCommands::listFriends)
.then(Commands.literal("add")
.then(Commands.argument("pseudo", StringArgumentType.word())
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(
ctx.getSource().getServer().getPlayerNames(), b))
.executes(ctx -> addFriend(ctx, StringArgumentType.getString(ctx, "pseudo")))))
.then(Commands.literal("unadd")
.then(Commands.argument("pseudo", StringArgumentType.word())
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(friendNames(ctx), b))
.executes(ctx -> removeFriend(ctx, StringArgumentType.getString(ctx, "pseudo"))))));
}
// --- Claims ---
private static int claim(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
ClaimsData data = ClaimsData.get(p.server);
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
int max = ClaimsConfig.maxClaims();
ClaimRegistry r = data.registry();
switch (r.claim(p.getUUID(), key, max)) {
case OK -> {
data.setDirty();
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] protégé. Claims : "
+ r.countOf(p.getUUID()) + "/" + max + ".");
return 1;
}
case ALREADY_YOURS -> fail(ctx, "Ce chunk est déjà à toi.");
case CLAIMED_BY_OTHER -> fail(ctx, "Ce chunk est déjà claim par " + nameOf(p.server, r.ownerOf(key)) + ".");
case LIMIT_REACHED -> fail(ctx, "Limite atteinte (" + max + " chunks). Fais /unclaim ailleurs d'abord.");
}
return 0;
}
private static int unclaim(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
ClaimsData data = ClaimsData.get(p.server);
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
switch (data.registry().unclaim(p.getUUID(), key)) {
case OK -> {
data.setDirty();
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] libéré.");
return 1;
}
case NOT_CLAIMED -> fail(ctx, "Ce chunk n'est pas claim.");
case NOT_OWNER -> fail(ctx, "Ce chunk appartient à " + nameOf(p.server, data.registry().ownerOf(key)) + ".");
}
return 0;
}
private static int info(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
ClaimRegistry r = ClaimsData.get(p.server).registry();
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
UUID owner = r.ownerOf(key);
int max = ClaimsConfig.maxClaims();
int left = Math.max(0, max - r.countOf(p.getUUID()));
String who = owner == null ? "libre" : "à " + nameOf(p.server, owner);
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] : " + who + ". Il te reste " + left + "/" + max + " claims.");
return 1;
}
// --- Amis ---
private static int listFriends(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
var friends = ClaimsData.get(p.server).registry().friendsOf(p.getUUID());
if (friends.isEmpty()) {
ok(ctx, "Aucun ami. Ajoute-en avec /friend add <pseudo>.");
} else {
List<String> names = new ArrayList<>();
for (UUID u : friends) names.add(nameOf(p.server, u));
ok(ctx, "Amis (" + names.size() + ") : " + String.join(", ", names));
}
return 1;
}
private static int addFriend(CommandContext<CommandSourceStack> ctx, String name) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
Optional<GameProfile> target = resolve(p.server, name);
if (target.isEmpty()) {
fail(ctx, "Joueur inconnu du serveur : " + name + ".");
return 0;
}
ClaimsData data = ClaimsData.get(p.server);
switch (data.registry().addFriend(p.getUUID(), target.get().getId())) {
case OK -> {
data.setDirty();
ok(ctx, target.get().getName() + " a maintenant accès à tous tes claims.");
return 1;
}
case SELF -> fail(ctx, "Tu ne peux pas t'ajouter toi-même.");
case ALREADY -> fail(ctx, target.get().getName() + " est déjà ton ami.");
default -> { }
}
return 0;
}
private static int removeFriend(CommandContext<CommandSourceStack> ctx, String name) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
ClaimsData data = ClaimsData.get(p.server);
// On cherche d'abord dans la liste d'amis (marche même si le cache de profils a oublié le pseudo)
UUID friend = null;
for (UUID u : data.registry().friendsOf(p.getUUID())) {
if (nameOf(p.server, u).equalsIgnoreCase(name)) { friend = u; break; }
}
if (friend == null) {
friend = resolve(p.server, name).map(GameProfile::getId).orElse(null);
}
if (friend == null || data.registry().removeFriend(p.getUUID(), friend) != ClaimRegistry.FriendResult.OK) {
fail(ctx, name + " n'est pas dans ta liste d'amis.");
return 0;
}
data.setDirty();
ok(ctx, name + " n'a plus accès à tes claims.");
return 1;
}
// --- Utilitaires ---
/** Pseudo -> profil : joueur en ligne, sinon cache de profils du serveur (joueurs déjà venus). */
private static Optional<GameProfile> resolve(MinecraftServer server, String name) {
ServerPlayer online = server.getPlayerList().getPlayerByName(name);
if (online != null) return Optional.of(online.getGameProfile());
if (server.getProfileCache() == null) return Optional.empty();
return server.getProfileCache().get(name);
}
public static String nameOf(MinecraftServer server, UUID uuid) {
if (uuid == null) return "?";
ServerPlayer online = server.getPlayerList().getPlayer(uuid);
if (online != null) return online.getGameProfile().getName();
if (server.getProfileCache() != null) {
Optional<GameProfile> prof = server.getProfileCache().get(uuid);
if (prof.isPresent()) return prof.get().getName();
}
return uuid.toString().substring(0, 8);
}
private static List<String> friendNames(CommandContext<CommandSourceStack> ctx) {
ServerPlayer p = ctx.getSource().getPlayer();
if (p == null) return List.of();
List<String> names = new ArrayList<>();
for (UUID u : ClaimsData.get(p.server).registry().friendsOf(p.getUUID())) names.add(nameOf(p.server, u));
return names;
}
private static void ok(CommandContext<CommandSourceStack> ctx, String msg) {
ctx.getSource().sendSuccess(() -> Component.literal(msg), false);
}
private static void fail(CommandContext<CommandSourceStack> ctx, String msg) {
ctx.getSource().sendFailure(Component.literal(msg));
}
private ClaimCommands() {}
}
+23
Voir le fichier
@@ -0,0 +1,23 @@
package com.gastinelclaims;
import net.neoforged.neoforge.common.ModConfigSpec;
public final class ClaimsConfig {
public static final ModConfigSpec SPEC;
public static final ModConfigSpec.IntValue MAX_CLAIMS;
static {
ModConfigSpec.Builder b = new ModConfigSpec.Builder();
MAX_CLAIMS = b.comment("Nombre maximum de chunks qu'un joueur peut claim.")
.defineInRange("maxClaimsParJoueur", 25, 0, 100000);
SPEC = b.build();
}
public static int maxClaims() {
// Si la config n'est pas encore chargée, on prend la valeur par défaut
return SPEC.isLoaded() ? MAX_CLAIMS.get() : MAX_CLAIMS.getDefault();
}
private ClaimsConfig() {}
}
+89
Voir le fichier
@@ -0,0 +1,89 @@
package com.gastinelclaims;
import com.gastinelclaims.core.ChunkKey;
import com.gastinelclaims.core.ClaimRegistry;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.saveddata.SavedData;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Sauvegarde des claims (toutes dimensions) dans data/gastinelclaims.dat de l'overworld.
* Le registre en mémoire est une HashMap : recherche en O(1) par chunk.
*/
public final class ClaimsData extends SavedData {
private static final String NAME = "gastinelclaims";
private final ClaimRegistry registry = new ClaimRegistry();
public static final SavedData.Factory<ClaimsData> FACTORY =
new SavedData.Factory<>(ClaimsData::new, ClaimsData::load, null);
public static ClaimsData get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(FACTORY, NAME);
}
public ClaimRegistry registry() {
return registry;
}
public static ChunkKey key(Level level, BlockPos pos) {
return ChunkKey.ofBlock(level.dimension().location().toString(), pos.getX(), pos.getZ());
}
static ClaimsData load(CompoundTag tag, HolderLookup.Provider provider) {
ClaimsData data = new ClaimsData();
ListTag claims = tag.getList("claims", Tag.TAG_COMPOUND);
for (int i = 0; i < claims.size(); i++) {
CompoundTag c = claims.getCompound(i);
data.registry.put(new ChunkKey(c.getString("dim"), c.getInt("x"), c.getInt("z")), c.getUUID("owner"));
}
ListTag friends = tag.getList("friends", Tag.TAG_COMPOUND);
for (int i = 0; i < friends.size(); i++) {
CompoundTag f = friends.getCompound(i);
UUID owner = f.getUUID("owner");
ListTag list = f.getList("friends", Tag.TAG_INT_ARRAY);
for (Tag t : list) {
data.registry.addFriend(owner, NbtUtils.loadUUID(t));
}
}
GastinelClaims.LOGGER.info("[GastinelClaims] {} claims chargés.", claims.size());
return data;
}
@Override
public CompoundTag save(CompoundTag tag, HolderLookup.Provider provider) {
ListTag claims = new ListTag();
for (Map.Entry<ChunkKey, UUID> e : registry.allClaims().entrySet()) {
CompoundTag c = new CompoundTag();
c.putString("dim", e.getKey().dimension());
c.putInt("x", e.getKey().x());
c.putInt("z", e.getKey().z());
c.putUUID("owner", e.getValue());
claims.add(c);
}
tag.put("claims", claims);
ListTag friends = new ListTag();
for (Map.Entry<UUID, Set<UUID>> e : registry.allFriends().entrySet()) {
CompoundTag f = new CompoundTag();
f.putUUID("owner", e.getKey());
ListTag list = new ListTag();
for (UUID u : e.getValue()) list.add(NbtUtils.createUUID(u));
f.put("friends", list);
friends.add(f);
}
tag.put("friends", friends);
return tag;
}
}
+26
Voir le fichier
@@ -0,0 +1,26 @@
package com.gastinelclaims;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.neoforge.common.NeoForge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Mod(GastinelClaims.MOD_ID)
public class GastinelClaims {
public static final String MOD_ID = "gastinelclaims";
public static final Logger LOGGER = LoggerFactory.getLogger(GastinelClaims.class);
public GastinelClaims(IEventBus modEventBus, ModContainer modContainer) {
// Config serveur : <monde>/serverconfig/gastinelclaims-server.toml
modContainer.registerConfig(ModConfig.Type.SERVER, ClaimsConfig.SPEC);
NeoForge.EVENT_BUS.register(ClaimCommands.class);
NeoForge.EVENT_BUS.register(ProtectionEvents.class);
LOGGER.info("[GastinelClaims] Protection de terrains chargée.");
}
}
+192
Voir le fichier
@@ -0,0 +1,192 @@
package com.gastinelclaims;
import com.gastinelclaims.core.ChunkKey;
import com.gastinelclaims.core.ClaimRegistry;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.npc.AbstractVillager;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BucketItem;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.entity.monster.Enemy;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.common.util.FakePlayer;
import net.neoforged.neoforge.event.entity.EntityTeleportEvent;
import net.neoforged.neoforge.event.entity.player.AttackEntityEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.level.BlockEvent;
import net.neoforged.neoforge.event.level.ExplosionEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/** Tous les refus dans les claims. Le passage à pied n'est jamais bloqué. */
public final class ProtectionEvents {
private static final long SPAM_MS = 1500;
private static final Map<UUID, Long> lastMessage = new HashMap<>();
// --- Règle centrale ---
/**
* Le joueur peut-il agir sur ce bloc ?
* FakePlayer (Create deployer...) : on prend comme "acteur" le propriétaire du chunk où se trouve
* la machine. Une machine hors claim n'a donc accès à aucun claim.
*/
static boolean allowed(Player player, Level level, BlockPos target) {
if (level.isClientSide() || player.getServer() == null) return true;
ClaimRegistry r = ClaimsData.get(player.getServer()).registry();
ChunkKey key = ClaimsData.key(level, target);
if (r.ownerOf(key) == null) return true; // cas le plus fréquent, on sort vite
if (player instanceof FakePlayer) {
UUID machineOwner = r.ownerOf(ClaimsData.key(level, player.blockPosition()));
return r.canAccess(machineOwner, key, false);
}
return r.canAccess(player.getUUID(), key, player.hasPermissions(2));
}
/** Vérifie et, si refusé, prévient le joueur (actionbar, anti-spam). */
private static boolean deny(Player player, Level level, BlockPos target) {
if (allowed(player, level, target)) return false;
warn(player, level, target);
return true;
}
private static void warn(Player player, Level level, BlockPos target) {
if (!(player instanceof ServerPlayer sp) || player instanceof FakePlayer) return;
long now = System.currentTimeMillis();
Long last = lastMessage.get(sp.getUUID());
if (last != null && now - last < SPAM_MS) return;
lastMessage.put(sp.getUUID(), now);
MinecraftServer server = sp.server;
UUID owner = ClaimsData.get(server).registry().ownerOf(ClaimsData.key(level, target));
sp.displayClientMessage(Component.literal("Terrain protégé (" + ClaimCommands.nameOf(server, owner) + ")")
.withStyle(ChatFormatting.RED), true);
}
/** Entités "non hostiles" protégées : animaux, cadres, supports d'armure, villageois... (pas les joueurs). */
private static boolean isProtectedEntity(Entity e) {
return !(e instanceof Enemy) && !(e instanceof Player);
}
// --- Blocs ---
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onBreak(BlockEvent.BreakEvent event) {
if (event.getLevel() instanceof Level level && deny(event.getPlayer(), level, event.getPos())) {
event.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onPlace(BlockEvent.EntityPlaceEvent event) {
// Couvre aussi EntityMultiPlaceEvent (lits, portes...)
if (event.getEntity() instanceof Player p && event.getLevel() instanceof Level level
&& deny(p, level, event.getPos())) {
event.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onTrample(BlockEvent.FarmlandTrampleEvent event) {
if (event.getEntity() instanceof Player p && event.getLevel() instanceof Level level
&& !allowed(p, level, event.getPos())) {
event.setCanceled(true);
}
}
/** Clic droit sur un bloc : coffres, portes, leviers, boutons, machines Create, briquet, seaux... */
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {
Player p = event.getEntity();
Level level = event.getLevel();
BlockPos pos = event.getPos();
boolean refuse = deny(p, level, pos);
// Avec un objet en main, ce qui est posé atterrit sur la case voisine (feu, liquide, bloc)
if (!refuse && !event.getItemStack().isEmpty() && event.getFace() != null) {
refuse = deny(p, level, pos.relative(event.getFace()));
}
if (refuse) event.setCanceled(true);
}
/** Seau utilisé "dans le vide" (vise un liquide ou un bloc à distance). */
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onRightClickItem(PlayerInteractEvent.RightClickItem event) {
if (!(event.getItemStack().getItem() instanceof BucketItem)) return;
Player p = event.getEntity();
Level level = event.getLevel();
Vec3 eye = p.getEyePosition();
Vec3 end = eye.add(p.getViewVector(1.0F).scale(p.blockInteractionRange()));
BlockHitResult hit = level.clip(new ClipContext(eye, end, ClipContext.Block.OUTLINE,
ClipContext.Fluid.SOURCE_ONLY, p));
if (hit.getType() != HitResult.Type.BLOCK) return;
if (deny(p, level, hit.getBlockPos()) || deny(p, level, hit.getBlockPos().relative(hit.getDirection()))) {
event.setCanceled(true);
}
}
// --- Entités ---
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onAttack(AttackEntityEvent event) {
Entity target = event.getTarget();
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
event.setCanceled(true);
}
}
/** Clic droit sur une entité (cadre, support d'armure, laisse, cisailles...). Commerce avec les villageois autorisé. */
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onEntityInteract(PlayerInteractEvent.EntityInteract event) {
Entity target = event.getTarget();
if (target instanceof AbstractVillager) return;
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
event.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific event) {
Entity target = event.getTarget();
if (target instanceof AbstractVillager) return;
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
event.setCanceled(true);
}
}
// --- Perles de l'Ender ---
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onPearl(EntityTeleportEvent.EnderPearl event) {
ServerPlayer p = event.getPlayer();
BlockPos dest = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ());
if (deny(p, p.level(), dest)) {
event.setCanceled(true);
}
}
// --- Explosions ---
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onExplosion(ExplosionEvent.Detonate event) {
Level level = event.getLevel();
if (level.isClientSide() || level.getServer() == null) return;
ClaimRegistry r = ClaimsData.get(level.getServer()).registry();
event.getAffectedBlocks().removeIf(pos -> r.ownerOf(ClaimsData.key(level, pos)) != null);
event.getAffectedEntities().removeIf(e -> isProtectedEntity(e)
&& r.ownerOf(ClaimsData.key(level, e.blockPosition())) != null);
}
private ProtectionEvents() {}
}
+10
Voir le fichier
@@ -0,0 +1,10 @@
package com.gastinelclaims.core;
/** Identifie une colonne de chunk : dimension (ex. "minecraft:overworld") + coordonnées de chunk. */
public record ChunkKey(String dimension, int x, int z) {
/** Chunk contenant le bloc (x, z) en coordonnées de bloc. */
public static ChunkKey ofBlock(String dimension, int blockX, int blockZ) {
return new ChunkKey(dimension, blockX >> 4, blockZ >> 4);
}
}
+105
Voir le fichier
@@ -0,0 +1,105 @@
package com.gastinelclaims.core;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Registre des claims et des amis. Logique pure : aucune classe Minecraft ici,
* pour pouvoir la tester avec JUnit.
*
* Un claim = une colonne de chunk entière (toute la hauteur) dans une dimension.
*/
public final class ClaimRegistry {
public enum ClaimResult { OK, ALREADY_YOURS, CLAIMED_BY_OTHER, LIMIT_REACHED }
public enum UnclaimResult { OK, NOT_CLAIMED, NOT_OWNER }
public enum FriendResult { OK, SELF, ALREADY, NOT_FRIEND }
private final Map<ChunkKey, UUID> owners = new HashMap<>();
private final Map<UUID, Integer> counts = new HashMap<>();
private final Map<UUID, Set<UUID>> friends = new HashMap<>();
// --- Claims ---
public ClaimResult claim(UUID player, ChunkKey key, int maxClaims) {
UUID owner = owners.get(key);
if (owner != null) {
return owner.equals(player) ? ClaimResult.ALREADY_YOURS : ClaimResult.CLAIMED_BY_OTHER;
}
if (countOf(player) >= maxClaims) {
return ClaimResult.LIMIT_REACHED;
}
put(key, player);
return ClaimResult.OK;
}
public UnclaimResult unclaim(UUID player, ChunkKey key) {
UUID owner = owners.get(key);
if (owner == null) return UnclaimResult.NOT_CLAIMED;
if (!owner.equals(player)) return UnclaimResult.NOT_OWNER;
owners.remove(key);
counts.merge(player, -1, (a, b) -> a + b <= 0 ? null : a + b);
return UnclaimResult.OK;
}
/** Ajout brut (chargement depuis la sauvegarde), sans contrôle de limite. */
public void put(ChunkKey key, UUID owner) {
UUID previous = owners.put(key, owner);
if (previous != null) {
counts.merge(previous, -1, (a, b) -> a + b <= 0 ? null : a + b);
}
counts.merge(owner, 1, Integer::sum);
}
public UUID ownerOf(ChunkKey key) {
return owners.get(key);
}
public int countOf(UUID player) {
return counts.getOrDefault(player, 0);
}
public Map<ChunkKey, UUID> allClaims() {
return Collections.unmodifiableMap(owners);
}
// --- Amis ---
public FriendResult addFriend(UUID owner, UUID friend) {
if (owner.equals(friend)) return FriendResult.SELF;
boolean added = friends.computeIfAbsent(owner, k -> new LinkedHashSet<>()).add(friend);
return added ? FriendResult.OK : FriendResult.ALREADY;
}
public FriendResult removeFriend(UUID owner, UUID friend) {
Set<UUID> set = friends.get(owner);
if (set == null || !set.remove(friend)) return FriendResult.NOT_FRIEND;
if (set.isEmpty()) friends.remove(owner);
return FriendResult.OK;
}
public Set<UUID> friendsOf(UUID owner) {
return Collections.unmodifiableSet(friends.getOrDefault(owner, Set.of()));
}
public Map<UUID, Set<UUID>> allFriends() {
return Collections.unmodifiableMap(friends);
}
// --- Règle d'accès ---
/**
* @param actor joueur qui agit ; null = inconnu (ex. machine hors claim) -> refusé dans un claim
* @param bypass vrai pour un op (niveau 2+)
*/
public boolean canAccess(UUID actor, ChunkKey key, boolean bypass) {
UUID owner = owners.get(key);
if (owner == null || bypass) return true;
if (actor == null) return false;
return owner.equals(actor) || friendsOf(owner).contains(actor);
}
}
+26
Voir le fichier
@@ -0,0 +1,26 @@
modLoader="javafml"
loaderVersion="[1,)"
license="MIT"
[[mods]]
modId="gastinelclaims"
version="1.0.0"
displayName="GastinelClaims"
authors="Théo Gastinel"
description='''Protection de terrains par chunk (/claim, /unclaim, /friend). 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.gastinelclaims]]
modId="neoforge"
type="required"
versionRange="[21.1,)"
ordering="NONE"
side="SERVER"
[[dependencies.gastinelclaims]]
modId="minecraft"
type="required"
versionRange="[1.21.1,1.21.2)"
ordering="NONE"
side="SERVER"
+32
Voir le fichier
@@ -0,0 +1,32 @@
package com.gastinelclaims;
import com.gastinelclaims.core.ChunkKey;
import net.minecraft.nbt.CompoundTag;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
/** Aller-retour NBT : ce qui est sauvegardé doit être relu à l'identique. */
class ClaimsDataTest {
@Test
void sauvegardeEtRelecture() {
UUID theo = UUID.randomUUID(), ami = UUID.randomUUID();
ClaimsData data = new ClaimsData();
ChunkKey a = new ChunkKey("minecraft:overworld", -3, 7);
ChunkKey b = new ChunkKey("minecraft:the_nether", 0, 0);
data.registry().claim(theo, a, 25);
data.registry().claim(theo, b, 25);
data.registry().addFriend(theo, ami);
CompoundTag tag = data.save(new CompoundTag(), null);
ClaimsData relu = ClaimsData.load(tag, null);
assertEquals(theo, relu.registry().ownerOf(a));
assertEquals(theo, relu.registry().ownerOf(b));
assertEquals(2, relu.registry().countOf(theo));
assertTrue(relu.registry().canAccess(ami, a, false));
}
}
+116
Voir le fichier
@@ -0,0 +1,116 @@
package com.gastinelclaims.core;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static com.gastinelclaims.core.ClaimRegistry.*;
import static org.junit.jupiter.api.Assertions.*;
class ClaimRegistryTest {
private static final String OW = "minecraft:overworld";
private final UUID theo = UUID.randomUUID();
private final UUID ami = UUID.randomUUID();
private final UUID autre = UUID.randomUUID();
private final ChunkKey c00 = new ChunkKey(OW, 0, 0);
@Test
void chunkKeyDepuisBloc() {
assertEquals(new ChunkKey(OW, 0, 0), ChunkKey.ofBlock(OW, 15, 0));
assertEquals(new ChunkKey(OW, -1, -1), ChunkKey.ofBlock(OW, -1, -16));
assertEquals(new ChunkKey(OW, 1, -2), ChunkKey.ofBlock(OW, 16, -17));
assertNotEquals(new ChunkKey(OW, 0, 0), new ChunkKey("minecraft:the_nether", 0, 0));
}
@Test
void claimEtRefus() {
ClaimRegistry r = new ClaimRegistry();
assertEquals(ClaimResult.OK, r.claim(theo, c00, 25));
assertEquals(theo, r.ownerOf(c00));
assertEquals(ClaimResult.ALREADY_YOURS, r.claim(theo, c00, 25));
assertEquals(ClaimResult.CLAIMED_BY_OTHER, r.claim(autre, c00, 25));
assertEquals(1, r.countOf(theo));
assertEquals(0, r.countOf(autre));
}
@Test
void limiteDe25() {
ClaimRegistry r = new ClaimRegistry();
for (int i = 0; i < 25; i++) {
assertEquals(ClaimResult.OK, r.claim(theo, new ChunkKey(OW, i, 0), 25));
}
assertEquals(ClaimResult.LIMIT_REACHED, r.claim(theo, new ChunkKey(OW, 99, 0), 25));
assertEquals(25, r.countOf(theo));
// Libérer un chunk redonne une place
assertEquals(UnclaimResult.OK, r.unclaim(theo, new ChunkKey(OW, 0, 0)));
assertEquals(ClaimResult.OK, r.claim(theo, new ChunkKey(OW, 99, 0), 25));
}
@Test
void limiteConfigurable() {
ClaimRegistry r = new ClaimRegistry();
assertEquals(ClaimResult.OK, r.claim(theo, c00, 1));
assertEquals(ClaimResult.LIMIT_REACHED, r.claim(theo, new ChunkKey(OW, 1, 0), 1));
}
@Test
void unclaim() {
ClaimRegistry r = new ClaimRegistry();
assertEquals(UnclaimResult.NOT_CLAIMED, r.unclaim(theo, c00));
r.claim(theo, c00, 25);
assertEquals(UnclaimResult.NOT_OWNER, r.unclaim(autre, c00));
assertEquals(UnclaimResult.OK, r.unclaim(theo, c00));
assertNull(r.ownerOf(c00));
assertEquals(0, r.countOf(theo));
}
@Test
void amis() {
ClaimRegistry r = new ClaimRegistry();
assertEquals(FriendResult.SELF, r.addFriend(theo, theo));
assertEquals(FriendResult.OK, r.addFriend(theo, ami));
assertEquals(FriendResult.ALREADY, r.addFriend(theo, ami));
assertTrue(r.friendsOf(theo).contains(ami));
// L'amitié n'est pas réciproque
assertFalse(r.friendsOf(ami).contains(theo));
assertEquals(FriendResult.OK, r.removeFriend(theo, ami));
assertEquals(FriendResult.NOT_FRIEND, r.removeFriend(theo, ami));
assertTrue(r.friendsOf(theo).isEmpty());
}
@Test
void reglesAcces() {
ClaimRegistry r = new ClaimRegistry();
ChunkKey libre = new ChunkKey(OW, 5, 5);
// Chunk libre : tout le monde, même une machine sans propriétaire
assertTrue(r.canAccess(autre, libre, false));
assertTrue(r.canAccess(null, libre, false));
r.claim(theo, c00, 25);
ChunkKey c10 = new ChunkKey(OW, 1, 0);
r.claim(theo, c10, 25);
assertTrue(r.canAccess(theo, c00, false));
assertFalse(r.canAccess(autre, c00, false));
assertFalse(r.canAccess(ami, c00, false));
assertFalse(r.canAccess(null, c00, false));
// Op
assertTrue(r.canAccess(autre, c00, true));
// Un ami a accès à TOUS les claims
r.addFriend(theo, ami);
assertTrue(r.canAccess(ami, c00, false));
assertTrue(r.canAccess(ami, c10, false));
r.removeFriend(theo, ami);
assertFalse(r.canAccess(ami, c10, false));
}
@Test
void putRecompteLesProprietaires() {
ClaimRegistry r = new ClaimRegistry();
r.put(c00, theo);
r.put(c00, autre);
assertEquals(0, r.countOf(theo));
assertEquals(1, r.countOf(autre));
}
}