What would be a good way to balance teams

Hey, so I have a problem, kinda.
Im currently working an a shooter for fun, and recently added teams.
Now, my problem is that I dont know exactly how to “randomize” them.

What i mean, is that both teams have aproximately the same amount of players, a server of 3 people would have 2 people on one team, and 1 on the other, however i dont want the teams to be the same through rounds.

If i just use a for i, v in pairs() loop to get the players, it will result in the exact same teams until a player joins or leaves.

I have a working system at the moment, but I want to know if there is a better way I can do this.
Here is my code:

local Teams = {
	game.Teams.Red;
	game.Teams.Blue;
}

.
.
.

-- Select one of the two teams here
local Team = Teams[math.random(1, #Teams)]

-- Start going through the players and swapping the team after each player
for i, v in pairs(game.Players:GetPlayers()) do
	v.Team = Team
	if Team == game.Teams.Red then Team = game.Teams.Blue else Team = game.Teams.Red end
end

Thanks for your help.

1 Like

(Wrote the randomise table function for another post, hence why Im using it here. You can modify it if you like)


You could put all the players into a table, then randomise the table. Looping through this

function RandomiseTable(TempTable)
    local ResultTable = {}

    while #TempTable > 0 do
        local RandomValue = math.random(#TempTable)
        table.insert(ResultTable, TempTable[RandomValue])
        table.remove(TempTable,  RandomValue)
    end
    return ResultTable
end

local RandomisedPlayers = RandomiseTable(game.Players:GetPlayers())
for index, Player in ipairs(RandomisedPlayers) do
    if index % 2 == 0 then
        Player.Team = game.Teams.Red
    else
        Player.Team = game.Teams.Blue
    end
end

-- The above code should work sufficiently. If you want to shorten the for loop
-- to make it take up less lines, this code here does this same thing.
-- It uses tertiary operations to compress the if statement.

for index, Player in ipairs(RandomisedPlayers) do
    Player.Team = game.Teams[index % 2 == 0 and "Red" or "Blue"]
end

1 Like

You just need to check how many people are in a team and if the other team has less than the other team disable joining the team that has more players.

This will see what team has less and add a player to that team

local Teams = {
	game.Teams.Red;
	game.Teams.Blue;
}

function AddPlayerToTeam(Player)
	local TeamToJoin = Teams[1]  -- default to first team
	for i, team in ipairs(Teams) do  -- check all teams see which has less players
		if #team:GetPlayers() < #TeamToJoin:GetPlayers() then
			TeamToJoin = team  -- set to the new team with less players
		end
	end
	Player.Team = TeamToJoin
end

game.Players.PlayerAdded:Connect(function(Player)
	AddPlayerToTeam(Player)
end)

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