Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I split teams evenly?

Asked by 10 years ago

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

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. GoldenPhysics 474 — 10y

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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
Ad

Answer this question