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

How would I split teams evenly?

So I have a script, but instead of splitting the teams evenly, it puts everyone on the same team.

for i, player in pairs(game.Players:GetPlayers()) do
    if rval < dval then
        player.TeamColor = BrickColor.new("Bright red")
        rval = rval + 1 -- you forgot to add the new player to the team value
    elseif rval > dval then
        player.TeamColor=BrickColor.new("Bright blue")
        dval = dval + 1 -- and here too
    else

How would I have this (Or a different script) split the teams evenly?

I know it would have to take each individual player, but Im 95% certain this takes all the players, instead of one at a time

1 comment

0

The for loop iterates to code for each player one at a time, so no problem there. Also, take out the elseif and replace it with else. That way it has somewhere to go in case they were equal.

1 answer

I would recommend a simpler condition, that doesn't involve you keeping track of anything!

local players = game.Players:GetPlayers();
for i, player in pairs(players) do
	if i > #players / 2 then
		player.TeamColor = BrickColor.new("Bright red")
	else
		player.TeamColor = BrickColor.new("Bright blue")
	end
end

Here, we just say the first half of players are Blue, and the second half are Red. We do this based on the index of the player in the list, so it is obvious that we are guaranteed even teams!


Also, most likely you would want to shuffle players before applying this, so that the order is fresh whenever you remake teams. You could do that with this snippet:

for n = #t,2,-1 do
	-- Fisher-Yates fair shuffle algorithm
	-- Adapted from RosettaCode
	local k = math.random(n);
	players[n], players[k] = players[k], players[n];
end

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