How to Completely Randomize Teams?

Hello, Recently while working on my project, I ran into a problem regarding the team distributing system. how it works is it runs a “for” loop through the players in the game and also checks which team has less players. whichever team has less players gets the next person lined up in the loop unless both teams have a even amount of players in which a random team will get that player. The issue is, its not random. when testing on a local server with 6 players, its always players 1,3, and 5 vs 2,4, and 6. the only difference being the team the trios are on. (red or blue). I’m not exactly sure how to make it completely random and not just the same people going up against each other. if anyone knows anything that may help regarding this topic, it would be greatly appreciated.

function TeamDistributor() -- the job of this script is to make sure that the teams are completely randomized and even.
	for _, Player in pairs(game.Players:GetChildren()) do
		wait(.2)
		if #Red:GetPlayers() > #Blue:GetPlayers() then
			NexusGearHandler.MaverickGear(Player)
			Player.Team = Blue
			
		elseif #Blue:GetPlayers() > #Red:GetPlayers() then
			NexusGearHandler.SentinalsGear(Player)
			Player.Team = Red
		else
			
			local Num = math.random(1,2)
			if Num == 1 then
				NexusGearHandler.MaverickGear(Player)
				Player.Team = Blue
			else
				NexusGearHandler.SentinalsGear(Player)
				Player.Team = Red
			end
		end
	end
end

ignore the “nexus gear handler”, it just gives the player a armor set color depending on their team.

You can use a basic shuffle function to mix up the list and then assign teams.

local function Shuffle(t)
    for i = #t, 2, -1 do
        local j = math.random(i)
        t[i], t[j] = t[j], t[i]
    end
end

function TeamDistributor()
    local remainder = math.random(0, 1) -- pick random remainder so no team always gets advantage when odd
    local players = game.Players:GetChildren()
    Shuffle(players)

    for i, Player in ipairs(players) do
        if i % 2 == remainder then
            -- is blue
        else
            -- is red
        end
    end
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.