AutoEat module

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

4 implementationsPLAYERPlayer

Full module source: 4 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/AutoEat.javaJava · 112 lines · 4.3 KB

Eat food under given conditions.

SettingsHungerGappleChorusRottenFleshSpiderEyePufferfishSwapBackPauseBaritone
AutoEat.javaJava · Minecraft 26.2 · 112 lines · 4.3 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.player;
2
3
import thunder.hack.utility.BaritoneIntegration;
4
import net.minecraft.core.component.DataComponents;
5
import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket;
6
import net.minecraft.world.InteractionHand;
7
import net.minecraft.world.item.Item;
8
import net.minecraft.world.item.ItemStack;
9
import net.minecraft.world.item.Items;
10
import thunder.hack.ThunderHack;
11
import thunder.hack.injection.accesors.IMinecraftClient;
12
import thunder.hack.features.modules.Module;
13
import thunder.hack.setting.Setting;
14
15
public class AutoEat extends Module {
16
    public AutoEat() {
17
        super("AutoEat", Category.PLAYER);
18
    }
19
20
    public final Setting<Integer> hunger = new Setting("Hunger", 8, 0, 20);
21
    public final Setting<Boolean> gapple = new Setting("Gapple", false);
22
    public final Setting<Boolean> chorus = new Setting("Chorus", false);
23
    public final Setting<Boolean> rottenFlesh = new Setting("RottenFlesh", false);
24
    public final Setting<Boolean> spiderEye = new Setting("SpiderEye", false);
25
    public final Setting<Boolean> pufferfish = new Setting("Pufferfish", false);
26
    public final Setting<Boolean> swapBack = new Setting<>("SwapBack", true);
27
    public final Setting<Boolean> pauseBaritone = new Setting<>("PauseBaritone", true, v -> ThunderHack.baritone);
28
29
    private boolean eating;
30
    private int prevSlot;
31
32
    @Override
33
    public void onUpdate() {
34
        if (mc.player.getFoodData().getFoodLevel() <= hunger.getValue()) {
35
36
            boolean found;
37
38
            if(!isHandGood(InteractionHand.MAIN_HAND) && !isHandGood(InteractionHand.OFF_HAND)) {
39
                found = switchToFood();
40
            } else found = true;
41
42
            if (!found) {
43
                if (eating)
44
                    stopEating();
45
                return;
46
            }
47
48
            startEating();
49
        } else if (eating)
50
            stopEating();
51
    }
52
53
    public void startEating() {
54
        eating = true;
55
56
        if (mc.gui.screen() != null && !mc.player.isUsingItem())
57
            ((IMinecraftClient) mc).idoItemUse();
58
        else {
59
            if(pauseBaritone.getValue() && ThunderHack.baritone)
60
                BaritoneIntegration.execute("pause");
61
62
            mc.options.keyUse.setDown(true);
63
        }
64
    }
65
66
    public void stopEating() {
67
        eating = false;
68
        mc.options.keyUse.setDown(false);
69
        if (swapBack.getValue())
70
            mc.player.getInventory().setSelectedSlot(prevSlot);
71
72
        if (pauseBaritone.getValue() && ThunderHack.baritone)
73
            BaritoneIntegration.execute("resume");
74
    }
75
76
    public boolean switchToFood() {
77
        for (int i = 0; i < 9; i++) {
78
            ItemStack stack = mc.player.getInventory().getItem(i);
79
            if (stack.getComponents().has(DataComponents.FOOD)) {
80
                if (!gapple.getValue() && (stack.getItem() == Items.GOLDEN_APPLE || stack.getItem() == Items.ENCHANTED_GOLDEN_APPLE))
81
                    continue;
82
                if (!chorus.getValue() && (stack.getItem() == Items.CHORUS_FRUIT))
83
                    continue;
84
                if (!rottenFlesh.getValue() && (stack.getItem() == Items.ROTTEN_FLESH))
85
                    continue;
86
                if (!spiderEye.getValue() && (stack.getItem() == Items.SPIDER_EYE))
87
                    continue;
88
                if (!pufferfish.getValue() && (stack.getItem() == Items.PUFFERFISH))
89
                    continue;
90
                prevSlot = mc.player.getInventory().getSelectedSlot();
91
                mc.player.getInventory().setSelectedSlot(i);
92
                sendPacket(new ServerboundSetCarriedItemPacket(i));
93
                return true;
94
            }
95
        }
96
        return false;
97
    }
98
99
100
    private boolean isHandGood(InteractionHand hand) {
101
        ItemStack stack = hand == InteractionHand.MAIN_HAND ? mc.player.getMainHandItem() : mc.player.getOffhandItem();
102
103
        Item item = stack.getItem();
104
        return stack.getComponents().has(DataComponents.FOOD)
105
                && (gapple.getValue() || (item != Items.GOLDEN_APPLE && item != Items.ENCHANTED_GOLDEN_APPLE))
106
                && (chorus.getValue() || item != Items.CHORUS_FRUIT)
107
                && (rottenFlesh.getValue() || item != Items.ROTTEN_FLESH)
108
                && (spiderEye.getValue() || item != Items.SPIDER_EYE)
109
                && (pufferfish.getValue() || item != Items.PUFFERFISH);
110
    }
111
}
112
OfflineClientPLAYERsrc/main/java/com/jellypudding/offlineclient/modules/player/AutoEat.javaJava · 499 lines · 19.2 KB

Eats for you when you get hungry or hurt.

