Asisalsol&Adrielcuentagamer

Actúa como un desarrollador experto de mods para Fabric en Minecraft 1.21.11. Necesito que crees el código base y la estructura para un add-on llamado "Vex Civilization".

Este mod es una mejora para el mod existente "VexBot" (que añade bots al servidor). El mod debe estar desarrollado en Java usando la API de Fabric y debe compilar correctamente generando el archivo .jar.

La mecánica principal es el "Looteo de Cofres" con dos modos: Manual y Autónomo.

REQUISITOS DE LOS COMANDOS (Usando Brigadier):

  1. "/vexcivilization loot <nombre_del_bot>": Hace que un bot específico lootee el cofre más cercano en un radio de 4 bloques.
  2. "/vexcivilization lootarea": Hace que TODOS los bots en un radio de 30 bloques del jugador busquen y looteen cofres (ignorando al jugador humano).
  3. "/vexcivilization autoloot <true|false>": Un comando con argumento booleano (true/false). Activa o desactiva el modo AUTÓNOMO GLOBAL.

LÓGICA DE AUTONOMÍA (El modo Global):

  • Debes crear una variable estática global (ej. boolean isAutoLootEnabled = false).
  • Si el jugador usa "/vexcivilization autoloot true", la variable se vuelve true.
  • Si se usa "false", se desactiva.
  • IMPORTANTE: Si isAutoLootEnabled es TRUE, debes implementar un evento ServerTickEvents.END_SERVER_TICK. Cada 20 ticks (1 segundo), el mod debe revisar a TODOS los bots del servidor. Si un bot tiene un cofre a 4 bloques o menos, debe ejecutar la lógica de looteo automáticamente sin que el jugador haga nada.

LÓGICA DE LOOTEO (Para todos los modos):

  • Al lootear, buscar el bloque ChestBlockEntity.
  • Transferir TODOS los ítems del cofre al inventario del bot.
  • Cerrar la interfaz del cofre.
  • EVITAR ATASCOS: Después de lootear, el mod debe ejecutar internamente un comando de VexBot: "/vexbot goto <x> <y> <z>" (con coordenadas 2 bloques alejadas del cofre) para que el bot se mueva y no se quede pegado al cofre vacío.
  • Enviar un mensaje al chat: "Cofre saqueado. [X] ítems obtenidos".

ESTRUCTURA DEL PROYECTO:

  • Genera el archivo "fabric.mod.json" con el ID "vexcivilization", compatible con "1.21.11", dependiendo de "fabric-api" y "vexbot".
  • Genera la clase principal "VexCivilizationMain.java" en el paquete "com.vexcivilization".
  • Asegúrate de incluir todos los imports necesarios y estructurar bien el árbol de comandos con Brigadier.
Kodari AI
KodariOct 28 at 9:01 pm 4
VexCivilization
Fabric mod for Minecraft 1.21.11 that enhances VexBot with chest looting mechanics. Features Brigadier commands for manual bot looting, area looting for all nearby bots, and a global autonomous mode toggle. Implements ServerTickEvents for automatic looting every second when enabled, transferring all chest items to bot inventories, moving bots away to prevent stuck states, and notifying players of looted items.
  1. Crearé la configuración de Fabric 1.21.11 y los metadatos del mod.

  2. Añadiré comandos Brigadier y el ciclo de looteo manual/autónomo, compatibles sin enlazar a APIs internas desconocidas de VexBot.

Creé el proyecto Fabric 1.21.11 con configuración de Loom, metadatos del mod y la clase principal com.vexcivilization.VexCivilizationMain.

Incluye /vexcivilization loot <nombre_del_bot>, lootarea y autoloot <true|false>. El modo autónomo revisa a los bots cada 20 ticks, transfiere los objetos que caben en su inventario, cierra la interfaz y ejecuta vexbot goto para apartarlos del cofre.

Compatibilidad: como no se proporcionó una API de VexBot para identificar bots, el código los reconoce por el nombre de su clase Java (vexbot, bot o fakeplayer). Si VexBot usa la clase vanilla sin un marcador distintivo, habrá que conectar su API para detectarlos con fiabilidad. Si el inventario está lleno, los objetos restantes quedan en el cofre.

Para compilar y descargar el .jar: en escritorio, pulsa Compile en la barra superior; en móvil, ⋮ → Compile Project. Pulsa Compile en la ventana y, cuando termine, Download en el build.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 324
src/main/java/com/vexcivilization/VexCivilizationMain.java
package com.vexcivilization;

import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.ChestBlockEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;

import java.util.Locale;

import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal;
import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument;

public class VexCivilizationMain implements ModInitializer {
    public static boolean isAutoLootEnabled = false;

    private static int ticksSinceAutoLoot;

