AutoArmor module

AutoArmor: Minecraft 26.3 cheat module, full source for every implementation (5 clients: MelaHack (ThunderHack fork), OfflineClient, Combatant, …).

5 implementationsPLAYERCOMBATCombat

Full module source: 5 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

MelaHack (ThunderHack fork)PLAYERsrc/main/java/thunder/hack/features/modules/player/AutoArmor.javaJava · 244 lines · 9.7 KB

Automatically puts on the best armor.

SettingsHeadBodyTightsFeetElytraPriorityDelayOldVersionPauseInventoryNoMoveIgnoreCurseStrict
AutoArmor.javaJava · Minecraft 26.2 · 244 lines · 9.7 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.player;
2
3
import thunder.hack.core.manager.client.ModuleManager;
4
import thunder.hack.gui.clickui.ClickGUI;
5
import thunder.hack.gui.hud.HudEditorGui;
6
import thunder.hack.features.modules.Module;
7
import thunder.hack.setting.Setting;
8
import thunder.hack.utility.player.InventoryUtility;
9
import thunder.hack.utility.player.MovementUtility;
10
11
import java.util.Arrays;
12
import java.util.List;
13
import net.minecraft.client.gui.screens.ChatScreen;
14
import net.minecraft.core.registries.Registries;
15
import net.minecraft.network.protocol.game.ServerboundContainerClosePacket;
16
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
17
import net.minecraft.network.protocol.game.ServerboundUseItemPacket;
18
import net.minecraft.world.InteractionHand;
19
import net.minecraft.world.entity.EquipmentSlot;
20
import net.minecraft.world.entity.LivingEntity;
21
import net.minecraft.world.entity.ai.attributes.Attributes;
22
import net.minecraft.world.item.ItemStack;
23
import net.minecraft.world.item.Items;
24
import net.minecraft.world.item.enchantment.EnchantmentHelper;
25
import net.minecraft.world.item.enchantment.Enchantments;
26
import net.minecraft.world.item.enchantment.ItemEnchantments;
27
28
public class AutoArmor extends Module {
29
    public AutoArmor() {
30
        super("AutoArmor", Category.PLAYER);
31
    }
32
33
    private final Setting<EnchantPriority> head = new Setting<>("Head", EnchantPriority.Protection);
34
    private final Setting<EnchantPriority> body = new Setting<>("Body", EnchantPriority.Protection);
35
    private final Setting<EnchantPriority> tights = new Setting<>("Tights", EnchantPriority.Protection);
36
    private final Setting<EnchantPriority> feet = new Setting<>("Feet", EnchantPriority.Protection);
37
    private final Setting<ElytraPriority> elytraPriority = new Setting<>("ElytraPriority", ElytraPriority.Ignore);
38
    private final Setting<Integer> delay = new Setting<>("Delay", 5, 0, 10);
39
    private final Setting<Boolean> oldVersion = new Setting<>("OldVersion", false);
40
    private final Setting<Boolean> pauseInventory = new Setting<>("PauseInventory", false);
41
    private final Setting<Boolean> noMove = new Setting<>("NoMove", false);
42
    private final Setting<Boolean> ignoreCurse = new Setting<>("IgnoreCurse", true);
43
    private final Setting<Boolean> strict = new Setting<>("Strict", false);
44
45
    private int tickDelay = 0;
46
47
    List<ArmorData> armorList = Arrays.asList(
48
            new ArmorData(EquipmentSlot.FEET, 36, -1, -1, -1),
49
            new ArmorData(EquipmentSlot.LEGS, 37, -1, -1, -1),
50
            new ArmorData(EquipmentSlot.CHEST, 38, -1, -1, -1),
51
            new ArmorData(EquipmentSlot.HEAD, 39, -1, -1, -1)
52
    );
53
54
    @Override
55
    public void onUpdate() {
56
        if (mc.gui.screen() != null && pauseInventory.getValue() && !(mc.gui.screen() instanceof ChatScreen) && !(mc.gui.screen() instanceof ClickGUI) && !(mc.gui.screen() instanceof HudEditorGui))
57
            return;
58
59
        if (tickDelay-- > 0)
60
            return;
61
62
        armorList.forEach(ArmorData::reset);
63
64
        for (int i = 0; i < 36; i++) {
65
            ItemStack stack = mc.player.getInventory().getItem(i);
66
            int prot = getProtection(stack);
67
            if (prot > 0)
68
                for (ArmorData e : armorList) {
69
                    if (e.getEquipmentSlot() == mc.player.getEquipmentSlotForItem(stack))
70
                        if (prot > e.getPrevProt() && prot > e.getNewProtection()) {
71
                            e.setNewSlot(i);
72
                            e.setNewProtection(prot);
73
                        }
74
                }
75
        }
76
77
        for (ArmorData armorPiece : armorList) {
78
            int slot = armorPiece.getNewSlot();
79
            if (slot != -1) {
80
                if ((armorPiece.getPrevProt() == -1 || !oldVersion.getValue()) && slot < 9) {
81
                    InventoryUtility.saveAndSwitchTo(slot);
82
                    sendSequencedPacket(id -> new ServerboundUseItemPacket(InteractionHand.MAIN_HAND, id, mc.player.getYRot(), mc.player.getXRot()));
83
                    InventoryUtility.returnSlot();
84
                } else {
85
                    if (MovementUtility.isMoving() && noMove.getValue())
86
                        return;
87
88
                    int newArmorSlot = slot < 9 ? 36 + slot : slot;
89
90
                    if(strict.getValue())
91
                        sendPacket(new ServerboundPlayerCommandPacket(mc.player, ServerboundPlayerCommandPacket.Action.STOP_SPRINTING));
92
93
                    clickSlot(newArmorSlot);
94
                    clickSlot((armorPiece.getArmorSlot() - 34) + (39 - armorPiece.getArmorSlot()) * 2);
95
                    if (armorPiece.getPrevProt() != -1)
96
                        clickSlot(newArmorSlot);
97
98
                    sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
99
                }
100
101
                tickDelay = delay.getValue();
102
                return;
103
            }
104
        }
105
    }
106
107
    private int getProtection(ItemStack is) {
108
        if (mc.player.getEquipmentSlotForItem(is).isArmor() || is.is(Items.ELYTRA)) {
109
            int prot = 0;
110
111
            EquipmentSlot slot = mc.player.getEquipmentSlotForItem(is);
112
113
            if (is.is(Items.ELYTRA)) {
114
                if (!isUsableElytra(is))
115
                    return 0;
116
117
                boolean ePlus = elytraPriority.is(ElytraPriority.ElytraPlus) && (ModuleManager.elytraRecast.isEnabled() || ModuleManager.elytraPlus.isEnabled());
118
                boolean ignore = elytraPriority.is(ElytraPriority.Ignore) && mc.player.getInventory().getItem(38).is(Items.ELYTRA);
119
120
                if (ePlus || ignore || elytraPriority.is(ElytraPriority.Always))
121
                    prot = 999;
122
            }
123
124
            int blastMultiplier = 1;
125
            int protectionMultiplier = 1;
126
127
            switch (slot) {
128
                case HEAD -> {
129
                    if(head.is(EnchantPriority.Protection)) protectionMultiplier *= 2;
130
                    else blastMultiplier *= 2;
131
                }
132
                case BODY -> {
133
                    if(body.is(EnchantPriority.Protection)) protectionMultiplier *= 2;
134
                    else blastMultiplier *= 2;
135
                }
136
                case LEGS -> {
137
                    if(tights.is(EnchantPriority.Protection)) protectionMultiplier *= 2;
138
                    else blastMultiplier *= 2;
139
                }
140
                case FEET -> {
141
                    if(feet.is(EnchantPriority.Protection)) protectionMultiplier *= 2;
142
                    else blastMultiplier *= 2;
143
                }
144
            }
145
146
            if (is.isEnchanted()) {
147
                ItemEnchantments enchants = EnchantmentHelper.getEnchantmentsForCrafting(is);
148
149
                var enchantments = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
150
                var protection = enchantments.getOrThrow(Enchantments.PROTECTION);
151
                var blastProtection = enchantments.getOrThrow(Enchantments.BLAST_PROTECTION);
152
                var bindingCurse = enchantments.getOrThrow(Enchantments.BINDING_CURSE);
153
154
                if (enchants.keySet().contains(protection))
155
                    prot += enchants.getLevel(protection) * protectionMultiplier;
156
157
                if (enchants.keySet().contains(blastProtection))
158
                    prot += enchants.getLevel(blastProtection) * blastMultiplier;
159
160
                if (enchants.keySet().contains(bindingCurse) && ignoreCurse.getValue())
161
                    prot = -999;
162
            }
163
164
            if (slot.isArmor()) {
165
                final double[] armorValues = new double[2];
166
                is.forEachModifier(slot, (attribute, modifier) -> {
167
                    if (attribute.is(Attributes.ARMOR)) {
168
                        armorValues[0] += modifier.amount();
169
                    } else if (attribute.is(Attributes.ARMOR_TOUGHNESS)) {
170
                        armorValues[1] += modifier.amount();
171
                    }
172
                });
173
                int base = (int) Math.ceil(armorValues[0] + armorValues[1]);
174
                return base * 10 + prot;
175
            }
176
            return prot;
177
        } else if (!is.isEmpty()) return 0;
178
        return -1;
179
    }
180
181
    private boolean isUsableElytra(ItemStack stack) {
182
        return LivingEntity.canGlideUsing(stack, EquipmentSlot.CHEST);
183
    }
184
185
    public class ArmorData {
186
        private EquipmentSlot equipmentSlot;
187
        private int armorSlot, prevProtection, newSlot, newProtection;
188
189
        public ArmorData(EquipmentSlot equipmentSlot, int armorSlot, int prevProtection, int newSlot, int newProtection) {
190
            this.equipmentSlot = equipmentSlot;
191
            this.armorSlot = armorSlot;
192
            this.prevProtection = prevProtection;
193
            this.newSlot = newSlot;
194
            this.newProtection = newProtection;
195
        }
196
197
        public int getArmorSlot() {
198
            return armorSlot;
199
        }
200
201
        public int getPrevProt() {
202
            return prevProtection;
203
        }
204
205
        public void setPrevProt(int prevProtection) {
206
            this.prevProtection = prevProtection;
207
        }
208
209
        public int getNewSlot() {
210
            return newSlot;
211
        }
212
213
        public void setNewSlot(int newSlot) {
214
            this.newSlot = newSlot;
215
        }
216
217
        public int getNewProtection() {
218
            return newProtection;
219
        }
220
221
        public void setNewProtection(int newProtection) {
222
            this.newProtection = newProtection;
223
        }
224
225
        public EquipmentSlot getEquipmentSlot() {
226
            return equipmentSlot;
227
        }
228
229
        public void reset() {
230
            setPrevProt(getProtection(mc.player.getInventory().getItem(getArmorSlot())));
231
            setNewSlot(-1);
232
            setNewProtection(-1);
233
        }
234
    }
235
236
    private enum ElytraPriority {
237
        None, Always, ElytraPlus, Ignore
238
    }
239
240
    private enum EnchantPriority {
241
        Blast, Protection
242
    }
243
}
244
OfflineClientCOMBATsrc/main/java/com/jellypudding/offlineclient/modules/combat/AutoArmor.javaJava · 197 lines · 8.6 KB