SettingsTriggerHungerInjured hungerInjury thresholdTarget hungerHealthPriorityAvoidTake fromSave golden applesPrefer soupTidy bowlsAvoid clicksUse offhandEat whilst movingPause combatEat in screensNo slowdownPause on fire
AutoEat.javaJava · Minecraft 26.2 · 499 lines · 19.2 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.player;
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.EnumSetting;
9
import com.jellypudding.offlineclient.setting.NumberSetting;
10
import com.jellypudding.offlineclient.setting.RegistryListSetting;
11
import com.jellypudding.offlineclient.util.BlockUtil;
12
import com.jellypudding.offlineclient.util.EntityUtil;
13
import com.jellypudding.offlineclient.util.InventoryUtil;
14
import com.jellypudding.offlineclient.util.Modules;
15
import com.jellypudding.offlineclient.util.UseHold;
16
import net.minecraft.core.component.DataComponents;
17
import net.minecraft.core.registries.BuiltInRegistries;
18
import net.minecraft.world.InteractionHand;
19
import net.minecraft.world.effect.MobEffects;
20
import net.minecraft.world.entity.Entity;
21
import net.minecraft.world.entity.TamableAnimal;
22
import net.minecraft.world.entity.npc.villager.AbstractVillager;
23
import net.minecraft.world.entity.player.Inventory;
24
import net.minecraft.world.food.FoodProperties;
25
import net.minecraft.world.item.Item;
26
import net.minecraft.world.item.ItemStack;
27
import net.minecraft.world.item.Items;
28
import net.minecraft.world.phys.BlockHitResult;
29
import net.minecraft.world.phys.EntityHitResult;
30
31
import java.util.List;
32
33
// Eats when hunger or health drops low. Food anywhere in the inventory
34
// counts and is swapped into the hotbar and back.
35
public final class AutoEat extends Module {
36
37
    // Ticks to wait after a meal whilst the food and the healing land.
38
    private static final int SETTLE_TICKS = 10;
39
40
    // A golden apple takes a moment to land. Rechecking too early eats a second one.
41
    private static final int HEAL_SETTLE_TICKS = 30;
42
43
    // The first slot of the backpack. Empty bowls are gathered there.
44
    private static final int BOWL_SLOT = 9;
45
46
    public enum Priority { BEST_HUNGER, BEST_SATURATION, BEST_OVERALL }
47
48
    public enum TakeFrom { HANDS, HOTBAR, INVENTORY }
49
50
    public enum Trigger { HUNGER, HEALTH, EITHER, BOTH }
51
52
    private final EnumSetting<Trigger> trigger = new EnumSetting<>("Trigger",
53
        "What starts a meal.", Trigger.EITHER)
54
        .describe(Trigger.HUNGER, "Eats when your food drops to the Hunger value.")
55
        .describe(Trigger.HEALTH, "Eats when your health drops to the Health value.")
56
        .describe(Trigger.EITHER, "Eats when your food or your health drops to its value.")
57
        .describe(Trigger.BOTH, "Eats only when your food and your health have both dropped to their values.");
58
    private final NumberSetting hunger = new NumberSetting("Hunger",
59
        "Start eating at or below this many food points. Full is 20.", 14, 1, 19, 1)
60
        .under(trigger, Trigger.HUNGER, Trigger.EITHER, Trigger.BOTH);
61
    private final NumberSetting injuredHunger = new NumberSetting("Injured hunger",
62
        "Start eating at or below this many food points whilst you are hurt. "
63
            + "Regeneration needs a nearly full bar.", 19, 1, 20, 1)
64
        .under(trigger, Trigger.HUNGER, Trigger.EITHER, Trigger.BOTH);
65
    private final NumberSetting injuryThreshold = new NumberSetting("Injury threshold",
66
        "How much health you must be missing before Injured hunger takes over.",
67
        1.5, 0.5, 10, 0.5, " hearts").min(0.5)
68
        .under(trigger, Trigger.HUNGER, Trigger.EITHER, Trigger.BOTH);
69
    private final NumberSetting targetHunger = new NumberSetting("Target hunger",
70
        "Fills your bar up to this many food points and picks food that wastes none.",
71
        20, 1, 20, 1);
72
    private final NumberSetting health = new NumberSetting("Health",
73
        "Start eating at or below this many hearts. A golden apple is reached for first and other food after. "
74
            + "Zero turns it off.",
75
        5, 0, 10, 0.5, " hearts").min(0).max(20)
76
        .under(trigger, Trigger.HEALTH, Trigger.EITHER, Trigger.BOTH);
77
    private final EnumSetting<Priority> priority = new EnumSetting<>("Priority",
78
        "Which food to reach for first.", Priority.BEST_HUNGER)
79
        .describe(Priority.BEST_HUNGER, "Eats whatever restores the most food points.")
80
        .describe(Priority.BEST_SATURATION, "Eats whatever gives the most saturation.")
81
        .describe(Priority.BEST_OVERALL, "Eats whatever scores best on both together.");
82
    private final RegistryListSetting<Item> avoid = new RegistryListSetting<>("Avoid",
83
        "Food that never gets eaten. Click to pick it.", BuiltInRegistries.ITEM,
84
        List.of(Items.ROTTEN_FLESH, Items.SPIDER_EYE, Items.POISONOUS_POTATO,
85
            Items.PUFFERFISH, Items.CHICKEN, Items.SUSPICIOUS_STEW, Items.CHORUS_FRUIT));
86
    private final EnumSetting<TakeFrom> takeFrom = new EnumSetting<>("Take from",
87
        "Where food may be taken from.", TakeFrom.INVENTORY)
88
        .describe(TakeFrom.HANDS, "Only eats what is already in your hands.")
89
        .describe(TakeFrom.HOTBAR, "Picks food from the hotbar only.")
90
        .describe(TakeFrom.INVENTORY, "Borrows food from anywhere in the inventory.");
91
    private final BoolSetting saveGapples = new BoolSetting("Save golden apples",
92
        "Never eats a golden apple for hunger alone. They are kept for the Health check.", false);
93
    private final BoolSetting preferSoup = new BoolSetting("Prefer soup",
94
        "Reaches for stew and soup before other food whilst healing.", false);
95
    private final BoolSetting tidyBowls = new BoolSetting("Tidy bowls",
96
        "Gathers empty bowls into the first backpack slot so they are easy to refill.", false);
97
    private final BoolSetting avoidClicks = new BoolSetting("Avoid clicks",
98
        "Never eat whilst your crosshair is on something a right click would open.", true);
99
    private final BoolSetting offhand = new BoolSetting("Use offhand",
100
        "Reach for food in your offhand first.", true);
101
    private final BoolSetting whileMoving = new BoolSetting("Eat whilst moving",
102
        "Eat on the move. Eating drops you to walking speed.", true);
103
    private final BoolSetting pauseCombat = new BoolSetting("Pause combat",
104
        "Holds the combat modules back whilst you eat.", true);
105
    private final BoolSetting whileBusy = new BoolSetting("Eat in screens",
106
        "Keeps eating whilst a chest or inventory is open.", false);
107
    private final BoolSetting noSlowdown = new BoolSetting("No slowdown",
108
        "Keeps your normal speed whilst eating. Meals you start yourself count too.", false);
109
    private final BoolSetting pauseOnFire = new BoolSetting("Pause on fire",
110
        "Stops eating whilst you are burning.", false);
111
112
    private boolean eating;
113
    private boolean healing;
114
    private final UseHold use = new UseHold();
115
    private int settle;
116
    private final InventoryUtil.HotbarLoan loan = new InventoryUtil.HotbarLoan();
117
118
    public AutoEat() {
119
        super("AutoEat", "Eats for you when you get hungry or hurt.", Category.PLAYER);
120
        addSettings(trigger, hunger, injuredHunger, injuryThreshold, targetHunger, health,
121
            priority, avoid, takeFrom, saveGapples, preferSoup, tidyBowls, avoidClicks,
122
            offhand, whileMoving, pauseCombat, whileBusy, noSlowdown, pauseOnFire);
123
        searchTags("food", "golden apple", "gapple");
124
    }
125
126
    public boolean isEating() {
127
        return isEnabled() && eating && pauseCombat.isOn();
128
    }
129
130
    public boolean isBusy() {
131
        return isEnabled() && eating;
132
    }
133
134
    // Read by LocalPlayerMixin to keep a meal from slowing you down.
135
    public boolean suppressesSlowdown() {
136
        return isEnabled() && noSlowdown.isOn() && eatingFood();
137
    }
138
139
    // True whilst any food is going down. A meal started by hand counts.
140
    private boolean eatingFood() {
141
        return mc.player != null && mc.player.isUsingItem()
142
            && mc.player.getUseItem().has(DataComponents.FOOD);
143
    }
144
145
    @Override
146
    public String getSuffix() {
147
        return eating ? "eating" : null;
148
    }
149
150
    @Override
151
    protected void onDisable() {
152
        stopEating();
153
    }
154
155
    @Subscribe
156
    private void onTick(TickEvent event) {
157
        if (!inGame() || mc.player.isSpectator() || mc.player.getAbilities().instabuild) {
158
            stopEating();
159
            return;
160
        }
161
        if (mc.player.isDeadOrDying()) {
162
            // Respawn rebuilds the inventory.
163
            loan.forget();
164
            stopEating();
165
            settle = 0;
166
            return;
167
        }
168
        if (settle > 0) {
169
            settle--;
170
            return;
171
        }
172
        moveBowl();
173
        if (burning()) {
174
            stopEating();
175
            return;
176
        }
177
178
        if (eating) {
179
            continueEating();
180
            return;
181
        }
182
        if (Modules.feeding(this)) {
183
            return;
184
        }
185
        // A carried stack would be dropped by a slot swap.
186
        if (!mc.player.containerMenu.getCarried().isEmpty()) {
187
            return;
188
        }
189
        if (busy() && !whileBusy.isOn()) {
190
            return;
191
        }
192
        if (potionBusy() || clickInTheWay()) {
193
            return;
194
        }
195
        if (!whileMoving.isOn() && mc.player.getDeltaMovement().horizontalDistanceSqr() > 1.0E-4) {
196
            return;
197
        }
198
199
        boolean healthLow = healthLow();
200
        if (!triggered(healthLow, wantsFood())) {
201
            return;
202
        }
203
        int limit = slotLimit();
204
        int slot = healthLow && !healingWasted() ? findHealing(limit) : -1;
205
        healing = slot != -1;
206
        if (slot == -1 && healthLow && preferSoup.isOn()) {
207
            slot = findSoup(limit);
208
        }
209
        if (slot == -1) {
210
            slot = findFood(limit);
211
        }
212
        if (slot == -1) {
213
            return;
214
        }
215
        beginEating(slot);
216
    }
217
218
    // The Health value only counts in the modes that show it.
219
    private boolean healthLow() {
220
        return !trigger.is(Trigger.HUNGER) && EntityUtil.healthAtOrBelow(health.getValue());
221
    }
222
223
    private boolean triggered(boolean healthLow, boolean hungerLow) {
224
        return switch (trigger.getValue()) {
225
            case HUNGER -> hungerLow;
226
            case HEALTH -> healthLow;
227
            case EITHER -> healthLow || hungerLow;
228
            case BOTH -> healthLow && hungerLow;
229
        };
230
    }
231
232
    // Hands mode searches no slots. Hotbar mode or an open screen searches the
233
    // hotbar. Anything else searches the whole inventory.
234
    private int slotLimit() {
235
        if (takeFrom.is(TakeFrom.HANDS)) {
236
            return 0;
237
        }
238
        if (takeFrom.is(TakeFrom.HOTBAR) || busy()) {
239
            return InventoryUtil.HOTBAR_SIZE;
240
        }
241
        return InventoryUtil.WHOLE_INVENTORY;
242
    }
243
244
    // The held slot always counts. The rest only up to the limit.
245
    private boolean searchable(int slot, int limit) {
246
        return slot < limit || slot == InventoryUtil.selectedSlot();
247
    }
248
249
    // A screen or a foreign container is open.
250
    private boolean busy() {
251
        return mc.gui.screen() != null || mc.player.containerMenu.containerId != 0;
252
    }
253
254
    // The absorption a golden apple grants does not stack. A second one is wasted.
255
    private boolean healingWasted() {
256
        return mc.player.getAbsorptionAmount() > 0;
257
    }
258
259
    // Fire resistance takes the burn damage away. A meal stays safe under it.
260
    private boolean burning() {
261
        return pauseOnFire.isOn() && mc.player.isOnFire()
262
            && !mc.player.hasEffect(MobEffects.FIRE_RESISTANCE);
263
    }
264
265
    private boolean potionBusy() {
266
        AutoPotion potion = Modules.get(AutoPotion.class);
267
        return potion != null && potion.isDrinking();
268
    }
269
270
    private boolean wantsFood() {
271
        int food = mc.player.getFoodData().getFoodLevel();
272
        return food <= (injured() ? injuredHunger.getInt() : hunger.getInt());
273
    }
274
275
    // True whilst enough health is missing for the injured threshold to take over.
276
    private boolean injured() {
277
        return mc.player.getMaxHealth() - mc.player.getHealth() >= injuryThreshold.getValue() * 2;
278
    }
279
280
    // A right click through a meal would open a chest or start a trade.
281
    private boolean clickInTheWay() {
282
        if (!avoidClicks.isOn() || mc.hitResult == null) {
283
            return false;
284
        }
285
        if (mc.hitResult instanceof EntityHitResult entityHit) {
286
            Entity entity = entityHit.getEntity();
287
            return entity instanceof AbstractVillager || entity instanceof TamableAnimal;
288
        }
289
        return mc.hitResult instanceof BlockHitResult blockHit
290
            && BlockUtil.opensOnClick(BlockUtil.state(blockHit.getBlockPos()));
291
    }
292
293
    // Soup servers want the empties in one place for a refill.
294
    private void moveBowl() {
295
        if (!tidyBowls.isOn() || eating || !InventoryUtil.inventoryFree()) {
296
            return;
297
        }
298
        if (mc.player.getInventory().getItem(BOWL_SLOT).is(Items.BOWL)) {
299
            return;
300
        }
301
        int from = InventoryUtil.findSlot(Items.BOWL, InventoryUtil.WHOLE_INVENTORY);
302
        if (from == -1 || from == BOWL_SLOT) {
303
            return;
304
        }
305
        InventoryUtil.swap(InventoryUtil.networkSlot(from), InventoryUtil.networkSlot(BOWL_SLOT));
306
    }
307
308
    // Honey bottles and golden apples work at full hunger. Other food does not.
309
    private boolean edibleNow(ItemStack stack) {
310
        FoodProperties food = stack.get(DataComponents.FOOD);
311
        if (food == null) {
312
            return false;
313
        }
314
        return mc.player.getFoodData().getFoodLevel() < 20 || food.canAlwaysEat();
315
    }
316
317
    private void beginEating(int slot) {
318
        // The offhand needs no swap at all.
319
        if (slot == Inventory.SLOT_OFFHAND) {
320
            eating = true;
321
            use.begin();
322
            return;
323
        }
324
        if (!loan.select(slot)) {
325
            return;
326
        }
327
        eating = true;
328
        use.begin();
329
    }
330
331
    private void continueEating() {
332
        if ((busy() && !whileBusy.isOn()) || !holdingFood()) {
333
            stopEating();
334
            return;
335
        }
336
        if (!use.tick()) {
337
            finishMeal();
338
            return;
339
        }
340
        // A screen stops the game reading the use key. The meal is started by hand.
341
        if (busy() && !mc.player.isUsingItem()) {
342
            mc.gameMode.useItem(mc.player, offhandUsable()
343
                ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND);
344
        }
345
    }
346
347
    // A golden apple needs longer before the health is worth reading again.
348
    private void finishMeal() {
349
        boolean wasHealing = healing;
350
        stopEating();
351
        settle = wasHealing ? HEAL_SETTLE_TICKS : SETTLE_TICKS;
352
    }
353
354
    // The use key hits the main hand first. Food there fires instead of the offhand.
355
    private boolean offhandUsable() {
356
        return offhand.isOn()
357
            && !mc.player.getInventory().getSelectedItem().has(DataComponents.FOOD);
358
    }
359
360
    private boolean holdingFood() {
361
        if (isEdible(mc.player.getInventory().getSelectedItem())) {
362
            return true;
363
        }
364
        return offhand.isOn() && isEdible(mc.player.getOffhandItem());
365
    }
366
367
    private void stopEating() {
368
        if (eating) {
369
            eating = false;
370
            healing = false;
371
            use.release();
372
        }
373
        // A loan whose return was refused earlier gets another go.
374
        loan.giveBack();
375
    }
376
377
    // The plain apple wins over the enchanted one.
378
    private int findHealing(int limit) {
379
        if (offhandUsable()) {
380
            ItemStack held = mc.player.getOffhandItem();
381
            if ((held.is(Items.GOLDEN_APPLE) || held.is(Items.ENCHANTED_GOLDEN_APPLE))
382
                && !avoid.contains(held.getItem())) {
383
                return Inventory.SLOT_OFFHAND;
384
            }
385
        }
386
        int enchanted = -1;
387
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
388
            if (!searchable(i, limit)) {
389
                continue;
390
            }
391
            ItemStack stack = mc.player.getInventory().getItem(i);
392
            if (stack.is(Items.GOLDEN_APPLE) && !avoid.contains(stack.getItem())) {
393
                return i;
394
            }
395
            if (enchanted == -1 && stack.is(Items.ENCHANTED_GOLDEN_APPLE)
396
                && !avoid.contains(stack.getItem())) {
397
                enchanted = i;
398
            }
399
        }
400
        return enchanted;
401
    }
