How to team player with the first player they see?

I am making a 1.14 minecraft minigame, and one aspect is when two players not on a team walk up to each other, they are put on the same team. I am wondering how to do this.I have included all 16 team colo(u)rs, and the team names are:

dark_red, green, dark_green, yellow, black, dark_blue, dark_purple, gold, red, aqua, gray, light_purple, blue, white, dark_aqua, dark_gray


Solution 1:

To team players who are within five blocks of one another who don't currently have a team:

In a repeating command block:

execute as @a[team=] at @s if @a[team=,distance=1..5,limit=1] run execute as @a[distance=..5,limit=2] run team join <team name> @s

What this does is it executes as a player who has no team at that player if there is a single player within 1 to 5 blocks away who also doesn't have a team. It runs another execute function which executes as both players joining them both to a team. If you want to randomize which team they join try something like this:

Setup a scoreboard to track the current time: /scoreboard objectives add time dummy

In a repeating command block set the scoreboard to the current time: execute store result score @a time run time query daytime

In a number of similar repeating command blocks set a particular team depending on the current time: in this example green is for 1000 to 2000:

execute as @a[team=] at @s if @a[team=,distance=1..5,limit=1] run execute as @a[distance=..5,limit=2] if score @s time matches 1000..2000 run team join green @s

You'd need a different command block for each team and time.