How to calculate the area of a region of any shape (Minecraft Java Edition 1.18)
-
There is an armorstand on one of the red regions. How to count blocks that are including to the region the armorstand stands on? The result has to be stored to a scoreboard. Red regions can have any shape and size, and also have some number of holes.
The illustration of it is below:
-
My idea is to use a flood fill algorithm
Before we start the loop, we do
Spawn a temporary armor stand (called "filled") on the start tile (if the starting point is allowed to be outside the red region, you need to add an
if
to the execute commandexecute as @e[tag=,type=minecraft:armor_stand] at @s run summon minecraft:armor_stand ~ ~ ~ {Tags:[filled]}
Start an loop executing every tick
setblock ~ ~ ~1 minecraft:redstone_block
Reset scoreboard to 0
/scoreboard players set count region 0
In the loop, do:
- For each cardinal direction, try to spawn a new armor stand, if the location is not occupied and the new location is above a red wool block
execute as @e[tag=filled,type=minecraft:armor_stand] at @s positioned ~-1 ~ ~ unless entity @e[type=minecraft:armor_stand,tag=filled,distance=...9] if block ~ ~-1 ~ minecraft:red_wool run summon minecraft:armor_stand ~ ~ ~ {Tags:[filled]} execute as @e[tag=filled,type=minecraft:armor_stand] at @s positioned ~1 ~ ~ unless entity @e[type=minecraft:armor_stand,tag=filled,distance=...9] if block ~ ~-1 ~ minecraft:red_wool run summon minecraft:armor_stand ~ ~ ~ {Tags:[filled]} execute as @e[tag=filled,type=minecraft:armor_stand] at @s positioned ~ ~ ~1 unless entity @e[type=minecraft:armor_stand,tag=filled,distance=...9] if block ~ ~-1 ~ minecraft:red_wool run summon minecraft:armor_stand ~ ~ ~ {Tags:[filled]} execute as @e[tag=filled,type=minecraft:armor_stand] at @s positioned ~ ~ ~-1 unless entity @e[type=minecraft:armor_stand,tag=filled,distance=...9] if block ~ ~-1 ~ minecraft:red_wool run summon minecraft:armor_stand ~ ~ ~ {Tags:[filled]}
- Use comparators to monitor the spawning process, if no armorstands are spawned, we have filled the area
After the loop, we need to cleanup:
- Update the scoreboard
execute as @e[type=minecraft:armor_stand,tag=filled] run scoreboard players add count region 1
- Cleanup the progress armorstands
execute as @e[type=minecraft:armor_stand,tag=filled] run kill @s
- Stop the repeating clock
setblock ~ ~ ~-11 air
World download: https://files.ferrybig.me/s/HCd9mgKSB9jPSPJt (though the descriptions in the answer should be good enough to recreate this)