402
403
    // Food that wastes no points first. Anything edible after that. A golden
404
    // apple only when nothing is left and it is not saved.
405
    private int findFood(int limit) {
406
        int best = pickFood(limit, true);
407
        if (best == -1) {
408
            best = pickFood(limit, false);
409
        }
410
        if (best == -1 && !saveGapples.isOn()) {
411
            return findHealing(limit);
412
        }
413
        return best;
414
    }
415
416
    private int pickFood(int limit, boolean noWaste) {
417
        if (offhandUsable()) {
418
            ItemStack held = mc.player.getOffhandItem();
419
            if (isEdible(held) && !isHealing(held) && edibleNow(held) && (!noWaste || fits(held))) {
420
                return Inventory.SLOT_OFFHAND;
421
            }
422
        }
423
        int best = -1;
424
        double bestScore = 0;
425
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
426
            if (!searchable(i, limit)) {
427
                continue;
428
            }
429
            ItemStack stack = mc.player.getInventory().getItem(i);
430
            if (!isEdible(stack) || isHealing(stack) || !edibleNow(stack)) {
431
                continue;
432
            }
433
            if (noWaste && !fits(stack)) {
434
                continue;
435
            }
436
            double score = score(stack);
437
            if (score > bestScore) {
438
                bestScore = score;
439
                best = i;
440
            }
441
        }