    @Override
    public void onInitialize() {
        CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
                com.mojang.brigadier.builder.LiteralArgumentBuilder.<ServerCommandSource>literal("vexcivilization")
                        .then(com.mojang.brigadier.builder.LiteralArgumentBuilder.<ServerCommandSource>literal("loot")
                                .then(com.mojang.brigadier.builder.RequiredArgumentBuilder.<ServerCommandSource, String>argument("nombre_del_bot", StringArgumentType.word())
                                        .executes(context -> {
                                            ServerCommandSource source = context.getSource();
                                            String botName = StringArgumentType.getString(context, "nombre_del_bot");
                                            ServerPlayerEntity bot = source.getServer().getPlayerManager().getPlayer(botName);
                                            if (bot == null || !isVexBot(bot)) {
                                                source.sendFeedback(() -> Text.literal("No se encontró el bot '" + botName + "'."), false);
                                                return 0;
                                            }

                                            LootResult result = lootNearby(bot, 4);
                                            if (!result.foundChest()) {
                                                source.sendFeedback(() -> Text.literal("No se encontró un cofre con objetos a 4 bloques de " + botName + "."), false);
                                                return 0;
                                            }

                                            source.sendFeedback(() -> Text.literal(lootMessage(result.itemCount())), false);
                                            return 1;
                                        })))
                        .then(com.mojang.brigadier.builder.LiteralArgumentBuilder.<ServerCommandSource>literal("lootarea")
                                .executes(context -> {
                                    ServerCommandSource source = context.getSource();
                                    ServerPlayerEntity executor = source.getPlayerOrThrow();
                                    int lootedBots = 0;

                                    for (ServerPlayerEntity bot : source.getServer().getPlayerManager().getPlayerList()) {
                                        if (!isVexBot(bot)
                                                || bot.getEntityWorld() != executor.getEntityWorld()
                                                || !executor.getBlockPos().isWithinDistance(bot.getBlockPos(), 30)) {
                                            continue;
                                        }

                                        LootResult result = lootNearby(bot, 4);
                                        if (result.foundChest()) {
                                            source.sendFeedback(() -> Text.literal(bot.getName().getString() + ": " + lootMessage(result.itemCount())), false);
                                            lootedBots++;
                                        }
                                    }

                                    if (lootedBots == 0) {
                                        source.sendFeedback(() -> Text.literal("No se encontraron bots con cofres cercanos."), false);
                                    }
                                    return lootedBots;
                                }))
                        .then(com.mojang.brigadier.builder.LiteralArgumentBuilder.<ServerCommandSource>literal("autoloot")
                                .then(com.mojang.brigadier.builder.RequiredArgumentBuilder.<ServerCommandSource, Boolean>argument("enabled", BoolArgumentType.bool())
                                        .executes(context -> {
                                            isAutoLootEnabled = BoolArgumentType.getBool(context, "enabled");
                                            ticksSinceAutoLoot = 0;
                                            context.getSource().sendFeedback(
                                                    () -> Text.literal("Autoloot global " + (isAutoLootEnabled ? "activado." : "desactivado.")),
                                                    false
                                            );
                                            return 1;
                                        })))
        ));

        ServerTickEvents.END_SERVER_TICK.register(VexCivilizationMain::onEndServerTick);
    }

    private static void onEndServerTick(MinecraftServer server) {
        if (!isAutoLootEnabled) {
            ticksSinceAutoLoot = 0;
            return;
        }

        if (++ticksSinceAutoLoot < 20) {
            return;
        }
        ticksSinceAutoLoot = 0;

        for (ServerPlayerEntity bot : server.getPlayerManager().getPlayerList()) {
            if (!isVexBot(bot)) {
                continue;
            }

            LootResult result = lootNearby(bot, 4);
            if (result.foundChest()) {
                bot.sendMessage(Text.literal(lootMessage(result.itemCount())), false);
            }
        }
    }

    private static LootResult lootNearby(ServerPlayerEntity bot, int radius) {
        NearbyChest nearbyChest = findNearestChest(bot, radius);
        if (nearbyChest == null) {
            return new LootResult(false, 0);
        }

        int itemCount = transferContents(bot, nearbyChest.chest());
        ServerWorld world = bot.getEntityWorld();
        BlockPos chestPos = nearbyChest.pos();

        for (int offsetX = -1; offsetX <= 1; offsetX++) {
            for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
                if (Math.abs(offsetX) + Math.abs(offsetZ) != 1) {
                    continue;
                }

                BlockEntity adjacent = world.getBlockEntity(new BlockPos(
                        chestPos.getX() + offsetX,
                        chestPos.getY(),
                        chestPos.getZ() + offsetZ
                ));
                if (adjacent instanceof ChestBlockEntity adjacentChest) {
                    itemCount += transferContents(bot, adjacentChest);
                }
            }
        }

        bot.closeHandledScreen();
        moveBotAwayFromChest(bot, chestPos);
        return new LootResult(true, itemCount);
    }

    private static NearbyChest findNearestChest(ServerPlayerEntity bot, int radius) {
        ServerWorld world = bot.getEntityWorld();
        BlockPos origin = bot.getBlockPos();
        ChestBlockEntity nearest = null;
        BlockPos nearestPos = null;
        double nearestDistance = (double) radius * radius;

        for (BlockPos pos : BlockPos.iterate(
                origin.getX() - radius, origin.getY() - radius, origin.getZ() - radius,
                origin.getX() + radius, origin.getY() + radius, origin.getZ() + radius
        )) {
            double distance = origin.getSquaredDistance(pos);
            if (distance > nearestDistance) {
                continue;
            }

            BlockEntity blockEntity = world.getBlockEntity(pos);
            if (!(blockEntity instanceof ChestBlockEntity chest) || !hasContents(chest)) {
                continue;
            }

            nearest = chest;
            nearestPos = new BlockPos(pos.getX(), pos.getY(), pos.getZ());
            nearestDistance = distance;
        }

        return nearest == null ? null : new NearbyChest(nearest, nearestPos);
    }

    private static boolean hasContents(Inventory inventory) {
        for (int slot = 0; slot < inventory.size(); slot++) {
            if (!inventory.getStack(slot).isEmpty()) {
                return true;
            }
        }
        return false;
    }

    private static int transferContents(ServerPlayerEntity bot, Inventory chest) {
        PlayerInventory botInventory = bot.getInventory();
        int itemCount = 0;

        for (int slot = 0; slot < chest.size(); slot++) {
            ItemStack stack = chest.getStack(slot);
            if (stack.isEmpty()) {
                continue;
            }

            ItemStack remaining = stack.copy();
            int before = remaining.getCount();
            botInventory.insertStack(remaining);