How can I make players share damage using command blocks?

Solution 1:

You should use a dummy variable and target selector arguments.

Run once

Have a dummy score, call it healthDif.

/scoreboard objectives add healthDif dummy

Run every tick, in order

Set each players healthDif score to their own health score:

/execute @a ~ ~ ~ scoreboard players operation @a[c=1] healthDif = @a[c=1] health

Subtract the other player's healthDif score from your own:

/execute @a ~ ~ ~ scoreboard players operation @a[c=1] healthDif -= @a[rm=0] health

Now players with a positive healthDif score will have more health than the other player. Target with @a[score_healthDif=1]
Note this will only work for two players. In order for it to work with more, you have to take a few extra steps.


Run once

First you'll need a dummy variable to store miscellaneous variables. Call it vars. Note: If you already have a variable for this (you likely do), you can skip this step.

/scoreboard objectives add vars dummy

Run every tick, in order

Put these between the two commands from before.

First, set the #nplayers to 0:

/scoreboard players set #nplayers vars -1

Now, have each player increment #nplayers:

/execute @a ~ ~ ~ scoreboard players add #nplayers vars 1

Finally, multiply each players healthDif score by this number

/scoreboard players operation @a healthDif *= #nplayers vars

This way, you can have any amount of players, and the system automatically adapts!