442
        return best;
443
    }
444
445
    // True when the food would not push the bar past the target.
446
    private boolean fits(ItemStack stack) {
447
        FoodProperties food = stack.get(DataComponents.FOOD);
448
        if (food == null || food.canAlwaysEat()) {
449
            return true;
450
        }
451
        return mc.player.getFoodData().getFoodLevel() + food.nutrition() <= targetHunger.getInt();
452
    }
453
454
    // Stew and soup heal on soup servers where a golden apple is never allowed.
455
    private int findSoup(int limit) {
456
        if (offhandUsable() && isSoup(mc.player.getOffhandItem())) {
457
            return Inventory.SLOT_OFFHAND;
458
        }
459
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
460
            if (searchable(i, limit) && isSoup(mc.player.getInventory().getItem(i))) {
461
                return i;
462
            }
463
        }
464
        return -1;
465
    }
466
467
    private boolean isSoup(ItemStack stack) {
468
        if (!isEdible(stack) || !edibleNow(stack)) {
469
            return false;
470
        }
471
        return stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW)
472
            || stack.is(Items.BEETROOT_SOUP);
473
    }
474
475
    private double score(ItemStack stack) {
476
        FoodProperties food = stack.get(DataComponents.FOOD);
477
        if (food == null) {
478
            return 0;
479
        }
480
        // Saturation is the whole value and not a multiplier of the nutrition.
481
        if (priority.is(Priority.BEST_SATURATION)) {
482
            return food.saturation();
483
        }
484
        if (priority.is(Priority.BEST_OVERALL)) {
485
            return food.nutrition() + food.saturation();
486
        }
487
        return food.nutrition();
488
    }