Automatically wears the best armour you have.

SettingsDelayPreferBlast leggingsAvoided enchantmentsKeep elytraWhile movingAnti breakDurability
AutoArmor.javaJava · Minecraft 26.2 · 197 lines · 8.6 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.combat;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.TickEvent;
5
import com.jellypudding.offlineclient.module.Category;
6
import com.jellypudding.offlineclient.module.Module;
7
import com.jellypudding.offlineclient.setting.BoolSetting;
8
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
9
import com.jellypudding.offlineclient.setting.EnumSetting;
10
import com.jellypudding.offlineclient.setting.NumberSetting;
11
import com.jellypudding.offlineclient.util.InventoryUtil;
12
import com.jellypudding.offlineclient.util.InventoryUtil.Swap;
13
import com.jellypudding.offlineclient.util.ItemUtil;
14
import com.jellypudding.offlineclient.util.MovementUtil;
15
import it.unimi.dsi.fastutil.objects.Object2IntMap;
16
import net.minecraft.core.Holder;
17
import net.minecraft.resources.ResourceKey;
18
import net.minecraft.world.entity.EquipmentSlot;
19
import net.minecraft.world.entity.ai.attributes.Attributes;
20
import net.minecraft.world.item.ItemStack;
21
import net.minecraft.world.item.Items;
22
import net.minecraft.world.item.enchantment.Enchantment;
23
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
24
import net.minecraft.world.item.enchantment.EnchantmentHelper;
25
import net.minecraft.world.item.enchantment.Enchantments;
26
27
import java.util.List;
28
29
public final class AutoArmor extends Module {
30
31
    public enum Protection {
32
        PROTECTION(Enchantments.PROTECTION),
33
        BLAST_PROTECTION(Enchantments.BLAST_PROTECTION),
34
        FIRE_PROTECTION(Enchantments.FIRE_PROTECTION),
35
        PROJECTILE_PROTECTION(Enchantments.PROJECTILE_PROTECTION);
36
37
        private final ResourceKey<Enchantment> enchantment;
38
39
        Protection(ResourceKey<Enchantment> enchantment) {
40
            this.enchantment = enchantment;
41
        }
42
    }
43
44
    private final NumberSetting delay = new NumberSetting("Delay",
45
        "Ticks between each swap.", 2, 0, 20, 1, " ticks");
46
    private final EnumSetting<Protection> prefer = new EnumSetting<>("Prefer",
47
        "The protection enchantment that counts for the most.", Protection.PROTECTION)
48
        .describe(Protection.PROTECTION, "Plain Protection against everything.")
49
        .describe(Protection.BLAST_PROTECTION, "Blast Protection against crystals and beds.")
50
        .describe(Protection.FIRE_PROTECTION, "Fire Protection against lava and fire.")
51
        .describe(Protection.PROJECTILE_PROTECTION, "Projectile Protection against arrows.");
52
    private final BoolSetting blastLeggings = new BoolSetting("Blast leggings",
53
        "Leggings always prefer Blast Protection whatever is picked above.", true);
54
    private final ChoiceListSetting avoided = new ChoiceListSetting("Avoided enchantments",
55
        "Never put on a piece carrying any of these and take one off when something else fits.",
56
        ItemUtil::enchantmentIds, List.of("minecraft:binding_curse", "minecraft:frost_walker"));
57
    private final BoolSetting keepElytra = new BoolSetting("Keep elytra",
58
        "Leave a worn elytra alone rather than swapping a chestplate over it.", true);
59
    private final BoolSetting whileMoving = new BoolSetting("While moving",
60
        "Keep swapping whilst you walk. Off waits until you stand still.", true);
61
    private final BoolSetting antiBreak = new BoolSetting("Anti break",
62
        "Takes a worn piece off before it shatters and never puts one on.", true);
63
    private final NumberSetting durability = new NumberSetting("Durability",
64
        "Uses left at which a piece counts as worn out.", 10, 1, 100, 1, " uses")
65
        .under(antiBreak);
66
67
    private int timer;
68
69
    public AutoArmor() {
70
        super("AutoArmor", "Automatically wears the best armour you have.", Category.COMBAT);
71
        addSettings(delay, prefer, blastLeggings, avoided, keepElytra, whileMoving, antiBreak, durability);
72
        searchTags("armour", "auto equip");
73
    }
74
75
    @Subscribe
76
    private void onTick(TickEvent event) {
77
        if (!inGame() || mc.player.isSpectator()) {
78
            return;
79
        }
80
        // Clicks are thrown away unless the survival inventory is the open one.
81
        if (!InventoryUtil.canClick()) {
82
            return;
83
        }
84
        if (!whileMoving.isOn() && MovementUtil.inputDirection().lengthSqr() > 0) {
85
            return;
86
        }
87
        if (!InventoryUtil.carried().isEmpty()) {
88
            return;
89
        }
90
        if (timer > 0) {
91
            timer--;
92
            return;
93
        }
94
95
        for (int slotIndex = 0; slotIndex < ItemUtil.ARMOR_SLOTS.size(); slotIndex++) {
96
            EquipmentSlot slot = ItemUtil.ARMOR_SLOTS.get(slotIndex);
97
            ItemStack worn = mc.player.getItemBySlot(slot);
98
            if (slot == EquipmentSlot.CHEST && worn.is(Items.ELYTRA) && keepElytra.isOn()) {
99
                continue;
100
            }
101
            // A cursed piece never comes off. Clicking at it every tick gets nowhere.
102
            if (EnchantmentHelper.has(worn, EnchantmentEffectComponents.PREVENT_ARMOR_CHANGE)) {
103
                continue;
104
            }
105
106
            int armorNetworkSlot = InventoryUtil.ARMOR_START + slotIndex;
107
            int upgrade = bestUpgrade(worn, slot);
108
            if (upgrade == -1) {
109
                // Nothing better to wear. A shattering piece still comes off.
110
                if (wornOut(worn) && stow(armorNetworkSlot)) {
111
                    return;
112
                }
113
                continue;
114
            }
115
116
            if (InventoryUtil.swap(InventoryUtil.networkSlot(upgrade), armorNetworkSlot) != Swap.REFUSED) {
117
                timer = delay.getInt();
118
            }
119
            return;
120
        }
121
    }
122
123
    // Moves a worn out piece into the first free inventory slot.
124
    private boolean stow(int armorNetworkSlot) {
125
        int free = InventoryUtil.findSlot(ItemStack::isEmpty, InventoryUtil.WHOLE_INVENTORY);
126
        if (free == -1) {
127
            return false;
128
        }
129
        if (InventoryUtil.swap(armorNetworkSlot, InventoryUtil.networkSlot(free)) == Swap.REFUSED) {
130
            return false;
131
        }
132
        timer = delay.getInt();
133
        return true;
134
    }
135
136
    private boolean wornOut(ItemStack stack) {
137
        return antiBreak.isOn() && ItemUtil.nearlyBroken(stack, durability.getInt());
138
    }
139
140
    // The inventory slot of the piece that beats the worn one or minus one.
141
    // An elytra or a worn out piece scores nothing. Anything real replaces it.
142
    private int bestUpgrade(ItemStack worn, EquipmentSlot slot) {
143
        int best = -1;
144
        double bestScore = worn.is(Items.ELYTRA) || wornOut(worn) ? -1 : score(worn, slot);
145
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
146
            ItemStack stack = mc.player.getInventory().getItem(i);
147
            if (stack.isEmpty() || stack.is(Items.ELYTRA) || ItemUtil.equipSlot(stack) != slot
148
                || wornOut(stack) || carriesAvoided(stack)) {
149
                continue;
150
            }
151
            double stackScore = score(stack, slot);
152
            if (stackScore > bestScore) {
153
                bestScore = stackScore;
154
                best = i;
155
            }
156
        }
157
        return best;
158
    }
159
160
    // Armour points count double and the chosen protection triple. Every other
161
    // protection and Unbreaking count once and Mending twice. Avoided ones count against.
162
    private double score(ItemStack stack, EquipmentSlot slot) {
163
        double score = 2 * ItemUtil.attributeValue(stack, Attributes.ARMOR, slot)
164
            + ItemUtil.attributeValue(stack, Attributes.ARMOR_TOUGHNESS, slot);
165
        ResourceKey<Enchantment> preferred = slot == EquipmentSlot.LEGS && blastLeggings.isOn()
166
            ? Enchantments.BLAST_PROTECTION : prefer.getValue().enchantment;
167
        score += 3 * ItemUtil.enchantLevel(preferred, stack);
168
        for (Protection kind : Protection.values()) {
169
            score += ItemUtil.enchantLevel(kind.enchantment, stack);
170
        }
171
        score += ItemUtil.enchantLevel(Enchantments.UNBREAKING, stack);
172
        score += 2 * ItemUtil.enchantLevel(Enchantments.MENDING, stack);
173
        for (Object2IntMap.Entry<Holder<Enchantment>> entry
174
            : EnchantmentHelper.getEnchantmentsForCrafting(stack).entrySet()) {
175
            if (isAvoided(entry.getKey())) {
176
                score -= 2 * entry.getIntValue();
177
            }
178
        }
179
        return score;
180
    }
