AutoShop module

AutoShop: Minecraft 26.3 cheat module, full source for every implementation (1 client: LiquidBounce (Kotlin)).

1 implementationPLAYER

Clients with this module

Full module source: 1 implementation

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

LiquidBounce (Kotlin)PLAYERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/player/autoshop/ModuleAutoShop.ktKotlin · 485 lines · 18.5 KB

Automatically buys specific items in a BedWars shop.

SettingsConfigStartDelayExtraCategorySwitchDelayAutoClose
ModuleAutoShop.ktKotlin · Minecraft 26.2 · 485 lines · 18.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.player.autoshop
20
21
import it.unimi.dsi.fastutil.ints.IntArrayList
22
import it.unimi.dsi.fastutil.ints.IntList
23
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap
24
import it.unimi.dsi.fastutil.objects.Object2IntMap
25
import it.unimi.dsi.fastutil.objects.Object2IntMaps
26
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
27
import kotlinx.coroutines.Dispatchers
28
import kotlinx.coroutines.delay
29
import net.ccbluex.fastutil.fastIterator
30
import net.ccbluex.fastutil.forEachInt
31
import net.ccbluex.fastutil.intListOf
32
import net.ccbluex.liquidbounce.event.tickConditional
33
import net.ccbluex.liquidbounce.event.tickHandler
34
import net.ccbluex.liquidbounce.event.tickUntil
35
import net.ccbluex.liquidbounce.features.module.ClientModule
36
import net.ccbluex.liquidbounce.features.module.ModuleCategories
37
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.AutoShopConfig.loadAutoShopConfig
38
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.purchasemode.NormalPurchaseMode
39
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.purchasemode.QuickPurchaseMode
40
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.serializable.ItemInfo
41
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.serializable.ShopConfig
42
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.serializable.ShopElement
43
import net.ccbluex.liquidbounce.features.module.modules.player.autoshop.serializable.conditions.ConditionCalculator
44
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug
45
import net.ccbluex.liquidbounce.utils.client.chat
46
import net.ccbluex.liquidbounce.utils.text.stripMinecraftColorCodes
47
import net.ccbluex.liquidbounce.utils.kotlin.Minecraft
48
import net.ccbluex.liquidbounce.utils.kotlin.subList
49
import net.minecraft.client.gui.screens.inventory.ContainerScreen
50
import net.minecraft.world.inventory.ContainerInput
51
import kotlin.math.ceil
52
import kotlin.math.min
53
import kotlin.time.Duration.Companion.milliseconds
54
55
/**
56
 * AutoShop module
57
 *
58
 * Automatically buys specific items in a BedWars shop.
59
 */
