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 make this local function truly random?

i'm making a randomizeTeams() function to randomly but evenly assign players to 2 teams, and i've noticed while, it works, it's not random, choosing the same players over and over to be on the same teams over and over, any ideas how i can make it truly random?

local function randomizeTeams()
	local players = game.Players:GetPlayers()
	for i,v in pairs(players) do
		if i > #players/2 then 
		v.Team = game.Teams.Team1
		else
		v.Team = game.Teams.Team2
		end
	end
	end

1 answer

Truly random isn't really achievable... But! For the sake of our purposes here math.random() should do the trick :)

It's been a while since I've done Roblox coding but this and this might be helpful :)

You could loop over each player in the game and generate a random number for each of them, say you have ten players, each would get a random number and then the highest five players will be put into one team and the remaining five would form the other team :)

//This might need a little work, it's a while since I've done lua and I'm typing on mobile

//Whenever a round is being set up call "randomiseTeams"

local function randomiseTeams()

local players = game.GetService("Players")
local teams = game.GetService("Teams")
local randomiser ={} //will be filled as a dictionary linking a player to a random number
local array = [] //to order the dictionary, table.sort isn't meant for dictionaries

for _,player in pairs(players) do 
randomiser[math.random()] = player.name  //generates a random number and links it to a player name
end

for i,_ in pairs(randomiser) do
table.insert(array, key)
end

table.sort(array)

for i,number in pairs(array) do
if i < array.length/2 then
players.FindFirstChild(randomiser[number]).team = //teamOne
else
players.FindFirstChild(randomiser[number]).team = //teamTwo
end
end

end

It might be a bit complicated but it basically gets all players in the game, puts them in a dictionary with a random number attached to them Then the random numbers get sorted in an array Then this sorted list of random numbers is used to separate the players into teams... Hopefully it works alright, might have some bugs lol

2 comments

0

do you have an example of how i would go about using math.random() in this? im not exactly sure how i should make this type of system you're talking about

0

I've edited the answer above ???? hopefully it works, but if it's a bit buggy I'm sure you can see where I was heading with it! ????

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