181
182
    private boolean carriesAvoided(ItemStack stack) {
183
        for (Holder<Enchantment> enchantment : EnchantmentHelper.getEnchantmentsForCrafting(stack).keySet()) {
184
            if (isAvoided(enchantment)) {
185
                return true;
186
            }
187
        }
188
        return false;
189
    }
190
191
    private boolean isAvoided(Holder<Enchantment> enchantment) {
192
        return enchantment.unwrapKey()
193
            .map(key -> avoided.contains(key.identifier().toString()))
194
            .orElse(false);
195
    }
196
}
197
CombatantPLAYERsrc/main/java/combatant/client/features/module/modules/player/AutoArmor.javaJava · 222 lines · 8.7 KB
SettingsautoArmorModearmor_items
AutoArmor.javaJava · Minecraft 26.2 · 222 lines · 8.7 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.player;
9
10
import combatant.client.util.screen.ClientScreen;
11
import net.minecraft.client.Minecraft;
12
import net.minecraft.client.gui.screens.inventory.InventoryScreen;
13
import net.minecraft.core.Holder;
14
import net.minecraft.core.Registry;
15
import net.minecraft.core.component.DataComponents;
16
import net.minecraft.core.registries.BuiltInRegistries;
17
import net.minecraft.core.registries.Registries;
18
import net.minecraft.resources.Identifier;
19
import net.minecraft.resources.ResourceKey;
20
import net.minecraft.world.entity.EquipmentSlot;
21
import net.minecraft.world.entity.ai.attributes.Attributes;
22
import net.minecraft.world.inventory.ContainerInput;
23
import net.minecraft.world.item.ItemStack;
24
import net.minecraft.world.item.Items;
25
import net.minecraft.world.item.enchantment.Enchantment;
26
import net.minecraft.world.item.enchantment.EnchantmentHelper;
27
import net.minecraft.world.item.enchantment.Enchantments;
28
import net.minecraft.world.item.equipment.Equippable;
29
import combatant.client.config.values.EnumValue;
30
import combatant.client.config.values.ItemIdSetValue;
31
import combatant.client.features.gui.clickgui.settings.TextListSetting;
32
import combatant.client.features.module.Module;
33
import combatant.client.features.module.ModuleCategory;
34
import combatant.client.features.module.ModuleInfo;
35
import combatant.client.util.player.inventory.InventorySwap;
36
37
import java.util.Set;
38
39
//todo Description
40
@ModuleInfo(
41
        id = "autoarmor",
42
        displayName = "AutoArmor",
43
        category = ModuleCategory.PLAYER
44
)
45
public class AutoArmor extends Module {
46
47
    private static final String SETTING_MODE = "mode";
48
    private static final String SETTING_ARMOR_ITEMS = "armor_items";
49
    private final EnumValue<Mode> mode =
50
            enumSetting("autoArmorMode", SETTING_MODE, Mode.AUTO, Mode.values());
51
    private final ItemIdSetValue armorItems =
52
            visibleWhen(itemList("armor_items", SETTING_ARMOR_ITEMS, TextListSetting.PickerMode.EQUIPPABLE_ARMOR),
53
                    () -> mode.get() == Mode.WHITELIST);
54
    private final Minecraft mc = Minecraft.getInstance();
55
56
    @Override
57
    public void onTick() {
58
        if (!isEnabled() || mc.player == null || mc.gameMode == null || mc.level == null) return;
59
        if (ClientScreen.current() != null && !(ClientScreen.current() instanceof InventoryScreen))
60
            return;
61
        if (mc.player.inventoryMenu == null) return;
62
63
        int syncId = mc.player.inventoryMenu.containerId;
64
        for (EquipmentSlot slot : EquipmentSlot.values()) {
65
            if (slot.getType() != EquipmentSlot.Type.HUMANOID_ARMOR) continue;
66
67
            ItemStack equipped = mc.player.getItemBySlot(slot);
68
            if (slot == EquipmentSlot.CHEST && equipped.is(Items.ELYTRA)) continue;
69
70
            Candidate best = findBestCandidate(slot);
71
            if (best != null && isBetter(best.stack, equipped, slot)) {
72
                int from = InventorySwap.mapInventoryToScreenSlot(best.invSlot);
73
                int to = armorScreenSlot(slot);
74
                InventorySwap.INSTANCE.swapScreenSlots(from, to);
75
                return;
76
            }
77
78
            if (isBroken(equipped)) {
79
                if (best != null) {
80
                    int from = InventorySwap.mapInventoryToScreenSlot(best.invSlot);
81
                    int to = armorScreenSlot(slot);
82
                    InventorySwap.INSTANCE.swapScreenSlots(from, to);
83
                    return;
84
                }
85
                int armorSlot = armorScreenSlot(slot);
86
                if (hasInventorySpace()) {
87
                    mc.gameMode.handleContainerInput(syncId, armorSlot, 0, ContainerInput.QUICK_MOVE, mc.player);
88
                    return;
89
                }
90
            }
91
        }
92
    }
93
94
    private Candidate findBestCandidate(EquipmentSlot slot) {
95
        if (mc.player == null) return null;
96
        Set<String> whitelist = armorItems.get();
97
        int bestSlot = -1;
98
        double bestScore = Double.NEGATIVE_INFINITY;
99
100
        for (int i = 0; i < 36; i++) {
101
            ItemStack stack = mc.player.getInventory().getItem(i);
102
            if (stack == null || stack.isEmpty()) continue;
103
            if (!isEquippableForSlot(stack, slot)) continue;
104
            if (isBroken(stack)) continue;
105
            if (hasCurseOfBinding(stack)) continue;
106
            if (mode.get() == Mode.WHITELIST && !isWhitelisted(stack, whitelist)) continue;
107
108
            double score = scoreArmor(stack, slot);
109
            if (score > bestScore) {
110
                bestScore = score;
111
                bestSlot = i;
112
            }
113
        }
114
115
        return bestSlot >= 0 ? new Candidate(bestSlot, mc.player.getInventory().getItem(bestSlot).copy()) : null;
116
    }
117
118
    private boolean isWhitelisted(ItemStack stack, Set<String> ids) {
119
        if (ids == null || ids.isEmpty()) return false;
120
        Identifier id = BuiltInRegistries.ITEM.getKey(stack.getItem());
121
        return id != null && ids.contains(id.toString());
122
    }
123
124
    private boolean isEquippableForSlot(ItemStack stack, EquipmentSlot slot) {
125
        Equippable eq = stack.get(DataComponents.EQUIPPABLE);
126
        return eq != null && eq.slot() == slot;
127
    }
128
129
    private boolean isBetter(ItemStack candidate, ItemStack current, EquipmentSlot slot) {
130
        if (candidate == null || candidate.isEmpty()) return false;
131
        if (current == null || current.isEmpty()) return true;
132
        if (hasCurseOfBinding(current)) return false;
133
        return scoreArmor(candidate, slot) > scoreArmor(current, slot);
134
    }
135
136
    private double scoreArmor(ItemStack stack, EquipmentSlot slot) {
137
        if (stack == null || stack.isEmpty()) return Double.NEGATIVE_INFINITY;
138
139
        double[] armor = new double[]{0.0};
140
        double[] toughness = new double[]{0.0};
141
        double[] kbResist = new double[]{0.0};
142
        stack.forEachModifier(slot, (attribute, modifier) -> {
143
            if (attribute.is(Attributes.ARMOR)) {
144
                armor[0] += modifier.amount();
145
            } else if (attribute.is(Attributes.ARMOR_TOUGHNESS)) {
146
                toughness[0] += modifier.amount();
147
            } else if (attribute.is(Attributes.KNOCKBACK_RESISTANCE)) {
148
                kbResist[0] += modifier.amount();
149
            }
150
        });
151
152
        int protection = getEnchantmentLevel(Enchantments.PROTECTION, stack);
153
        int blast = getEnchantmentLevel(Enchantments.BLAST_PROTECTION, stack);
154
        int projectile = getEnchantmentLevel(Enchantments.PROJECTILE_PROTECTION, stack);
155
        int fire = getEnchantmentLevel(Enchantments.FIRE_PROTECTION, stack);
156
        int unbreaking = getEnchantmentLevel(Enchantments.UNBREAKING, stack);
157
        int mending = getEnchantmentLevel(Enchantments.MENDING, stack);
158
159
        return armor[0] * 10.0
160
                + toughness[0] * 4.0
161
                + kbResist[0] * 2.0
162
                + protection * 1.4
163
                + blast * 0.6
164
                + projectile * 0.4
165
                + fire * 0.3
166
                + unbreaking * 0.1
167
                + mending * 0.2;
168
    }
169
170
    private boolean hasCurseOfBinding(ItemStack stack) {
171
        Holder<Enchantment> curse = getEnchantmentEntry(Enchantments.BINDING_CURSE);
172
        return curse != null && EnchantmentHelper.getItemEnchantmentLevel(curse, stack) > 0;
173
    }
174
175
    private int getEnchantmentLevel(ResourceKey<Enchantment> key, ItemStack stack) {
176
        Holder<Enchantment> entry = getEnchantmentEntry(key);
177
        return entry == null ? 0 : EnchantmentHelper.getItemEnchantmentLevel(entry, stack);
178
    }
179
180
    private Holder<Enchantment> getEnchantmentEntry(ResourceKey<Enchantment> key) {
181
        if (mc.level == null) return null;
182
        Registry<Enchantment> registry = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
183
        Enchantment enchantment = registry.getValue(key);
184
        return enchantment != null ? registry.wrapAsHolder(enchantment) : null;
185
    }
186
187
    private boolean isBroken(ItemStack stack) {
188
        if (stack == null || stack.isEmpty()) return false;
189
        int max = stack.getMaxDamage();
190
        if (max <= 0) return false;
191
        return (double) stack.getDamageValue() / max > 0.98;
192
    }
193
194
    private boolean hasInventorySpace() {
195
        if (mc.player == null) return false;
196
        for (int i = 0; i < 36; i++) {
197
            if (mc.player.getInventory().getItem(i).isEmpty()) {
198
                return true;
199
            }
200
        }
201
        return false;
202
    }
203
204
    private int armorScreenSlot(EquipmentSlot slot) {
205
        return switch (slot) {
206
            case HEAD -> 5;
207
            case CHEST -> 6;
208
            case LEGS -> 7;
209
            case FEET -> 8;
210
            default -> -1;
211
        };
212
    }
213
214
    public enum Mode {
215
        AUTO,
216
        WHITELIST
217
    }
218
219
    private record Candidate(int invSlot, ItemStack stack) {
220
    }
221
}
222
NicotineCombatsrc/client/java/nicotine/mod/mods/combat/AutoArmor.javaJava · 78 lines · 2.7 KB
AutoArmor.javaJava · Minecraft 26.3 · 78 lines · 2.7 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.combat;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.core.component.DataComponents;
5
import net.minecraft.world.entity.EquipmentSlot;
6
import net.minecraft.world.item.Item;
7
import net.minecraft.world.item.ItemStack;
8
import net.minecraft.world.item.Items;
9
import nicotine.events.ClientLevelTickEvent;
10
import nicotine.mod.Mod;
11
import nicotine.mod.ModCategory;
12
import nicotine.mod.option.KeybindOption;
13
import nicotine.mod.option.ToggleOption;
14
import nicotine.util.EventBus;
15
import nicotine.util.Inventory;
16
import nicotine.util.Keybind;
17
import nicotine.util.Player;
18
19
import java.util.Arrays;
20
import java.util.List;
21
22
import static nicotine.util.Common.mc;
23
24
public class AutoArmor extends Mod {
25
26
    public AutoArmor() {
27
        super(ModCategory.Combat,"AutoArmor");
28
        this.keybind.keyCode = InputConstants.KEY_Z;
29
        this.keybind.name = "ElytraSwap";
30
    }
31
32
    @Override
33
    protected void init() {
34
        EventBus.register(ClientLevelTickEvent.class, event -> {
35
            if (!this.enabled || Inventory.isContainerOpen())
36
                return true;
37
38
            if (Keybind.keyReleased(keybind.name, true, keybind.keyCode, false)) {
39
                Player.elytraSwap();
40
                return true;
41
            }
42
43
            List<ItemStack> armorItems = Player.getArmorItems();
44
45
            if (!armorItems.contains(ItemStack.EMPTY))
46
                return true;
47
48
            for (int i = 0; i <= 35; i++) {
49
                ItemStack curStack = mc.player.getInventory().getItem(i);
50
                Item curItem = curStack.getItem();
51
                if (curItem.components().has(DataComponents.EQUIPPABLE)) {
52
                    EquipmentSlot equipment = curItem.components().get(DataComponents.EQUIPPABLE).slot();
53
54
                    if (equipment.getType() != EquipmentSlot.Type.HUMANOID_ARMOR)
55
                        continue;
56
57
                    int equipmentSlot = equipment.getIndex() + 1;
58
                    int armorSlot = 35 + equipmentSlot;
59
60
                    ItemStack armorStack = mc.player.getInventory().getItem(armorSlot);
61
62
                   if (armorStack == ItemStack.EMPTY && curItem != Items.ELYTRA) {
63
                        Inventory.swap(i < 9 ? 36 + i : i, 9 - equipmentSlot);
64
                    } else if (curItem == Items.ELYTRA && armorStack.getItem() == Items.ELYTRA) {
65
                        if (armorStack.getDamageValue() > curStack.getDamageValue() && armorStack.getDamageValue() == armorStack.getMaxDamage() - 1) {
66
                            Inventory.swap(i < 9 ? 36 + i : i, 9 - equipmentSlot);
67
                            Player.startFlying();
68
                        }
69
                    }
70
                }
71
            }
72
73
            return true;
74
        });
75
76
    }
77
}
78
LiquidBounce (Kotlin)COMBATsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/combat/autoarmor/ModuleAutoArmor.ktKotlin · 138 lines · 5.5 KB

