TransWikia.com

How to detect whether a player has two of a specific item in their inventory, and drop one?

Arqade Asked on January 8, 2021

We’re building a capture the flag style map in Minecraft, but we do not want people to take multiple flags at once.

To stop that, when a player manages to get two flags at once, we want to drop one out of their inventory. This is easily done by a combination of /clear and /summon.

The hard part is, how do we detect whether someone is holding two of an item?

We’ve tried detecting items with the following command:

/execute as @a if entity @s[nbt={Inventory:[{id:"minecraft:chest", Count:2b}]}]

This has the fatal flaw though in that it doesn’t detect two stacks of one item. This is an issue because by putting an item temporarily under their cursor, players can deliberately prevent items from stacking.

How do we detect whether a player has two or more of the same item in their inventory using command blocks?

One Answer

Here's a unique thing about /clear. Remember how you can specify a maximum item count of items to remove? For example...

clear @p stone 3

will remove up to 3 stone, even if you have more than 3 stone.

But there's another value that you can use: 0. From the Minecraft Wiki:

Must be a 32-bit integer number. In Java Edition, it must be between 0 and 2147483647 (inclusive). In Bedrock Edition, it must be between -1 and 2147483647 (inclusive). Specifies the maximum number of items to be cleared. If not specified, or if -1‌[Bedrock Edition only], all items that match item, or itemName: Item and data: int are cleared. If 0, instead of clearing of items, detects and queries the amount of specified items.

Note the statement in bold. This means that if you run /clear @s stone 0, it will detect and return the number of stone in your inventory!

Once you know that, a simple /execute store will do the trick.

execute as @a store result score @s flagsInHand run clear @s chest 0
execute as @a if score @s flagsInHand matches 2.. run clear @s chest 1

If you run these commands in a repeating command block, when you have 2 or more chests, the script will repeatedly clear them until you only have 1.

Further commands will allow you to summon another flag nearby when one is cleared.

Correct answer by ExpertCoder14 on January 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP