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

[Repost]How can I randomly and evenly assign teams?

I want to make players get randomly assigned to teams. I have one script for this, but its not really that good. Is there a better way to do this? Here is my script:

local assign = 1
for i,v in pairs(game.Players:GetChildren()) do
	if assign = 1 then
		assign = 2 
		v.Team.BrickColor = BrickColor.new("Black")
	else
		assign = 1
		v.Team.BrickColor = BrickColor.new("White")
	end
end

1 answer

Different ways to do this and even more possibilities you could extend to. The problem with the code you're using is that it can be reduced with using something like math.random.

Although, since you want to randomize players for two teams we could do something special with the % or modulus operator.

We first need to get the amount players in the server. Then to get half the amount we divide it by 2. We could use % to make sure it's even by looking at the remainder. If it's not even then that means the player count isn't evened out and we address it accordingly.

local Players = game:GetService("Players")

local playerArray = Players:GetPlayers() --Use this instead of GetChildren
local playerCount = #playerArray --Would get us the number of players

local halfCount

if #playerCount%2 ~= 0 then
	halfCount = (playerCount+1)/2 --Odd player count? Add one then divide.
else
	halfCount = playerCount/2 --Even? Continue on after dividing
end

The above checks if the remainder of playerCount divided by 2 is 0. If it isn't then it means it's an odd amount of players. We add one to the count if that is the case. This means that one team will always have more than one player.

Now we could move on to setting up the teams. I will use tables as teams to organize the players.

local teamOne = Players:GetPlayers()
local teamTwo = {}

local playerCount = #teamOne
local halfCount
if playerCount%2 ~= 0 then
	halfCount = (playerCount+1)/2
else
	halfCount = playerCount/2
end
	
for i = 1, halfCount do
	local rdm = math.random(1, playerCount)
	local chosenPlayer = teamOne[rdm]
		
	table.insert(teamTwo, chosenPlayer)
	table.remove(teamOne, rdm)
end

In our numerical for-loop we count up to the half amount of players. We get a random player using math.random and insert them to the table. We then use table.remove to remove them from the other team table.


This system is pretty straightforward to understand and should be used when starting a new round. After this you would loop through each team table and change the player's team to the respective team in Teams service.

####Let me know if I missed anything or you want something explained more.

Edit: Extended explanation some.

1 comment

0

+rep is very fancy man

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