I have a simple method that evenly splits players into 2 teams, but it teams the same players together every round. Is there a way to re script this and make it more random?
(c is the player, and this current code uses a for a,c in ipairs(game.Players:GetPlayers()) do)
-teams have to be even
-teams have to be randomized
if team == "red" then
c.FTEAM.Value = "Red"
team = "blue"
else
c.FTEAM.Value = "Blue"
team = "red"
end
local teamColors = {"Blue","Red"}
for a, c in pairs(game.Players:GetChildren()) do
c.FTEAM.Value = teamColors[math.random(1,#teamColors)] -- Choose a random value from the teamColor list
end
You can also implement math.randomseed() to help vary the randomness from server to server, however ‘true random number generation’ is its own rabbit hole
No; but this will (assuming you have an even number of players):
local players = game.Players:GetPlayers()
for i = 1, #players do
players[i].FTEAM.Value = "Red"
if i%2 == 0 then
players[i].FTeam.Value = "Blue"
end
end
local function assignTeams(playersPerTeam)
local players = game.Players:GetPlayers()
local redTeam, blueTeam = {}, {}
math.randomseed(tick())
for i = #players, 2, -1 do
local j = math.random(i)
players[i], players[j] = players[j], players[i]
end
local currentTeam = redTeam
for i, player in ipairs(players) do
if #currentTeam < playersPerTeam then
table.insert(currentTeam, player)
player.FTEAM.Value = "Red"
else
if currentTeam == redTeam then currentTeam = blueTeam
end table.insert(currentTeam, player)
player.FTEAM.Value = "Blue"
end
end
end
assignTeams(3) --playersPerTeam
Mockup
local function assignTeams(playersPerTeam)
local players = {"Player1", "Player2", "Player3", "Player4", "Player5", "Player6", "Player7", "Player8"}
local redTeam, blueTeam = {}, {}
math.randomseed(tick())
for i = #players, 2, -1 do
local j = math.random(i)
players[i], players[j] = players[j], players[i]
end
local currentTeam = redTeam
for i, player in ipairs(players) do
if #currentTeam < playersPerTeam then
table.insert(currentTeam, player)
else
if currentTeam == redTeam then currentTeam = blueTeam
end table.insert(currentTeam, player)
end
end
print("Red Team:", table.concat(redTeam, ", "))
print("Blue Team:", table.concat(blueTeam, ", "))
end
for i = 1, 4 do assignTeams(4) --playersPerTeam, testing 4, 4 times
print(" ") task.wait(3)
end
Confirmed this shuffles players each time and equally divides into two teams
-- Tables
local plrTable = game.Players:GetPlayers()
local shuffledPlrs = {}
-- Shuffle Players
for i, v in pairs (plrTable) do
local slot = math.random(1,#plrTable)
while shuffledPlrs[slot] do
slot = math.random(1,#plrTable)
end
shuffledPlrs[slot] = v
end
-- Equally divide teams from shuffled table
local last = "Red"
for i, v in ipairs(shuffledPlayers) do
if last == "Red" then
last = "Blue"
else
last = "Red"
end
v.FTEAM.Value = last
end