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?
Best Answer
Here's a unique thing about
/clear
. Remember how you can specify a maximum item count of items to remove? For example...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:
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.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.