Automatically equips the best armor in your inventory.

SettingsCanSwapArmor
ModuleAutoArmor.ktKotlin · Minecraft 26.2 · 138 lines · 5.5 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.combat.autoarmor
20
21
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
22
import net.ccbluex.liquidbounce.event.events.ScheduleInventoryActionEvent
23
import net.ccbluex.liquidbounce.event.handler
24
import net.ccbluex.liquidbounce.features.module.ClientModule
25
import net.ccbluex.liquidbounce.features.module.ModuleCategories
26
import net.ccbluex.liquidbounce.features.module.modules.combat.autoarmor.AutoArmorSaveArmor.durabilityThreshold
27
import net.ccbluex.liquidbounce.features.module.modules.combat.autoarmor.ModuleAutoArmor.performMoveOrHotbarClick
28
import net.ccbluex.liquidbounce.utils.inventory.ArmorItemSlot
29
import net.ccbluex.liquidbounce.utils.inventory.HotbarItemSlot
30
import net.ccbluex.liquidbounce.utils.inventory.InventoryAction
31
import net.ccbluex.liquidbounce.utils.inventory.InventoryManager
32
import net.ccbluex.liquidbounce.utils.inventory.PlayerInventoryConstraints
33
import net.ccbluex.liquidbounce.utils.inventory.hasInventorySpace
34
import net.ccbluex.liquidbounce.utils.item.armor.ArmorEvaluation
35
import net.ccbluex.liquidbounce.utils.item.armor.ArmorPiece
36
import net.ccbluex.liquidbounce.utils.item.isGlider
37
import net.ccbluex.liquidbounce.utils.kotlin.Priority
38
39
/**
40
 * AutoArmor module
41
 *
42
 * Automatically puts on the best armor.
43
 */
44
object ModuleAutoArmor : ClientModule("AutoArmor", ModuleCategories.COMBAT) {
45
46
    val inventoryConstraints = tree(PlayerInventoryConstraints())
47
48
    /**
49
     * Should the module use the hotbar to equip armor pieces?
50
     * If disabled, it will only use inventory moves.
51
     */
52
    object UseHotbar : ToggleableValueGroup(this, "Hotbar", true) {
53
        /**
54
         * Defines whether the [UseHotbar] option supports the armor swap from MC 1.19.4+.
55
         */
56
        val canSwapArmor by boolean("CanSwapArmor", false)
57
    }
58
59
    init {
60
        tree(UseHotbar)
61
        tree(AutoArmorSaveArmor)
62
    }
63
64
    @Suppress("unused")
65
    private val scheduleHandler = handler<ScheduleInventoryActionEvent> { event ->
66
        if (player.isSpectator) {
67
            return@handler
68
        }
69
70
        // Filter out already equipped armor pieces
71
        val durabilityThreshold = if (AutoArmorSaveArmor.enabled) durabilityThreshold else Int.MIN_VALUE
72
73
        val armorToEquip = ArmorEvaluation
74
            .findBestArmorPieces(durabilityThreshold = durabilityThreshold)
75
            .values.filterNotNull().filter { !it.isAlreadyEquipped }
76
77
        for (armorPiece in armorToEquip) {
78
            event.schedule(
79
                inventoryConstraints,
80
                equipArmorPiece(armorPiece) ?: continue,
81
                Priority.IMPORTANT_FOR_PLAYER_LIFE
82
            )
83
        }
84
    }
85
86
    /**
87
     * Tries to move the given armor piece in the target slot in the inventory. There are two possible behaviors:
88
     * 1. If there is no free space in the target slot, it will make space in that slot (see [performMoveOrHotbarClick])
89
     * 2. If there is free space, it will move the armor piece there
90
     *
91
     * @return false if a move was not possible, true if a move occurred
92
     */
93
    private fun equipArmorPiece(armorPiece: ArmorPiece): InventoryAction? {
94
        val stackInArmor = player.inventory.getItem(armorPiece.inventorySlot)
95
96
        if (stackInArmor.isGlider) {
97
            return null
98
        }
99
100
        return performMoveOrHotbarClick(armorPiece, isInArmorSlot = !stackInArmor.isEmpty)
101
    }
102
103
    /**
104
     * Central move-function of this module. There are following options:
105
     * 1. If the slot is in the hotbar, we do a right-click on it (if possible)
106
     * 2. If the slot is in inventory, we shift+left click it
107
     * 3. If the slot is an armor slot and there is free space in inventory, we shift+left click it otherwise
108
     * throw it out.
109
     *
110
     * @param isInArmorSlot True if the slot is an armor slot.
111
     * @return True if a move occurred.
112
     */
113
    private fun performMoveOrHotbarClick(
114
        armorPiece: ArmorPiece,
115
        isInArmorSlot: Boolean
116
    ): InventoryAction {
117
        val inventorySlot = armorPiece.itemSlot
118
        val armorPieceSlot = if (isInArmorSlot) ArmorItemSlot(armorPiece.slotType) else inventorySlot
119
120
        val canTryHotbarMove = UseHotbar.enabled &&
121
            !InventoryManager.isInventoryOpen && (!isInArmorSlot || UseHotbar.canSwapArmor)
122
123
        if (inventorySlot is HotbarItemSlot && canTryHotbarMove) {
124
            return InventoryAction.UseItem(inventorySlot, this)
125
        }
126
127
        // Should the item be just thrown out of the inventory
128
        val shouldThrow = isInArmorSlot && !hasInventorySpace()
129
130
        return if (shouldThrow) {
131
            InventoryAction.Click.performThrow(screen = null, armorPieceSlot)
132
        } else {
133
            InventoryAction.Click.performQuickMove(screen = null, armorPieceSlot)
134
        }
135
    }
136
137
}
138