01 | local players = game.Players:GetChildren() |
02 | local teams = { "Persimmon" , "Cyan" } |
03 | local count = 1 |
04 | for i, v in pairs (players) do |
05 | v.TeamColor = BrickColor.new(teams [ count ] ) |
06 | count = count + 1 |
07 | v.PlayerFolder:WaitForChild( "Team" ).Value = tostring (v.TeamColor) |
08 | if count > #teams then |
09 | count = 1 |
10 | end |
11 | end |
The whole point of this script is to get random teams for every player. The only problem I have noticed is that every round I'm on the exact same team. Can anyone please help?
Of course this isn't random. You're not using a single random function.
I think what you're trying to do is create separate teams with as equal number of players as possible. Because you're already doing this, I have an idea that will compliment with your method, without changing anything.
Just create a table with the players inside, but shuffled. This will create a table of players randomly indexed.
Below is the added code which does this, combined with your code.
01 | local players = game.Players:GetPlayers() -- I changed this to GetPlayers instead of GetChildren |
02 | local teams = { "Persimmon" , "Cyan" } |
03 | local count = 1 |
04 |
05 | for i = #players, 2 , - 1 do |
06 | local j = math.random (i) |
07 | players [ i ] , players [ j ] = players [ j ] , players [ i ] |
08 | end |
09 |
10 | for i, v in pairs (players) do |
11 | v.TeamColor = BrickColor.new(teams [ count ] ) |
12 | count = count + 1 |
13 | v.PlayerFolder:WaitForChild( "Team" ).Value = tostring (v.TeamColor) |
14 |
15 | if count > #teams then |
16 | count = 1 |
17 | end |
18 | end |
I haven't tested this. If there is anything wrong, let me know.
What you want is constrained random assignment:
1) The team color of each player should be random
2) At the same time, you have certain constraints, e.g. you want all teams to have about an equal amount of players
The script below satisfies both requirements. Note that LUA random implementation seems to not be "very random", but adding a bunch of extra calls to math.random()
seems to help (see explanation below).
01 | local teams = { "Persimmon" , "Cyan" } |
02 |
03 | -- initialize team counts |
04 | local counts = { } |
05 | for i = 1 , #teams do counts [ i ] = 0 end |
06 |
07 | -- determine how many players per team (at most) |
08 | local maxCount = math.ceil(#players / #teams) |
09 |
10 | -- re-randomize every time a game starts |
11 | -- NOTE: because Lua random number implementation seems to be very weak, adding a bunch of extra calls to random() can help things a bit |
12 | -- reference: http://stackoverflow.com/questions/20154991/generating-uniform-random-numbers-in-lua |
13 | math.randomseed(tick()) |
14 | math.random(); math.random(); math.random() |
15 |
Locked by OldPalHappy
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?