Rodion Khaliullin

https://modrinth.com/mod/bonk-xp-multiplier/version/uugrAjoG портируй этот мод для версии fabric 26.3

Kodari AI
KodariOct 7 at 2:26 pm 5
BonkXpMultiplierPort
Ports the Bonk XP Multiplier mod to Minecraft Fabric 26.3. This mod adds a configurable experience multiplier system that increases XP gain from all sources including mob kills, mining, and crafting. Features include adjustable multiplier values via configuration file, real-time XP boost application, and compatibility with existing XP mechanics. The mod intercepts XP gain events and applies the configured multiplier before adding experience to the player. Includes a simple configuration system allowing server administrators to set global or per-player multipliers. Designed for seamless integration with vanilla gameplay while providing enhanced progression speed for players who prefer faster leveling.

Реализую порт как серверный Fabric-мод для 26.3:

  • Масштабирование XP в общей точке создания орбов — без двойного применения для разных источников.

  • Отдельная ставка для мобов, переопределения по типу, blacklist и обработка убийств игроком.

  • JSON-конфиг и админ-команды /xpmult; добавлю Gradle, metadata и mixin-конфигурацию.

Создал серверный Fabric-мод для Minecraft 26.3 с основными возможностями Bonk’s XP Multiplier: раздельные множители для мобов и остальных источников XP, настройки по типу моба, blacklist и корректная обработка дробных множителей. Учтены обычные награды мобов и особый путь опыта дракона.

Настройки создаются в config/xpmultiplier.json. Команды для модераторов: /xpmult или /xpmult status, /xpmult set <0–64>, /xpmult other <0–64>, /xpmult enabled <true|false> и /xpmult reload.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
settings.gradle
Code
9 411
src/main/java/com/kodari/xpmultiplier/XpMultiplier.java
package com.kodari.xpmultiplier;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.permissions.Permissions;
import net.minecraft.world.entity.LivingEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

public final class XpMultiplier implements ModInitializer {
	public static final String MOD_ID = "xpmultiplier";
	private static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
	private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
	private static final Path CONFIG_PATH = Path.of("config", "xpmultiplier.json");
	private static final ThreadLocal<ArrayDeque<MobContext>> MOB_CONTEXT = ThreadLocal.withInitial(ArrayDeque::new);
	private static final Map<String, Double> PER_MOB = new HashMap<>();
	private static final Set<String> BLACKLIST = new HashSet<>();

	private static boolean enabled = true;
	private static double multiplier = 2.0;
	private static double otherMultiplier = 2.0;
	private static boolean requirePlayerKill = true;

	@Override
	public void onInitialize() {
		loadConfig();
		registerCommands();
	}

	public static void beginMobReward(LivingEntity entity, boolean playerCredited) {
		MOB_CONTEXT.get().push(new MobContext(entity, playerCredited));
	}

	public static void endMobReward() {
		ArrayDeque<MobContext> contexts = MOB_CONTEXT.get();
		if (!contexts.isEmpty()) {
			contexts.pop();
		}
		if (contexts.isEmpty()) {
			MOB_CONTEXT.remove();
		}
	}

	public static int scaleOrbValue(int value) {
		if (!enabled || value <= 0) {
			return value;
		}

		double rate = otherMultiplier;
		ArrayDeque<MobContext> contexts = MOB_CONTEXT.get();
		if (!contexts.isEmpty()) {
			MobContext context = contexts.peek();
			String entityId = BuiltInRegistries.ENTITY_TYPE.getKey(context.entity().getType()).toString();
			if (BLACKLIST.contains(entityId) || (requirePlayerKill && !context.playerCredited())) {
				return value;
			}
			rate = PER_MOB.getOrDefault(entityId, multiplier);
		}

		double scaled = value * rate;
		long whole = (long) Math.floor(scaled);
		if (ThreadLocalRandom.current().nextDouble() < scaled - whole) {
			whole++;
		}
		return (int) Math.min(Integer.MAX_VALUE, whole);
	}

