Hey, I am new the world of Lua. I am working on a round based system and I wanted to implement a function that randomizes teams (game.Teams), has a probability of joining said team based off of the max/min and has a min/max amount of players for each team.
How would I do this? I looked at the Wiki for all types of different things I could use to help me but I am now sure how I could really get started doing this.
How many teams would this have to support? 2? 4? Even more possibly? I can think of a system for 2 teams but not sure if it’s efficient with 3 or 4.
Something like this should work for randomizing players into 2 teams:
local teams = game:GetService("Teams")
local players = game:GetService("Players")
local activePlayers = players:GetPlayers()
function randomizeTeams(team1, team2)
for i, player in ipairs(activePlayers) do
if (i % 2) == 0 then
player.Team = team1
else
player.Team = team2
end
end
end
-- And whenever you want to call it, for example after a map has loaded
randomizeTeams(teams:FindFirstChild("Team1Name", teams:FindFirstChild("Team2Name")) -- Would take in the two teams as parameters
I also forgot to mention it’s not just a 50/50 chance spawn, for example there is a max of 3 SCP’s to start out as and cannot have anymore, same with one other but the rest are Random.
Oh, thanks for the response. This info is very useful.
local teams = game:GetService("Teams")
local tInfo = {
["Team1Name"] = {
MaxPlayers = 3;
}
["Team2Name"] = {
MaxPlayers = 5;
}
["Team3Name"] = {
MaxPlayers = 10;
}
-- etc
}
local function countTeam(team)
local count = 0
for _, player in next, players:GetPlayers() do
if player.Team == team then
count = count + 1
end
end
return count
end
local function assignRandomTeam(player)
local assigned = false
while not assigned do
local randomTeam = teams:GetChildren()[math.random(#teams:GetChildren())]
if randomTeam and countTeam(randomTeam) < tInfo[randomTeam.Name].MaxPlayers
then
player.Team = randomTeam
assigned = true
end
wait(.5)
end
end
This code should work but hasn’t been tested. If it errors, the idea could be used I may have just implemented it wrong.