Right - so, here is the code I have come up with to accomplish this.
function Shuffle(Table)
local Size = (#Table)
for i = Size, 1, -1 do
local RandomObject = Random.new():NextInteger(1, Size)
Table[i], Table[RandomObject] = Table[RandomObject], Table[i]
end
return Table
end
_G.Districts = {}
local Players = (Shuffle(game:GetService("Players"):GetPlayers()))
for i = (1),(math.ceil(#Players/2)) do
_G.Districts[#_G.Districts + 1] = {}
end
for Player = (1),(#Players) do
local DesiredDistrict = (math.ceil(Player/2))
table.insert(_G.Districts[DesiredDistrict], Players[Player])
end
Let's break it down. To start, we write a general Lua array shuffler using Fisher-Yates shuffle. This is so that we won't simply be matching players together in the order that the :GetPlayers() table provides them. From there, we move on to the more clinical stuff. We create our initial districts and players table(s). So - what next? We run a numeric for loop with the goal of creating ceiling(#players/2) districts inside of our districts table. So - after this portion of code, the following will be true:
1 player joins? >> _G.Districts = {{}}
3 players join? >> _G.Districts = {{}, {}}
4 players join? >> _G.Districts = {{}, {}}
Now what? We run yet another numerical for loop with the goal to add every player currently in the game into a district, two per district. This works because:
ceiling(1/2) > 1
ceiling(2/2) > 1
ceiling(3/2) > 2
ceiling(4/2) > 2
That's it - that's all there is to it. Now, if:
1 player: {{RandomPlayer}}
4 players: {{RandomPlayer, RandomPlayer}, {RandomPlayer, RandomPlayer}}
Hopefully this helps you. If you have any questions don't hesitate to ask. :)
4 comments
Okey, thats super complicated for my knowledge but its fine. Thanks alot! But i got more questions. So we got the system going but how would i check if some districts died? or if even all players currently playing died? I get the code but i cant find a way to make it functional. So if you could give me some examples with it, i would understand it better :)
Humanoids have an event called .Died, you can hook this to each player, and upon death remove them from the table. That way the table will effectively consist of alive players and nobody who has died. When all players from a team die their district's array will remain empty as {}.
I dont know if you still read this but how would i call the Players name? If i do print(DesiredDistrict,Players.Name) He will give me the District,yes but not the real Player Name its combined to
Nevermind i got it myself :) its print(DesiredDistrict,Players[Player])