# Player Picking Team

I want to allow 4 players to randomly be selected to be team-captains and once they are team-captains, they will go through a voting that allows them to pick players to be apart of their team…

I am uncertain how to start it and exactly how to go along with doing this…

1 Like

To randomly pick 4 players, you can generate 4 random numbers between 1 and the number of online players. Then, run through a simple algorithm to check against duplicates. Eventually store the chosen captains in a table.

``````local Players = game:GetPlayers() -- Gets a table of all players currently connected

local ChosenCaptains = {} -- Creating an empty table to store the chosen ones
for i = 1,4 do -- Runs a loop 4 times (you wanted 4 captains)

repeat
wait() -- So it doesn't time out.
local candidate = Players[math.random(1,#Players)] -- Chooses a random player
until table.find(ChosenCaptains, candidate) ~= nil -- Makes sure that the chosen player is not already a captain. If they are, then it reruns the script

table.insert(ChosenCaptains, candidate)
-- Inserts in our ChosenCaptains table 4 random players
end
``````

I wrote this on the forum so I apologize in advance for any typos or small errors.
I’m also still thinking on the voting part so I’ll come in with some edits if I figure it out myself…

tyty bro for the advice so far. just trying to learn also may i ask what the purpose of repeat was, i thought the loop would repeat itself 4 times nonetheless because its a loop

The purpose of that repeat until construct is to select a player to be a team’s leader that hasn’t already been selected.

``````local Game = game
local Players = Game:GetService("Players")
local Teams = Game:GetService("Teams")
local Random = Random.new()

local PlayersArray = Players:GetPlayers()
local TeamsArray = {}
for _, Team in ipairs(Teams:GetTeams()) do --Number of loops (team leaders chosen) depends on the number of teams.
local Index = Random:NextInteger(1, #PlayersArray)
local Player = PlayersArray[Index] --Fetch a random player.
table.insert(TeamsArray, {Team, Player}) --Set the player as the team's leader.
table.remove(PlayersArray, Index) --Remove the player from the array of players so that they cannot be chosen to be the leader of another team.
end
return TeamsArray --Return the array of the teams and their leaders.
end

local TeamsArray = GetTeamLeaders() --Call the function.

--Here is where you'd provide a way for team leaders to select players for their team, possibly via a gui/chat command.
``````
1 Like