How Figure Out Who The Last Player Alive In A Round Is?

Hey guys, I’m making a game that is supposed to release in one day but I haven’t successfully created the win system yet. How would I add a win system into my code?
WHOLE CODE

local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local Maps = ServerStorage:WaitForChild('Maps'):GetChildren()
local Status = ReplicatedStorage:WaitForChild('Status')

while true do
	
	--Intermission
	
	local Countdown = 30 -- intermission, make this as long as you want
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Intermission : '..Countdown
	until Countdown <= 0
	
	--Choose the map.
	
	Status.Value = 'Choosing Map...'
	
	local ChosenMap = Maps[math.random(1, #Maps)]:Clone()
	local Spawns = ChosenMap:FindFirstChild('Spawns'):GetChildren()


	wait(3) -- little pause, make this as long as you want
	
	ChosenMap.Parent = workspace
	Status.Value = 'Map chosen, teleporting players.'
	
	wait(2) -- little pause, make this as long as you want
	local Knife = ServerStorage.Knife
	--teleport the players
	
	local playersInRound = {} -- track alive players
	local connections = {} -- store connections to disconnect later
	for _, Player in pairs(Players:GetChildren()) do
		if Player.Character and Player.Character:FindFirstChild('Humanoid') then
			local RandomSpawn = Spawns[math.random(1, #Spawns)]
			Player.Character.HumanoidRootPart.CFrame = RandomSpawn.CFrame
			local newKnife = Knife:Clone()
			newKnife.Parent = Player.Backpack

			table.insert(playersInRound, Player) -- add all players to table
			connections[Player.Name] = Player.Character.Humanoid.Died:Connect(function()
				table.remove(playersInRound, table.find(playersInRound, Player))
                if playersInRound[2] ~= nil then
                    -- Nothing
                else
                    -- What to happen when last player is alive
                    print("The Winner is: " ..playersInRound[1])
					Status.Value = playersInRound[1] .. " won the game!"
                    Player.leaderstats.Wins.Value = Player.leaderstats.Wins.Value + 1 -- I don't know if its called "Wins" but change it as you please
					Player.leaderstats.Coins.Value = Player.leaderstats.Coins.Value + 100
                end
			end)
		end
	end
	
	connections["Removing"] = game.Players.PlayerRemoving:Connect(function(player) -- remove player from list if they leave
		local ind = table.find(playersInRound, player)
		if ind then
			table.remove(playersInRound, ind)
		end
	end)
	
	Countdown = 5 -- Starting Round In, make this as long as you want
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Starting Round in : '..Countdown
	until Countdown <= 0
	
	Countdown = 60 -- Game Time
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Ingame : '..Countdown
	until Countdown <= 0 or #playersInRound == 1
--Dax could you make a gui pop up here that makes the last player left, the winner, get 1 win added to win leaderstats and also have a gui pop up on everyones screens 
--that says the winner, and also awards the winner 100 coins
-- ok -dax

	--Kill the players
	for _, connection in pairs(connections) do -- disconnect connections to prevent memory leaks
		connection:Disconnect()
	end
	
	for _, Player in pairs(playersInRound)do
		Player:LoadCharacter()
	end
	
	ChosenMap:Destroy()
	
	Status.Value = 'Round Ended, waiting for new game.'
	
	wait(4) -- little pause, make this as long as you want.
	
end

ATTEMPT AT WIN PART

 -- What to happen when last player is alive
                    print("The Winner is: " ..playersInRound[1])
					Status.Value = playersInRound[1] .. " won the game!"
                    Player.leaderstats.Wins.Value = Player.leaderstats.Wins.Value + 1 -- I don't know if its called "Wins" but change it as you please
					Player.leaderstats.Coins.Value = Player.leaderstats.Coins.Value + 100
                end
			end)
		end
	end

For some reason this doesn’t work. I need help urgently, so help is really appreciated. Thanks.

2 Likes

I am really, really stuck on this one so if anyone could help me they could make a big difference in my life.

Haven’t read the script cause it confuses me but
why not make a variable equaling to the last player that won before proceeding to the next round?

1 Like

Make a table with all the players and when someone dies remove them from the table, then check periodically what is the amount of players in the table.

2 Likes

Yes, I’ve done that- but I don’t know how to figure out who the last player is so I can give them a win and some coins @DaffyDavinko

Everytime a player dies or leaves the game(PlayerRemoving,Humanoid.Died) then
remove them from the table and check if #table = 1 then
winningplayer = table[1]
proceed to next round?

1 Like

Well you can like wait 1 second and check all the players, here is a example.

local Table = {}
local Winner = nil
local Players = game:GetService("Players")

table.insert(Table, Players)
game:GetService("RunService").Heartbeat:Connect(function())
  if #Table == 1 not 2 then
    for _,Player in pairs(Players:GetChildren()) do
        Winner = Player
        -- or you can just make a function that will have all the winning functions like giving coins, etc.
    end
  end
end)
2 Likes

Ok, but would I have to put that script inside my old one or make a new one? @DaffyDavinko

@octavodad You could insert a string value inside every player when he enters the map.

To make it easier make a part that covers the whole map and type this.
(Note make it’s size long and high more than the players size and make it transparent and can - collide to false)

game.Workspace:WaitForChild("Map").insertTagPart.Touched:Connect(function(player) -- finding the touched part and doing a Touched Event
   local playerInMatch = Instance.new("StringValue") -- making a new string value
   local playerInMatch.Name = "PlayerInMatch" -- naming it
   playerInMatch.Parent = player -- parenting it.
end)

-- also make sure to teleport the players to the lobby so they no more touch the part.

game.Workspace:WaitForChild("Map").insertTagPart.TouchEnded:Connect(function(player)  -- when touch ends AKA the player dies
    if player:FindFirstChild("PlayerInMatch") then -- checking if the player has the PlayerInMatch
       player:FindFirstChild("PlayerInMatch"):Destroy() -- if then destroying it.
    end 
end)

local playerInMatchTable = {} -- making a table

for	i, player in pairs(game.Players:GetPlayers()) do 
	if player:FindFirstChild("PlayerInMatch") then -- if the player has the player in match tag then
		table.insert(playerInMatchTable, player) -- inserting them to the table
	end 
end

NOTE: The above codes can be put anywhere before the code under

Put the code below in the place of this code of yours (Not 100% sure)

My code here

if playerInMatchTable >1 then -- checking the number of players in the match
   -- continue the match
   elseif playerInMatchTable = 1 the
      -- end the game
end

I hope I haven’t made any mistakes :smiley:
Hope this works for your game :hugs:

Also remember me?
The person who made a star wars team change UI for free? :grin:

1 Like

OMG its you! My only question is what would you do to make them get a win and some coins from that tho?

1 Like

Thats kinda not possible for me.
If you have a leaderstats then make a script to check the number of coins the player has by looping through their leaderstats.

I only how to do it but I have no idea to make a script for that.
Try checking the Youtube or posting about it on dev Forum

1 Like

Here’s a neat example that can definitely be useful in the future.
This is just pseud-ocode, don’t expect it to work as this is just an example to understand from.

local RunService = game:GetService('RunService')

local Alive = {}
-- Accessing the player instance is faster than accessing ex: its name (Player.Name).
-- No player instance can be the same, so it doesn't matter.
Alive[PlayerInstance] = true -- Add them to the table.
Alive[PlayerInstance] = nil -- Remove them from the table.

local Winner -- We're using this for later.

local Connection
Connection = RunService.RenderStepped:Connect(function()
	if #Alive == 1 then -- By using the length operator, we can check it every frame.
		
		Winner = Alive[1] -- Which is the last player alive.
		-- Award them whatever?
		print(Winner .. ' has won the game!')
		Connection:Disconnect() -- We no longer need it, let's disconnect it.
	end
end)

Humanoid.Died:Connect(function()
	if GAME_IS_RUNNING then -- Remove them only if the round has started (?)
		Alive[PlayerInstance] = nil -- Remove them from the table as they died.
	end	
end)

RenderStepped:

1 Like

This is how I’ve combined both of @amalnk0007 @Syclya scripts, but it doesn’t work; I’ve done something wrong, but I’m not sure what… Could you guys correct me?

local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local Maps = ServerStorage:WaitForChild('Maps'):GetChildren()
local Status = ReplicatedStorage:WaitForChild('Status')

while true do
	
	--Intermission
	
	local Countdown = 30 -- intermission, make this as long as you want
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Intermission : '..Countdown
	until Countdown <= 0
	
	--Choose the map.
	
	Status.Value = 'Choosing Map...'
	
	local ChosenMap = Maps[math.random(1, #Maps)]:Clone()
	local Spawns = ChosenMap:FindFirstChild('Spawns'):GetChildren()


	wait(3) -- little pause, make this as long as you want
	
	ChosenMap.Parent = workspace
	Status.Value = 'Map chosen, teleporting players.'
	
	wait(2) -- little pause, make this as long as you want
	local Knife = ServerStorage.Knife
	--teleport the players
	
	local playersInRound = {} -- track alive players
	local connections = {} -- store connections to disconnect later
	for _, Player in pairs(Players:GetChildren()) do
		if Player.Character and Player.Character:FindFirstChild('Humanoid') then
			local RandomSpawn = Spawns[math.random(1, #Spawns)]
			Player.Character.HumanoidRootPart.CFrame = RandomSpawn.CFrame
			local newKnife = Knife:Clone()
			newKnife.Parent = Player.Backpack

			table.insert(playersInRound, Player) -- add all players to table
			connections[Player.Name] = Player.Character.Humanoid.Died:Connect(function()
				table.remove(playersInRound, table.find(playersInRound, Player))
                if playersInRound[2] ~= nil then
                    -- Nothing
                else
                    
                    print("The Winner is: " ..playersInRound[1])
					Status.Value = playersInRound[1] .. " won the game!"
                    Player.leaderstats.Wins.Value = Player.leaderstats.Wins.Value + 1 -- I don't know if its called "Wins" but change it as you please
					Player.leaderstats.Coins.Value = Player.leaderstats.Coins.Value + 100
                end
			end)
		end
	end
	
	connections["Removing"] = game.Players.PlayerRemoving:Connect(function(player) -- remove player from list if they leave
		local ind = table.find(playersInRound, player)
		if ind then
			table.remove(playersInRound, ind)
		end
	end)
	
	Countdown = 5 -- Starting Round In, make this as long as you want
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Starting Round in : '..Countdown
	until Countdown <= 0
	
	Countdown = 240 -- Game Time
	
	repeat wait(1)
		Countdown = Countdown - 1
		
		Status.Value = 'Ingame : '..Countdown
	until Countdown <= 0 or #playersInRound == 1

--Dax could you make a gui pop up here that makes the last player left, the winner, get 1 win added to win leaderstats and also have a gui pop up on everyones screens 
--that says the winner, and also awards the winner 100 coins
-- ok -dax

	--Kill the players
	for _, connection in pairs(connections) do -- disconnect connections to prevent memory leaks
		connection:Disconnect()
	end
	
	for _, Player in pairs(playersInRound)do
		Player:LoadCharacter()
	end
	
	ChosenMap:Destroy()
	
	Status.Value = 'Round Ended, waiting for new game.'
	
	wait(4) -- little pause, make this as long as you want.
	
end



--Start of a new era
local Winner -- We're using this for later.
local Status = game.ReplicatedStorage:WaitForChild('Status')

game.Workspace:WaitForChild("Map").insertTagPart.Touched:Connect(function(player) -- finding the touched part and doing a Touched Event
   local playerInMatch = Instance.new("StringValue") -- making a new string value
   local playerInMatchName = "PlayerInMatch" -- naming it
   playerInMatch.Parent = player -- parenting it.
end)

-- also make sure to teleport the players to the lobby so they no more touch the part.

game.Workspace:WaitForChild("Map").insertTagPart.TouchEnded:Connect(function(player)  -- when touch ends AKA the player dies
    if player:FindFirstChild("PlayerInMatch") then -- checking if the player has the PlayerInMatch
       player:FindFirstChild("PlayerInMatch"):Destroy() -- if then destroying it.
    end 
end)

local playerInMatchTable = {} -- making a table

for	i, player in pairs(game.Players:GetPlayers()) do 
	if player:FindFirstChild("PlayerInMatch") then -- if the player has the player in match tag then
		table.insert(playerInMatchTable, player) -- inserting them to the table
	end 
end
if playerInMatchTable == 1 then
print("I am awesome")
Winner = playerInMatchTable[1]
Winner.leaderstats.Wins.Value = Winner.leaderstats.Wins.Value + 1
Winner.leaderstats.Coins.Value = Winner.leaderstats.Coins.Value + 100
Status.Value = Winner .. " won the round!"
end

Thanks
NOTE: Scroll all the way to the bottom for the new stuff

You should not comparing the table in here

if playerInMatchTable == 1

Try with

if #playerInMatchTable == 1
1 Like

Yeah, it doesn’t work still… any way I can check how much players are touching a part and then if 1 player is touching a part they get the rewards? @Syclya @AmbitiousAmateur @runaredie @DaffyDavinko @amalnk0007

What is the issue?

1 Like

Do you know of any way I can check how much players are touching a part and then if only 1 player is touching a part I give them the rewards?

Be more specific, not sure what you mean by “Do you know of any way I can check how much players are touching a part and then if only 1 player is touching a part I give them the rewards?”

EDIT: I assume you want the part to be destroyed once someone touches it?

1 Like

Ok, so I have this part right? And it covers the whole map. And, I figured that if I made a script which checked how much players were touching that part, when the number of players touching the part = 1, then I could call them the winner… and the script’d give em the win leaderstat + 1? Understand now?

Assuming you want to access it, you can do:
Replace Alive[Player] = true/nil with table.insert(Add, Player) as we can access it by indexing it below instead of a loop.

Add[1].leaderstats.STAT_NAME.Value = Value
1 Like