Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to divide players for a Minigame?

Hi all, I am trying to make a script that will divide the players in the game into teams.

Here is what I have found but can't seem to wrap my head around.

local Team1 = game.Teams["Attackers"]
local Team2 = game.Teams["Defenders"]
local players = game.Players:GetChildren()
local numberp = game.Players.NumPlayers
for i = 1,numberp do 
local x = math.random(numberp)
wait()
end 

for _,p in pairs(players) do 
p.TeamColor = Team2.TeamColor 
end 

for a = 1,#players/2 do 
players[a].TeamColor = Team1.TeamColor
end 
wait(2)
m:Destroy()
end

Thanks, Antux

1 answer

The code you have provided has a lot of useless waiting and looping. It also doesn't successfully randomize. Lets try to make our own that will perform much better than this.

We have to solve this problem: Randomly divide all players evenly onto two teams.

The hard part of this problem is choosing random players. There exists an algorithm that uses probability to determine if a number should be selected. For each player, the probability of being selected is (number of players needed)/(number of players left). So if there were 20 players, the first players chances of getting selected is 10/20. If it is selected the next probability is 9/19, otherwise it is 10/19. By the end you will have exactly half of the players being selected.

That may have been confusing, but hopefully the code makes it easier to follow. All that is left to do is loop through the players and set the team to either "Team1" or "Team2":

local Team1 = game.Teams["Attackers"]
local Team2 = game.Teams["Defenders"]
local players = game.Players:GetPlayers()

local numNeeded = math.floor(#players/2) -- floor so we don't have a decimal 
local numLeft = #players

for _, player in ipairs(players) do
	local probability = numNeeded/numLeft
	if probability < math.random() then
		player.TeamColor = Team1
		numNeeded = numNeeded - 1
	else
		player.TeamColor = Team2
	end
	numLeft = numLeft - 1
end

If you have any questions, just leave a comment below.

This discussion is preserved as it was. New answers, comments, and votes are closed.