489
490
    private boolean isEdible(ItemStack stack) {
491
        return stack.has(DataComponents.FOOD) && !avoid.contains(stack.getItem());
492
    }
493
494
    // Golden apples are kept back for the Health check.
495
    private boolean isHealing(ItemStack stack) {
496
        return stack.is(Items.GOLDEN_APPLE) || stack.is(Items.ENCHANTED_GOLDEN_APPLE);
497
    }
498
}
499
CombatantPLAYERsrc/main/java/combatant/client/features/module/modules/player/AutoEat.javaJava · 385 lines · 13.4 KB
SettingsautoEatModeautoEatHandautoEatHpThresholdautoEatAvoidFoods
AutoEat.javaJava · Minecraft 26.2 · 385 lines · 13.4 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 lombok.Getter;
11
import lombok.RequiredArgsConstructor;
12
import net.minecraft.client.Minecraft;
13
import net.minecraft.client.player.LocalPlayer;
14
import net.minecraft.core.registries.BuiltInRegistries;
15
import net.minecraft.resources.Identifier;
16
import net.minecraft.world.InteractionHand;
17
import net.minecraft.world.InteractionResult;
18
import net.minecraft.world.item.ItemStack;
19
import net.minecraft.world.item.Items;
20
import combatant.client.config.values.BooleanMapValue;
21
import combatant.client.config.values.EnumValue;
22
import combatant.client.config.values.NumberValue;
23
import combatant.client.features.gui.hud.draggable.impl.Itemizer;
24
import combatant.client.features.module.Module;
25
import combatant.client.features.module.ModuleCategory;
26
import combatant.client.features.module.ModuleInfo;
27
import combatant.client.mixins.accessors.PlayerInventoryAccessor;
28
import combatant.client.util.item.FoodUtil;
29
import combatant.client.util.player.inventory.InventorySwap;
30
31
//todo Description
32
@ModuleInfo(
33
        id = "autoeat",
34
        displayName = "AutoEat",
35
        category = ModuleCategory.PLAYER
36
)
37
public class AutoEat extends Module {
38
39
    private static final String SETTING_EAT_MODE = "eat_mode";
40
    private static final String SETTING_HAND_MODE = "hand_mode";
41
    private static final String SETTING_AVOID_FOODS = "avoid_foods";
42
    private static final String SETTING_HP_THRESHOLD = "hp_threshold";
43
44
    private final Minecraft mc = Minecraft.getInstance();
45
    private final EnumValue<EatMode> eatMode =
46
            enumSetting("autoEatMode", SETTING_EAT_MODE, EatMode.INSTANT, EatMode.INSTANT, EatMode.EXACT);
47
    private final EnumValue<HandMode> handMode =
48
            enumSetting("autoEatHand", SETTING_HAND_MODE, HandMode.MAINHAND, HandMode.MAINHAND, HandMode.OFFHAND);
49
    private final NumberValue<Integer> hpThreshold =
50
            num("autoEatHpThreshold", SETTING_HP_THRESHOLD, 8, 1, 20);
51
    private final BooleanMapValue avoidFoods = group(
52
            "autoEatAvoidFoods",
53
            SETTING_AVOID_FOODS,
54
            new java.util.LinkedHashMap<>() {{
55
                put("golden_apple", true);
56
                put("enchanted_golden_apple", true);
57
            }}
58
    );
59
    private boolean forcingUse = false;
60
    private boolean useKeyWasPressed = false;
61
    private int prevSelectedSlot = -1;
62
    private boolean restoreSelected = false;
63
    private int restoreInvSlot = -1;
64
    private int restoreHotbarSlot = -1;
65
    private boolean restoreMainPending = false;
66
    private int restoreOffhandSlot = -1;
67
    private boolean restoreOffhandPending = false;
68
69
    @Override
70
    public void onDisable() {
71
        if (mc != null && mc.player != null) {
72
            stopAutoUse(mc.player);
73
        }
74
    }
75
76
    @Override
77
    public void onTick() {
78
        if (!isEnabled()) return;
79
        if (mc == null || mc.player == null || mc.gameMode == null) return;
80
81
        LocalPlayer player = mc.player;
82
83
        if (player.isSpectator() || player.getAbilities().instabuild) {
84
            stopAutoUse(player);
85
            return;
86
        }
87
88
        if (player.isUsingItem()) {
89
            if (FoodUtil.isFood(player.getUseItem())) {
90
                if (forcingUse && !mc.options.keyUse.isDown()) {
91
                    mc.options.keyUse.setDown(true);
92
                }
93
                return;
94
            }
95
            stopAutoUse(player);
96
            return;
97
        }
98
99
        int hunger = player.getFoodData().getFoodLevel();
100
        int missing = 20 - hunger;
101
        int hp = Math.round(player.getHealth() + player.getAbsorptionAmount());
102
        boolean emergency = hp <= hpThreshold.get();
103
        if (missing <= 0 && !emergency) {
104
            stopAutoUse(player);
105
            return;
106
        }
107
108
        boolean exact = isExactMode();
109
        InteractionHand desiredHand = resolveDesiredHand(player);
110
111
        ItemStack offhand = player.getOffhandItem();
112
        ItemStack mainhand = player.getMainHandItem();
113
        boolean offhandCandidate = desiredHand == InteractionHand.OFF_HAND
114
                && shouldEatWith(offhand, missing, exact, emergency);
115
        boolean mainhandCandidate = desiredHand == InteractionHand.MAIN_HAND
116
                && shouldEatWith(mainhand, missing, exact, emergency);
117
        float offhandScore = offhandCandidate ? FoodUtil.scoreFood(offhand) : Float.NEGATIVE_INFINITY;
118
        float mainhandScore = mainhandCandidate ? FoodUtil.scoreFood(mainhand) : Float.NEGATIVE_INFINITY;
119
120
        int bestSlot = handMode.get() == HandMode.OFFHAND
121
                ? findBestFoodSlotPreferInventory(player, missing, exact, emergency)
122
                : findBestFoodSlot(player, missing, exact, emergency);
123
        if (bestSlot == -1 && (offhandCandidate || mainhandCandidate)) {
124
            startUse(player, offhandCandidate ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND);
125
            return;
126
        }
127
        if (bestSlot == -1) {
128
            stopAutoUse(player);
129
            return;
130
        }
131
132
        float bestScore = FoodUtil.scoreFood(player.getInventory().getItem(bestSlot));
133
        if (offhandCandidate && offhandScore >= bestScore) {
134
            startUse(player, InteractionHand.OFF_HAND);
135
            return;
136
        }
137
        if (mainhandCandidate && mainhandScore >= bestScore) {
138
            startUse(player, InteractionHand.MAIN_HAND);
139
            return;
140
        }
141
142
        boolean handReady = desiredHand == InteractionHand.OFF_HAND
143
                ? ensureFoodInOffhand(player, bestSlot, bestScore)
144
                : ensureFoodInMainhand(player, bestSlot, bestScore);
145
146
        if (!handReady) {
147
            stopAutoUse(player);
148
            return;
149
        }
150
151
        ItemStack active = desiredHand == InteractionHand.OFF_HAND
152
                ? player.getOffhandItem()
153
                : player.getMainHandItem();
154
155
        if (!shouldEatWith(active, missing, exact, emergency)) {
156
            stopAutoUse(player);
157
            return;
158
        }
159
160
        startUse(player, desiredHand);
161
    }
162
163
    private boolean isExactMode() {
164
        return eatMode.get() == EatMode.EXACT;
165
    }
166
167
    private InteractionHand resolveDesiredHand(LocalPlayer player) {
168
        boolean offhandBlocked = player.getOffhandItem().is(Items.TOTEM_OF_UNDYING);
169
        if (handMode.get() == HandMode.OFFHAND && !offhandBlocked) {
170
            return InteractionHand.OFF_HAND;
171
        }
172
        return InteractionHand.MAIN_HAND;
173
    }
174
175
    private boolean shouldEatWith(ItemStack stack, int missing, boolean exact, boolean emergency) {
176
        if (!FoodUtil.isFood(stack)) return false;
177
        if (!isFoodAllowed(stack)) return false;
178
        if (!exact || emergency) {
179
            if (missing > 0) return true;
180
            return emergency && FoodUtil.canAlwaysEat(stack);
181
        }
182
        return FoodUtil.getNutrition(stack) <= missing;
183
    }
184
185
    private int findBestFoodSlot(LocalPlayer player, int missing, boolean exact, boolean emergency) {
186
        int bestSlot = -1;
187
        float bestScore = Float.NEGATIVE_INFINITY;
188
189
        for (int i = 0; i < 36; i++) {
190
            ItemStack stack = player.getInventory().getItem(i);
191
            if (!FoodUtil.isFood(stack)) continue;
192
            if (!isFoodAllowed(stack)) continue;
193
            if (exact && !emergency && FoodUtil.getNutrition(stack) > missing) continue;
194
            if (emergency && missing <= 0 && !FoodUtil.canAlwaysEat(stack)) continue;
195
196
            float score = FoodUtil.scoreFood(stack);
197
            if (score > bestScore) {
198
                bestScore = score;
199
                bestSlot = i;
200
            }
201
        }
202
203
        return bestSlot;
204
    }
205
206
    private int findBestFoodSlotPreferInventory(LocalPlayer player, int missing, boolean exact, boolean emergency) {
207
        int bestSlot = -1;
208
        float bestScore = Float.NEGATIVE_INFINITY;
209
210
        for (int i = 9; i < 36; i++) {
211
            ItemStack stack = player.getInventory().getItem(i);
212
            if (!FoodUtil.isFood(stack)) continue;
213
            if (!isFoodAllowed(stack)) continue;
214
            if (exact && !emergency && FoodUtil.getNutrition(stack) > missing) continue;
215
            if (emergency && missing <= 0 && !FoodUtil.canAlwaysEat(stack)) continue;
216
            float score = FoodUtil.scoreFood(stack);
217
            if (score > bestScore) {
218
                bestScore = score;
219
                bestSlot = i;
220
            }
221
        }
222
223
        if (bestSlot != -1) return bestSlot;
224
        return findBestFoodSlot(player, missing, exact, emergency);
225
    }
226
227
    private boolean ensureFoodInMainhand(LocalPlayer player, int bestSlot, float bestScore) {
228
        PlayerInventoryAccessor inv = (PlayerInventoryAccessor) player.getInventory();
229
230
        if (restoreMainPending) {
231
            inv.combatant$setSelectedSlot(restoreHotbarSlot);
232
            return true;
233
        }
234
235
        ItemStack main = player.getMainHandItem();
236
        float mainScore = FoodUtil.scoreFood(main);
237
        if (FoodUtil.isFood(main) && mainScore >= bestScore) return true;
238
239
        if (bestSlot < 0) return false;
240
241
        if (bestSlot < 9) {
242
            int selected = inv.combatant$getSelectedSlot();
243
            if (selected != bestSlot) {
244
                prevSelectedSlot = selected;
245
                restoreSelected = true;
246
                inv.combatant$setSelectedSlot(bestSlot);
247
            }
248
            return true;
249
        }
250
251
        int targetHotbar = findEmptyHotbarSlot(player);
252
        int selected = inv.combatant$getSelectedSlot();
253
        if (targetHotbar == -1) targetHotbar = selected;
254
255
        if (targetHotbar != selected) {
256
            prevSelectedSlot = selected;
257
            restoreSelected = true;
258
        }
259
        inv.combatant$setSelectedSlot(targetHotbar);
260
261
        if (player.inventoryMenu == null) return false;
262
263
        restoreInvSlot = bestSlot;
264
        restoreHotbarSlot = targetHotbar;
265
        restoreMainPending = true;
266
267
        InventorySwap.INSTANCE.swapScreenSlots(InventorySwap.mapInventoryToScreenSlot(bestSlot), InventorySwap.mapHotbarToScreenSlot(targetHotbar));
268
        return true;
269
    }
270
271
    private boolean ensureFoodInOffhand(LocalPlayer player, int bestSlot, float bestScore) {
272
        if (restoreOffhandPending) return true;
273
274
        ItemStack off = player.getOffhandItem();
275
        float offScore = FoodUtil.scoreFood(off);
276
        if (FoodUtil.isFood(off) && offScore >= bestScore) return true;
277
278
        if (bestSlot < 0) return false;
279
        if (player.inventoryMenu == null) return false;
280
281
        restoreOffhandSlot = bestSlot;
282
        restoreOffhandPending = true;
283
284
        InventorySwap.INSTANCE.swapInventoryToOffhand(bestSlot);
285
        return true;
286
    }
287
288
    private int findEmptyHotbarSlot(LocalPlayer player) {
289
        for (int i = 0; i < 9; i++) {
290
            if (player.getInventory().getItem(i).isEmpty()) return i;
291
        }
292
        return -1;
293
    }
294
295
    private boolean isFoodAllowed(ItemStack stack) {
296
        if (stack == null || stack.isEmpty()) return false;
297
        Identifier id = BuiltInRegistries.ITEM.getKey(stack.getItem());
298
        if (id == null) return true;
299
        String key = id.getPath();
300
        if (!avoidFoods.getAll().containsKey(key)) return true;
301
        return !avoidFoods.get(key);
302
    }
303
304
    private void startUse(LocalPlayer player, InteractionHand hand) {
305
        if (!forcingUse) {
306
            useKeyWasPressed = mc.options.keyUse.isDown();
307
        }
308
309
        if (!mc.options.keyUse.isDown()) {
310
            mc.options.keyUse.setDown(true);
311
        }
312
        forcingUse = true;
313
314
        ItemStack used = hand == InteractionHand.OFF_HAND
315
                ? player.getOffhandItem().copy()
316
                : player.getMainHandItem().copy();
317
        InteractionResult r = mc.gameMode.useItem(player, hand);
318
        if (r.consumesAction()) {
319
            player.swing(hand);
320
            Itemizer.showAutoEat(used);
321
        }
322
    }
323
324
    private void stopAutoUse(LocalPlayer player) {
325
        if (forcingUse && !useKeyWasPressed) {
326
            mc.options.keyUse.setDown(false);
327
        }
328
        forcingUse = false;
329
330
        if (restoreMainPending) {
331
            restoreMainPending = false;
332
            restoreMainSwap(player);
333
        }
334
335
        if (restoreOffhandPending) {
336
            restoreOffhandPending = false;
337
            restoreOffhandSwap(player);
338
        }
339
340
        if (restoreSelected) {
341
            restoreSelected = false;
342
            if (prevSelectedSlot >= 0) {
343
                ((PlayerInventoryAccessor) player.getInventory()).combatant$setSelectedSlot(prevSelectedSlot);
344
            }
345
            prevSelectedSlot = -1;
346
        }
347
    }
348
349
    private void restoreMainSwap(LocalPlayer player) {
350
        if (restoreInvSlot < 0 || restoreHotbarSlot < 0) return;
351
        if (player.inventoryMenu == null) return;
352
353
        InventorySwap.INSTANCE.swapScreenSlots(InventorySwap.mapInventoryToScreenSlot(restoreInvSlot), InventorySwap.mapHotbarToScreenSlot(restoreHotbarSlot));
354
355
        restoreInvSlot = -1;
356
        restoreHotbarSlot = -1;
357
    }
358
359
    private void restoreOffhandSwap(LocalPlayer player) {
360
        if (restoreOffhandSlot < 0) return;
361
        if (player.inventoryMenu == null) return;
362
363
        InventorySwap.INSTANCE.swapInventoryToOffhand(restoreOffhandSlot);
364
        restoreOffhandSlot = -1;
365
    }
366
367
    @Getter
368
    @RequiredArgsConstructor
369
    private enum EatMode implements EnumValue.IdProvider {
370
        INSTANT("INSTANT"),
371
        EXACT("EXACT");
372
373
        private final String id;
374
    }
375
376
    @Getter
377
    @RequiredArgsConstructor
378
    private enum HandMode implements EnumValue.IdProvider {
379
        MAINHAND("MAINHAND"),
380
        OFFHAND("OFFHAND");
381
382
        private final String id;
383
    }
384
}
385
NicotinePlayersrc/client/java/nicotine/mod/mods/player/AutoEat.javaJava · 79 lines · 2.1 KB
SettingsHunger
AutoEat.javaJava · Minecraft 26.3 · 79 lines · 2.1 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.player;
2
3
import net.minecraft.core.component.DataComponents;
4
import net.minecraft.world.food.FoodProperties;
5
import net.minecraft.world.item.Item;
6
import nicotine.events.ClientLevelTickEvent;
7
import nicotine.mod.Mod;
8
import nicotine.mod.ModCategory;
9
import nicotine.mod.option.SliderOption;
10
import nicotine.util.EventBus;
11
import nicotine.util.Inventory;
12
13
import static nicotine.util.Common.mc;
14
15
public class AutoEat extends Mod {
16
    private boolean eating = false;
17
18
    private final SliderOption hunger = new SliderOption(
19
            "Hunger",
20
            15,
21
            0,
22
            19
23
    );
24
25
    public AutoEat() {
26
        super(ModCategory.Player, "AutoEat");
27
        this.addOptions(hunger);
28
    }
29
30
    @Override
31
    protected void init() {
32
        EventBus.register(ClientLevelTickEvent.class, event -> {
33
            if (!this.enabled)
34
                return true;
35
36
            if (eating && !mc.player.isUsingItem()) {
37
                mc.options.keyUse.setDown(false);
38
                eating = false;
39
            }
40
41
            if (mc.player.getFoodData().getFoodLevel() > hunger.value)
42
                return true;
43
44
            int slot = -1;
45
            FoodProperties bestFoodComponent = null;
46
47
            for (int i = 0; i < 9; i++) {
48
                Item item = mc.player.getInventory().getItem(i).getItem();
49
                FoodProperties foodComponent = item.components().getOrDefault(DataComponents.FOOD, null);
50
51
                if (foodComponent == null)
52
                    continue;
53
54
                if (bestFoodComponent == null) {
55
                    bestFoodComponent = foodComponent;
56
                    slot = i;
57
                    continue;
58
                }
59
60
                if (foodComponent.saturation() > bestFoodComponent.saturation()) {
61
                    bestFoodComponent = foodComponent;
62
                    slot = i;
63
                }
64
            }
65
66
            if (slot == -1)
67
                return true;
68
69
70
            Inventory.selectSlot(slot);
71
            mc.options.keyUse.setDown(true);
72
            eating = true;
73
74
            return true;
75
        });
76
77
    }
78
}
79