60
@Suppress("TooManyFunctions")
61
object ModuleAutoShop : ClientModule("AutoShop", ModuleCategories.PLAYER) {
62
63
    private val shopConfig by enumChoice("Config", ShopConfigPreset.PIKA_NETWORK).onChanged {
64
        loadAutoShopConfig(it)
65
    }
66
67
    private val startDelay by intRange("StartDelay", 1..2, 0..10, "ticks")
68
    val purchaseMode = modes(this, "PurchaseMode", NormalPurchaseMode,
69
        arrayOf(NormalPurchaseMode, QuickPurchaseMode)
70
    )
71
72
    private val extraCategorySwitchDelay by intRange("ExtraCategorySwitchDelay", 3..4,
73
        0..10, "ticks")
74
    private val autoClose by boolean("AutoClose", true)
75
76
    private var waitedBeforeTheFirstClick = false
77
    private var canAutoClose = false    // allows closing the shop menu only after a purchase
78
    private var prevCategorySlot = -1
79
    var currentConfig = ShopConfig.Empty
80
81
    // Debug
82
    private val recordedClicks = IntArrayList()
83
    private var startMilliseconds = 0L
84
85
    init {
86
        // Update [currentConfig] on module initialization
87
        loadAutoShopConfig(shopConfig)
88
    }
89
90
    @Suppress("unused")
91
    private val repeatable = tickHandler(Dispatchers.Minecraft) {
92
        if (!isShopOpen()) {
93
            return@tickHandler
94
        }
95
96
        if (ModuleDebug.running) {
97
            startMilliseconds = System.currentTimeMillis()
98
        }
99
100
        // wait after opening a shop (before the first click)
101
        if (!waitedBeforeTheFirstClick) {
102
            tickConditional(startDelay.random()) { !isShopOpen() }
103
            waitedBeforeTheFirstClick = true
104
        }
105
106
        if (!isShopOpen()) {
107
            reset()
108
            return@tickHandler
109
        }
110
111
        for (index in currentConfig.elements.indices) {
112
            val element = currentConfig.elements[index]
113
            val remainingElements = currentConfig.elements.subList(index)
114
            var needToBuy = checkElement(element, remainingElements) != null
115
            // buy an item
116
            while (needToBuy) {
117
                canAutoClose = true
118
                doClicks(currentConfig.elements.subList(index))
119
120
                // check if it's capable of clicking
121
                if (!isShopOpen()) {
122
                    reset()
123
                    return@tickHandler
124
                }
125
                needToBuy = checkElement(element, remainingElements) != null
126
            }
127
        }
128
129
        // close the shop after buying items
130
        if (waitedBeforeTheFirstClick && autoClose && canAutoClose) {
131
            player.closeContainer()
132
        }
133
        reset()
134
    }
135
136
    private suspend fun doClicks(remainingElements: List<ShopElement>) {
137
        val currentElement = remainingElements.first()
138
        val categorySlot = currentElement.categorySlot
139
        val itemSlot = currentElement.itemSlot
140
141
        // switches an item category to be able to buy an item
142
        switchCategory(categorySlot)
143
144
        // checks if it's capable of clicking
145
        // as a shop might get closed during switching the category
146
        if (!isShopOpen()) {
147
            return
148
        }
149
150
        // buys an item (1 click only)
151
        if (purchaseMode.activeMode == NormalPurchaseMode) {
152
            buyItem(itemSlot, currentElement)
153
            return
154
        }
155
156
        // buys all items in a category and switch to the next one
157
        buyAllItemsInCategory(remainingElements)
158
    }
159
160
    private suspend fun switchCategory(nextCategorySlot: Int) {
161
        // we don't need to open, for example, "Blocks" category again if it's already open
162
        if (prevCategorySlot == nextCategorySlot) {
163
            return
164
        }
165
166
        val prevShopStacks = (mc.gui.screen() as ContainerScreen).stacks()
167
        interaction.handleContainerInput(
168
            (mc.gui.screen() as ContainerScreen).menu.containerId,
169
            nextCategorySlot,
170
            0,
171
            NormalPurchaseMode.action.input,
172
            mc.player!!
173
        )
174
175
        if (ModuleDebug.running) {
176
            recordedClicks.add(nextCategorySlot)
177
        }
178
179
        prevCategorySlot = nextCategorySlot
180
        tickUntil { !isShopOpen() || hasItemCategoryChanged(prevShopStacks) }
181
        tickConditional(extraCategorySwitchDelay.random()) { !isShopOpen() }
182
    }
183
184
    private suspend fun buyItem(itemSlot: Int, shopElement: ShopElement) {
185
        val currentInventory = AutoShopInventoryManager.getInventoryItems()
186
187
        interaction.handleContainerInput(
188
            (mc.gui.screen() as ContainerScreen).menu.containerId,
189
            itemSlot,
190
            0,
191
            NormalPurchaseMode.action.input,
192
            mc.player!!
193
        )
194
195
        if (ModuleDebug.running) {
196
            recordedClicks.add(itemSlot)
197
        }
198
199
        // waits to receive items from a server after clicking before performing the next click
200
        tickUntil {
201
            !isShopOpen() || hasReceivedItems(
202
                prevInventory = currentInventory,
203
                expectedItems = Object2IntArrayMap(
204
                    arrayOf(shopElement.item.id, shopElement.price.id),
205
                    intArrayOf(shopElement.amountPerClick, -shopElement.price.minAmount),
206
                )
207
            )
208
        }
209
210
        // expects to get an item later
211
        if (shopElement.item.id.isArmorItem()) {
212
            AutoShopInventoryManager.addPendingItems(
213
                Object2IntMaps.singleton(shopElement.item.id, shopElement.amountPerClick)
214
            )
215
        }
216
217
        // waits extra ticks
218
        tickConditional(NormalPurchaseMode.extraDelay.random()) { !isShopOpen() }
219
    }
220
221
    private suspend fun buyAllItemsInCategory(remainingElements: List<ShopElement>) {
222
        val simulationResult = simulateNextPurchases(remainingElements, onlySameCategory = true)
223
        val slotsToClick = simulationResult.slots
224
        val prevInventory = AutoShopInventoryManager.getInventoryItems()
225
        val prevShopStacks = (mc.gui.screen() as ContainerScreen).stacks()
226
227
        slotsToClick.forEachInt { slot ->
228
            if (slot == -1) {
229
                return@forEachInt // it looks as if it doesn't require to switch an item category anymore
230
            }
231
232
            delay(QuickPurchaseMode.delayMs.random().milliseconds)
233
234
            interaction.handleContainerInput(
235
                (mc.gui.screen() as ContainerScreen).menu.containerId,
236
                slot,
237
                0,
238
                ContainerInput.PICKUP,
239
                mc.player!!
240
            )
241
242
            if (ModuleDebug.running) {
243
                recordedClicks.add(slot)
244
            }
245
        }
246
247
        val nextCategorySlot = slotsToClick.getInt(slotsToClick.lastIndex)
248
        if (nextCategorySlot != -1) {
249
            prevCategorySlot = nextCategorySlot
250
        }
251
252
        // expects to get items later
253
        val newPendingItems = if (QuickPurchaseMode.waitForItems) {
254
            val map = Object2IntOpenHashMap<String>()
255
            simulationResult.expectedItems.fastIterator().forEach {
256
                if (it.key.isArmorItem()) map.put(it.key, it.intValue)
257
            }
258
            map
259
        } else {
260
            simulationResult.expectedItems
261
        }
262
        AutoShopInventoryManager.addPendingItems(newPendingItems)
263
264
        // waits for an inventory update and for an item category update
265
        tickUntil {
266
            !isShopOpen() || (hasReceivedItems(prevInventory, simulationResult.expectedItems)
267
                && (nextCategorySlot == -1 || hasItemCategoryChanged(prevShopStacks)))
268
        }
269
270
        // waits extra ticks
271
        tickConditional(extraCategorySwitchDelay.random()) { !isShopOpen() }
272
    }
273
274
    private fun hasItemCategoryChanged(prevShopStacks: List<String>): Boolean {
275
        val currentShopStacks = (mc.gui.screen() as ContainerScreen).stacks()
276
277
        val difference = (currentShopStacks - prevShopStacks)
278
            .union(prevShopStacks - currentShopStacks)
279
280
        return difference.size > 1
281
    }
282
283
    /**
284
     * Checks if the player has received [expectedItems].
285
     *
286
     * If [expectedItems] contain only armor which can be received only after the shop is closed,
287
     * it will check whether the items required to buy it are taken.
288
     **/
289
    private fun hasReceivedItems(
290
        prevInventory: Object2IntMap<String>,
291
        expectedItems: Object2IntMap<String>,
292
    ): Boolean {
293
        val exceptedItemsToGet = expectedItems.filter { it.value > 0 }
294
        val exceptedItemsToLose = expectedItems.filter { it.value < 0 }
295
        val isArmorOnly = exceptedItemsToGet.all { it.key.isArmorItem() }
296
297
        val currentInventory = AutoShopInventoryManager.getInventoryItems()
298
        val receivedNewItems = exceptedItemsToGet.all { (item, expectedNewAmount) ->
299
            val prevItemAmount = prevInventory.getOrDefault(item, 0)
300
            val newItemAmount = currentInventory.getOrDefault(item, 0)
301
302
            newItemAmount - prevItemAmount >= expectedNewAmount
303
        }
304
305
        val lostPriceItems = isArmorOnly && exceptedItemsToLose.all { (item, expectedNewAmount) ->
306
            val prevItemAmount = prevInventory.getOrDefault(item, 0)
307
            val newItemAmount = currentInventory.getOrDefault(item, 0)
308
309
            newItemAmount - prevItemAmount <= expectedNewAmount
310
        }
311
312
        return receivedNewItems || lostPriceItems
313
    }
314
315
    /**
316
     * Returns items expected to get and a list of clickable slots
317
     * within the same category as the current element.
318
     * The last item in this list is a slot pointing to the next category
319
     * (if a category switch is unnecessary, it will be -1).
320
     *
321
     * The function determines what items can be bought,
322
     * based on the player's resources and the purchase order specified in the configuration.
323
     */
324
    private fun simulateNextPurchases(
325
        remainingElements: List<ShopElement>,
326
        onlySameCategory: Boolean,
327
    ): PurchaseSimulationResult {
328
329
        if (remainingElements.isEmpty()) {
330
            return PurchaseSimulationResult(intListOf(), Object2IntMaps.emptyMap())
331
        }
332
333
        val initialCategorySlot = remainingElements.first().categorySlot
334
        var currentCategorySlot = initialCategorySlot
335
        val currentItems = Object2IntOpenHashMap(AutoShopInventoryManager.getInventoryItems())
336
        val slots = IntArrayList()
337
        val expectedItems = Object2IntOpenHashMap<String>()
338
        var nextCategorySlot = -1
339
340
        @Suppress("LoopWithTooManyJumpStatements")
341
        for (element in remainingElements) {
342
            val requiredItems = checkElement(element, items = currentItems) ?: continue
343
            val clicks = getRequiredClicks(element, currentItems, requiredItems)
344
            if (clicks < 1) {
345
                continue    // we can't buy an item actually
346
            }
347
348
            // subtract the required items from the limited items we have
349
            requiredItems.fastIterator().forEach {
350
                currentItems.addTo(key, -it.intValue * clicks)
351
            }
352
            currentItems.addTo(element.item.id, element.amountPerClick * clicks)
353
354
            if (!onlySameCategory) {
355
                if (element.categorySlot != currentCategorySlot) {
356
                    slots.add(element.categorySlot)
357
                    currentCategorySlot = element.categorySlot
358
                }
359
                repeat(clicks) { slots.add(element.itemSlot) }
360
                expectedItems.addTo(element.item.id, element.amountPerClick * clicks)
361
                expectedItems.addTo(element.price.id, -element.price.minAmount * clicks)
362
                continue
363
            }
364
365
            if (element.categorySlot == initialCategorySlot) {
366
                repeat(clicks) { slots.add(element.itemSlot) }
367
                // for example, [wool: 64, iron_ingot: -16]
368
                expectedItems.addTo(element.item.id, element.amountPerClick * clicks)
369
                expectedItems.addTo(element.price.id, -element.price.minAmount * clicks)
370
                continue
371
            }
372
373
            // update the next category slot if it's empty
374
            if (nextCategorySlot == -1) {
375
                nextCategorySlot = element.categorySlot
376
            }
377
378
        }
379
380
        slots.add(nextCategorySlot)
381
        return PurchaseSimulationResult(slots, expectedItems)
382
    }
383
384
    private data class PurchaseSimulationResult(
385
        val slots: IntList,
386
        val expectedItems: Object2IntMap<String>,
387
    )
388
389
    /**
390
     * Returns the limited items and their amounts required to buy an item
391
     * Returns null if an item can't be bought
392
     */
393
    private fun checkElement(
394
        shopElement: ShopElement,
395
        remainingElements: List<ShopElement>? = null,
396
        items: Object2IntMap<String> = AutoShopInventoryManager.getInventoryItems(),
397
    ): Object2IntMap<String>? {
398
399
        // checks if the player already has the required item to be bought
400
        if (items.getOrDefault(shopElement.item.id, 0) >= shopElement.item.minAmount) {
401
            return null
402
        }
403
404
        // checks the item's price
405
        if (!checkPrice(shopElement.price, items)) {
406
            return null
407
        }
408
409
        // checks if the player is capable of buying a better item so that this item is not actually needed
410
        if (shopElement.item.id.isItemWithTiers() && remainingElements != null) {
411
            val simulationResult = simulateNextPurchases(remainingElements, onlySameCategory = false)
412
            val hasBetterItem = hasBetterTierItem(shopElement.item.id, simulationResult.expectedItems)
413
            if (hasBetterItem) {
414
                return null
415
            }
416
        }
417
418
        // makes sure that other conditions are met
419
        if (!ConditionCalculator(items).process(
420
                shopElement.item.id, shopElement.purchaseConditions)) {
421
            return null
422
        }
423
424
        return Object2IntMaps.singleton(shopElement.price.id, shopElement.price.minAmount)
425
    }
426
427
    /**
428
     * Returns the amount of clicks which can be performed to buy an item
429
     * For example, it might need 4 clicks to buy wool blocks
430
     * but there might be enough resources only for 3 clicks
431
     */
432
    private fun getRequiredClicks(
433
        shopElement: ShopElement,
434
        items: Object2IntMap<String>,
435
        requiredLimitedItems: Object2IntMap<String>,
436
    ): Int {
437
        val currentLimitedItems = Object2IntOpenHashMap<String>()
438
        items.fastIterator().forEach {
439
            if (it.key in LIMITED_ITEMS) currentLimitedItems.put(it.key, it.intValue)
440
        }
441
        val currentItemAmount = min(items.getOrDefault(shopElement.item.id, 0), shopElement.item.minAmount)
442
        val maxBuyClicks = ceil(
443
            1f * (shopElement.item.minAmount - currentItemAmount) / shopElement.amountPerClick).toInt()
444
445
        return requiredLimitedItems.keys.minOf { key ->
446
            val requiredItemsAmount = requiredLimitedItems.getOrDefault(key, 0)
447
            val currentItemsAmount = currentLimitedItems.getOrDefault(key, 0)
448
            min(maxBuyClicks, currentItemsAmount / requiredItemsAmount)
449
        }
450
    }
451
452
    /**
453
     * Checks the whole price block
454
     */
455
    private fun checkPrice(price: ItemInfo, items: Object2IntMap<String>): Boolean {
456
        val requiredItemAmount = items.getOrDefault(price.id, 0)
457
        return requiredItemAmount >= price.minAmount
458
    }
459
460
    private fun isShopOpen(): Boolean {
461
        val screen = mc.gui.screen() as? ContainerScreen ?: return false
462
463
        val title = screen.title.string.stripMinecraftColorCodes()
464
        val isTitleValid = currentConfig.traderTitles.any {
465
            title.contains(it, ignoreCase = true)
466
        }
467
468
        return isTitleValid
469
    }
470
471
    private fun reset() {
472
        if (ModuleDebug.running && startMilliseconds != 0L && canAutoClose) {
473
            chat("[AutoShop] Time elapsed: ${System.currentTimeMillis() - startMilliseconds} ms")
474
            chat("[AutoShop] Clicked on the following slots: $recordedClicks")
475
            recordedClicks.clear()
476
            startMilliseconds = 0L
477
        }
478
479
        AutoShopInventoryManager.clearPendingItems()
480
        prevCategorySlot = currentConfig.initialCategorySlot
481
        waitedBeforeTheFirstClick = false
482
        canAutoClose = false
483
    }
484
}
485