	private static void registerCommands() {
		CommandRegistrationCallback.EVENT.register((dispatcher, buildContext, selection) -> dispatcher.register(
				Commands.literal("xpmult")
						.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_MODERATOR))
						.executes(context -> showStatus(context.getSource()))
						.then(Commands.literal("status").executes(context -> showStatus(context.getSource())))
						.then(Commands.literal("set")
								.then(Commands.argument("value", DoubleArgumentType.doubleArg(0.0, 64.0))
										.executes(context -> setMultiplier(context.getSource(), DoubleArgumentType.getDouble(context, "value")))))
						.then(Commands.literal("other")
								.then(Commands.argument("value", DoubleArgumentType.doubleArg(0.0, 64.0))
										.executes(context -> setOtherMultiplier(context.getSource(), DoubleArgumentType.getDouble(context, "value")))))
						.then(Commands.literal("enabled")
								.then(Commands.argument("value", BoolArgumentType.bool())
										.executes(context -> setEnabled(context.getSource(), BoolArgumentType.getBool(context, "value")))))
						.then(Commands.literal("reload").executes(context -> reloadConfig(context.getSource())))
		));
	}

	private static int showStatus(CommandSourceStack source) {
		source.sendSuccess(() -> Component.literal(
				"XP multiplier: " + (enabled ? "enabled" : "disabled")
						+ ", mobs=" + multiplier
						+ ", other=" + otherMultiplier
						+ ", config=" + CONFIG_PATH.toAbsolutePath()
		), false);
		return 1;
	}

	private static int setMultiplier(CommandSourceStack source, double value) {
		multiplier = value;
		return saveAndReply(source, "Mob XP multiplier set to " + value + ".");
	}

	private static int setOtherMultiplier(CommandSourceStack source, double value) {
		otherMultiplier = value;
		return saveAndReply(source, "Other XP multiplier set to " + value + ".");
	}

	private static int setEnabled(CommandSourceStack source, boolean value) {
		enabled = value;
		return saveAndReply(source, "XP multiplier " + (value ? "enabled" : "disabled") + ".");
	}

	private static int saveAndReply(CommandSourceStack source, String message) {
		if (saveConfig()) {
			source.sendSuccess(() -> Component.literal(message), true);
		} else {
			source.sendSuccess(() -> Component.literal(message + " Could not save the config file."), false);
		}
		return 1;
	}

	private static int reloadConfig(CommandSourceStack source) {
		boolean loaded = loadConfig();
		source.sendSuccess(() -> Component.literal(loaded
				? "XP multiplier config reloaded."
				: "Could not read the XP multiplier config; defaults are active."), false);
		return loaded ? 1 : 0;
	}

	private static boolean loadConfig() {
		resetDefaults();
		if (!Files.exists(CONFIG_PATH)) {
			return saveConfig();
		}

		try {
			JsonElement root = JsonParser.parseString(Files.readString(CONFIG_PATH));
			if (!root.isJsonObject()) {
				throw new IllegalArgumentException("The config root must be a JSON object.");
			}
			JsonObject json = root.getAsJsonObject();
			enabled = readBoolean(json, "enabled", enabled);
			multiplier = readMultiplier(json, "multiplier", multiplier);
			otherMultiplier = readMultiplier(json, "other_multiplier", otherMultiplier);
			requirePlayerKill = readBoolean(json, "require_player_kill", requirePlayerKill);

			JsonElement perMob = json.get("per_mob");
			if (perMob != null && perMob.isJsonObject()) {
				for (Map.Entry<String, JsonElement> entry : perMob.getAsJsonObject().entrySet()) {
					JsonElement value = entry.getValue();
					if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber()) {
						PER_MOB.put(entry.getKey(), clampMultiplier(value.getAsDouble()));
					}
				}
			}

			JsonElement blacklist = json.get("blacklist");
			if (blacklist != null && blacklist.isJsonArray()) {
				BLACKLIST.clear();
				for (JsonElement value : blacklist.getAsJsonArray()) {
					if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
						BLACKLIST.add(value.getAsString());
					}
				}
			}
			return true;
		} catch (IOException | RuntimeException exception) {
			resetDefaults();
			LOGGER.warn("Could not load XP multiplier config at {}", CONFIG_PATH, exception);
			return false;
		}
	}

	private static boolean saveConfig() {
		JsonObject json = new JsonObject();
		json.addProperty("enabled", enabled);
		json.addProperty("multiplier", multiplier);
		json.addProperty("other_multiplier", otherMultiplier);