No chat to show

This project's files are all here to explore.

Files
src
build.gradle
gradle.properties
settings.gradle
Code
6 282
src/client/java/com/kodari/automace/client/AutoMaceClient.java
package com.kodari.automace.client;

import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.command.v2.ClientCommands;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.monster.Enemy;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.component.SwingAnimation;
import net.minecraft.world.level.Level;
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.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;

public class AutoMaceClient implements ClientModInitializer {
	private static final Logger LOGGER = LoggerFactory.getLogger("automace");
	private static final double TARGET_SCAN_RANGE = 8.0;
	private static final double ATTACK_RANGE = 3.0;
	private static final Set<String> WHITELIST = new TreeSet<>();
	private static boolean enabled;
	private static boolean attackedDuringFall;

	@Override
	public void onInitializeClient() {
		loadWhitelist();
		ClientTickEvents.END_CLIENT_TICK.register(AutoMaceClient::onClientTick);
		ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(
			ClientCommands.literal("automace")
				.then(ClientCommands.literal("on").executes(context -> {
					enabled = true;
					context.getSource().sendFeedback(Component.translatable("automace.enabled"));
					return 1;
				}))
				.then(ClientCommands.literal("off").executes(context -> {
					enabled = false;
					context.getSource().sendFeedback(Component.translatable("automace.disabled"));
					return 1;
				}))
				.then(ClientCommands.literal("toggle").executes(context -> {
					enabled = !enabled;
					context.getSource().sendFeedback(Component.translatable(enabled ? "automace.enabled" : "automace.disabled"));
					return 1;
				}))
				.then(ClientCommands.literal("whitelist")
					.then(ClientCommands.literal("add")
						.then(ClientCommands.argument("player", StringArgumentType.word()).executes(context -> {
							String name = StringArgumentType.getString(context, "player");
							boolean added = WHITELIST.add(normalize(name));
							saveWhitelist();
							context.getSource().sendFeedback(Component.translatable(
								added ? "automace.whitelist.added" : "automace.whitelist.already_added", name));
							return 1;
						})))
					.then(ClientCommands.literal("remove")
						.then(ClientCommands.argument("player", StringArgumentType.word()).executes(context -> {
							String name = StringArgumentType.getString(context, "player");
							boolean removed = WHITELIST.remove(normalize(name));
							if (removed) {
								saveWhitelist();
							}
							context.getSource().sendFeedback(Component.translatable(
								removed ? "automace.whitelist.removed" : "automace.whitelist.not_found", name));
							return 1;
						})))
					.then(ClientCommands.literal("list").executes(context -> {
						Component message = WHITELIST.isEmpty()
							? Component.translatable("automace.whitelist.empty")
							: Component.translatable("automace.whitelist.list", String.join(", ", WHITELIST));
						context.getSource().sendFeedback(message);
						return 1;
					}))
				)
		));
	}

	private static void onClientTick(Minecraft client) {
		if (!enabled || client.player == null || client.level == null || client.gameMode == null) {
			return;
		}

		Player player = client.player;
		boolean falling = player.fallDistance >= 1.5F && player.getDeltaMovement().y < 0.0;
		if (!falling) {
			attackedDuringFall = false;
		}
		if (!falling || player.getMainHandItem().getItem() != Items.MACE || attackedDuringFall) {
			return;
		}

		int maceSlot = findMaceSlot(player);
		if (maceSlot < 0) {
			return;
		}

		Entity target = findTarget(client.level, player);
		if (target == null) {
			return;
		}

		float distance = player.distanceTo(target);

		if (distance <= ATTACK_RANGE) {
			client.gameMode.attack(player, target);
			player.swing(InteractionHand.MAIN_HAND, SwingAnimation.DEFAULT, false);
			attackedDuringFall = true;
		}
	}

	private static int findMaceSlot(Player player) {
		for (int slot = 0; slot < 9; slot++) {
			if (player.getInventory().getItem(slot).getItem() == Items.MACE) {
				return slot;
			}
		}
		return -1;
	}

	private static Entity findTarget(Level level, Player player) {
		List<Entity> candidates = level.getEntities(player, player.getBoundingBox().inflate(TARGET_SCAN_RANGE), entity -> {
			if (entity instanceof Player otherPlayer) {
				return !WHITELIST.contains(normalize(otherPlayer.getPlainTextName()));
			}
			return entity instanceof Enemy;
		});

		Entity nearest = null;
		double nearestDistance = TARGET_SCAN_RANGE * TARGET_SCAN_RANGE;
		for (Entity candidate : candidates) {
			if (!candidate.isAlive()) {
				continue;
			}
			double distance = player.distanceToSqr(candidate);
			if (distance < nearestDistance) {
				nearest = candidate;
				nearestDistance = distance;
			}
		}
		return nearest;
	}

	private static String normalize(String name) {
		return name.toLowerCase(Locale.ROOT);
	}

	private static Path whitelistPath() {
		return Minecraft.getInstance().gameDirectory.toPath().resolve("config").resolve("automace-whitelist.txt");
	}

	private static void loadWhitelist() {
		Path path = whitelistPath();
		if (!Files.exists(path)) {
			return;
		}
		try {
			for (String name : Files.readAllLines(path)) {
				if (!name.isBlank()) {
					WHITELIST.add(normalize(name.trim()));
				}
			}
		} catch (IOException exception) {
			LOGGER.error("Could not load the Auto Mace whitelist", exception);
		}
	}

	private static void saveWhitelist() {
		Path path = whitelistPath();
		try {
			Files.createDirectories(path.getParent());
			Files.write(path, WHITELIST);
		} catch (IOException exception) {
			LOGGER.error("Could not save the Auto Mace whitelist", exception);
		}
	}
}