Was working on a sword fighting game when something went wrong

I was trying to make it so that I made a functioning sword fighting game.
I wanted to:
Create an intermission :white_check_mark:
Teleport all players to the map :white_check_mark:
Give them swords :white_check_mark:

But then when I was making it so that there was a time limit, and someone could win, and all of the circomstances that could’ve happened. So what happened was that I was testing my game, but then when all of the players teleported to the map and they all got there swords, it would immeditly announce the player who is at the top of the leaderboard the winner.
Example:
Player 2 is at the top of the leaderboard, while player 1 is at the bottom, (or not at the top) the game would start but then immeditly as the game started, it would announce player 2 as the winner.

I have tried checking the script for capitals, mispelling and everything but it dosent budge.
I will show you screenshots of what I have in game to make it more easier.
image
image

Note: There are more scripts, but they are irrelevent to the error

This is the main script, the most important things.

-- Define Variables

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ServerStorage = game:GetService("ServerStorage")

local MapsFolder = ServerStorage:WaitForChild("Maps")

local Status = ReplicatedStorage:WaitForChild("Status")

local GameLength = 50

local reward = 25

Game loop (Hidden in script)

while true do
	
	Status.Value = "Waiting for enough players"
	
	repeat wait(1) until game.Players.NumPlayers >= 2
	
	Status.Value = "Intermission"
	
	wait(10)
	
	local plrs = {}
	
	for i, player in pairs(game.Players:GetPlayers()) do
		if player then
			table.insert(plrs,player) -- Add each player into plrs table
		end
	end
	
	wait(2)
	
	local AvailableMaps = MapsFolder:GetChildren()
	
	local ChosenMap = AvailableMaps[math.random(1,#AvailableMaps)]
	
	Status.Value = ChosenMap.Name.." Chosen"
	
	local ClonedMap = ChosenMap:Clone()
	ClonedMap.Parent = workspace
	
	 --Teleport players to the map 
	
	local SpawnPoints = ClonedMap:FindFirstChild("SpawnPoints")
	
	if not SpawnPoints then
		print("You do not have spawnpoints! Fix this now.")
	end
	
	local AvailbaleSpawnPoints = SpawnPoints:GetChildren()
	
	for i, player in pairs(plrs) do
		if player then
			character = player.Character
			
			if character then
				--Teleport them 
				
				character:FindFirstChild("HumanoidRootPart").CFrame = AvailbaleSpawnPoints[1].CFrame
				table.remove(AvailbaleSpawnPoints,1)
				
				
				 Give them a sword (hidden in script)
				
				local ClassicSword = ServerStorage.ClassicSword:Clone()
				ClassicSword.Parent = player.Backpack
				
				local GameTag = Instance.new("BoolValue")
				GameTag.Name = "Gametag"
				GameTag.Parent = player.Character
				
			else
				 There is no character (Hidden in script)
				if not player then
					table.remove(plrs,i)
				end
			end
		end
	end
	
	
	Status.Value = "Get ready to play!"
	
	wait(2)
	
	for i = GameLength,0,-1 do
		
		for x,player in pairs(plrs) do
			if player then
				
				character = player.Character
				
				if not character then
					 Left the game (Hidden in script)
				else
					if character:FindFirstChild("GameTag") then
						They are still alive (Hidden in script)
						print(player.Name.." is still in the game!")
					else
						 They are dead (Hidden in script)
						table.remove(plrs,x)
						print(player.Name.." has been removed!")
					end
				end
			else
				table.remove(plrs,x)
				print(player.Name.." has been removed!")
			end
		end
		
		Status.Value = "There are "..i.." seconds remaining, and "..#plrs.." players left"
		
		if #plrs == 1 then
			-- Last person standing
			Status.Value = "The winner is "..plrs[1].Name
			plrs[1].leaderstats.Bucks.Value = plrs[1].leaderstats.Bucks.Value + reward
			break
		elseif #plrs == 0 then
			Status.Value = "Nobody won!"
			break
		elseif i == 0 then
			Status.Value = "Time up!"
			break
		end
		
		wait(1)
	end
	
	print("End of game")
	
	for i, player in pairs(game.Players:GetPlayers()) do
		character = player.Character
		
		if not character then
			 Ignore them (Hidden in script)
		else
			if character:FindFirstChild("GameTag") then
				character.GameTag:Destroy()
			end
			
			if player.Backpack:FindFirstChild("Sword") then
				player.Backpack.Sword:Destroy()
			end
			
			if character:FindFirstChild("Sword") then
				character.Sword:Destroy()
			end
			
		end
		
		player:LoadCharacter()
	end
	
	ClonedMap:Destroy()
	
	Status.Value = "Game Ended"
	
	
	wait(2)
end
2 Likes

I have the exact same topic posted! It doesn’t work for me either.

So I can find the problem easier, show me your output.

i think i know the problem, the script removes player 1 from the game, and i have it set up so that whoever is last in the players table, wins.
image

i just dont know how to fix it

Yeah, I have the same problem. It’s weird…

Possibly, the player could die while being teleported?

i dont think so because every time i do it, i dont see one player die, i could be wrong.

How do you reference the player being dead?

what do you mean?
im a begginer scripter and im following a tutorial

Basically, if the player is dead, how do you check?

There’s a couple questionable parts of this code, but none caught my attention more than this:

local plrs = {}
for i, player in pairs(game.Players:GetPlayers()) do
	if player then
		table.insert(plrs,player) -- Add each player into plrs table
	end
end

You could just make use of the :GetPlayers() function to do the same thing:

local plrs = game.Players:GetPlayers()

It returns a table of all of the players currently in the game.


As for the actual problem:

How I would approach this is using CollectionService to ‘tag’ every player with an ‘Alive’ tag and then use that to check if they’re active in the game.

In your PlayerAdded event, you could have an onCharacterAdded event to grab each player’s humanoid and check for when they die. Upon dying, if they have the ‘Alive’ tag, remove it. Something like this:

local function onPlayerAdded(player)
    local function onCharacterAdded(character)
        local humanoid = character:WaitForChild("Humanoid")
        humanoid.Died:Connect(function()
            if CollectionService:HasTag(player, "Alive") then
                CollectionService:RemoveTag(player, "Alive")
            end
        end)
    end
    if player.Character then
        onCharacterAdded(player.Character)
    end
    player.CharacterAdded:Connect(onCharacterAdded)
end

game.Players.PlayerAdded:Connect(onPlayerAdded)

With this approach, in your for i = GameLength, 0, -1 do loop, you can use something like this:

-- CollectionService here is assumed to be:
local CollectionService = game:GetService("CollectionService")
-- but you would define this up top like your other services

for i = GameLength, 0, -1 do
    if #CollectionService:GetTagged("Alive") == 1 then
        -- only one player is alive
        local winner = CollectionService:GetTagged("Alive")[1]
        Status.Value = "The winner is "..winner.Name
        winner.leaderstats.Bucks.Value += reward
    elseif #CollectionService:GetTagged("Alive") == 0 then
        -- nobody is alive
        Status.Value = "Nobody won!"
        break
    elseif i == 0 then
        -- timer ran out
        Status.Value = "Times up!"
        break
    end
    task.wait(1)
end

This also means that you’d have to change what you do to the player after they’re teleported. Instead of inserting a inserting a BoolValue into the player, just tag them with ‘Alive’:

for i, player in pairs(plrs) do
	if player then
		character = player.Character
		
		if character then
		    --Teleport them 
			character:FindFirstChild("HumanoidRootPart").CFrame = AvailbaleSpawnPoints[1].CFrame
			table.remove(AvailbaleSpawnPoints,1)
			
		    -- Give them a sword (hidden in script)
			local ClassicSword = ServerStorage.ClassicSword:Clone()
			ClassicSword.Parent = player.Backpack
			
			CollectionService:AddTag(player, "Alive")
		else
			-- There is no character (Hidden in script)
			if not player then
				table.remove(plrs,i)
			end
		end
	end
end
2 Likes

thanks for the information, but heres the thing. im a beginner scripter who dosent know where to put his scripts because i watched a tutorial, could you please tell me where to put the blocks of code?
dumb question, sorry

Fear not Mr. Creamy, I’ve come to the rescue.

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

local mapsFolder = ServerStorage:WaitForChild("Maps")
local statusTag = ReplicatedStorage:WaitForChild("Status")

-- Constants
local GAME_LENGTH = 50
local REWARD = 25
local PLAYERS_REQUIRED = 2
local INTERMISSION_TIME = 10

-- Functions
local function onPlayerAdded(player)
	local function onCharacterAdded(character)
		local humanoid = character:WaitForChild("Humanoid")
		humanoid.Died:Connect(function()
			if CollectionService:HasTag(player, "Alive") then
				CollectionService:RemoveTag(player, "Alive")
			end
		end)
	end
	if player.Character then
		onCharacterAdded(player.Character)
	end
	player.CharacterAdded:Connect(onCharacterAdded)
end

Players.PlayerAdded:Connect(onPlayerAdded)

-- Main loop
while true do
	-- Waiting for players
	statusTag.Value = "Waiting for enough players"
	repeat
		task.wait(1)
	until
	    #Players:GetPlayers() >= PLAYERS_REQUIRED

	-- Intermission
	for i = INTERMISSION_TIME, 0, -1 do
		statusTag.Value = "Intermission ["..i.."]"
		task.wait(1)
	end

	-- Choose a map
	local allMaps = mapsFolder:GetChildren()
	local map = allMaps[math.random(#allMaps)]:Clone()
    map.Parent = workspace
	statusTag.Value = map.Name .. " was chosen"
	task.wait(3)

	-- Teleport players
	local activePlayers = Players:GetPlayers()
	local spawns = map:FindFirstChild("SpawnPoints")
	if not spawns then
		warn("You do not have 'SpawnPoints', fix pl0x")
	end
	spawns = spawns:GetChildren()

	for _, player in pairs(activePlayers) do
		local hrp = player.Character:FindFirstChild("HumanoidRootPart")
		if hrp then
			local chosenSpawn = spawns[math.random(#spawns)]
			hrp.CFrame = chosenSpawn.CFrame
			table.remove(spawns, table.find(spawns, chosenSpawn))

			-- Give them a sword
			local sword = ServerStorage.ClassicSword:Clone()
			sword.Parent = player.Backpack

			CollectionService:AddTag(player, "Alive")
		end
	end

	statusTag.Value = "Get ready to play!"
	task.wait(2)

	for i = GAME_LENGTH, 0, -1 do
		if #CollectionService:GetTagged("Alive") == 1 then
			-- only one player is alive
			local winner = CollectionService:GetTagged("Alive")[1]
			statusTag.Value = "The winner is "..winner.Name
			winner.leaderstats.Bucks.Value += REWARD
			break
		elseif #CollectionService:GetTagged("Alive") == 0 then
			-- nobody is alive
			statusTag.Value = "Nobody won!"
			break
		elseif i == 0 then
			-- timer ran out
			statusTag.Value = "Times up!"
			break
		end
		task.wait(1)
		statusTag.Value = "There are " .. i .. " seconds remaining, and " .. #CollectionService:GetTagged("Alive") .. " players left"
	end

	print("END OF GAME")

	-- Clean up
	for _, player in pairs(activePlayers) do
		if CollectionService:HasTag(player, "Alive") then
			CollectionService:RemoveTag(player, "Alive")
		end
		if player.Backpack:FindFirstChild("Sword") then
			player.Backpack.Sword:Destroy()
		end
		if player.Character:FindFirstChild("Sword") then
			player.Character.Sword:Destroy()
		end
		player:LoadCharacter()
	end

	map:Destroy()
	statusTag.Value = "Game over"
	task.wait(2)
end

Try disabling your current script (don’t delete it just yet, good to keep an archive) and insert a new Script into ServerScriptService and paste that code above into there.

2 Likes

holy crap, thanks, one small issue though, is that an error appears.


on this line
image
though an error popped up, i appreciate the time and effort you put into that script, thanks

Yeah I fixed that, noticed it after. I changed it to:

table.remove(spawns, table.find(spawns, chosenSpawn))

Try that.

thank you alot, but the map dosent spawn, but one thing is that whoever is last, wins which was a problem i was struggling with alot.

For me, it’s not loading the map, and only teleporting 1 player.

for me its teleporting both players but the map dosent load

Fixed this, re-copy and paste the code from the post I made, I edited it.

O_O? What? If you have multiple spawn points, that shouldn’t be happening.