Game breaking when someone leaves

Hey so I am working on this roblox game and the game keeps breaking when someone leaves and I cant figure out how to fix this I have seen nothing in the output and I can’t figure out the fix
image

--Rounds script
local info=require(script:WaitForChild('GameInformation'))
local State=require(script:WaitForChild('Phase'))
--[[local function RoundCycle()
	if info.Currents["In Round"] or #game.Players:GetPlayers()<info.Requirements["Players Needed"] then return end
	info.Currents["In Round"]=true
	local State=require(script:WaitForChild('Phase'))
	local Continue = State.Intermisson()
	if not Continue then
		for i,plr in pairs(game.Players:GetPlayers()) do
			plr.PlayerGui.PlayerUI.GameMenus.Vote.GlobalTimer.TextLabel.Text = "Waiting for  two  players to join the game..."
		end
		return RoundCycle()
	end
	State.Map_Vote()
	State:BeginRound()
	info.Currents["In Round"]=false
	RoundCycle()
end
--]]
local Reset = true

game.Players.PlayerRemoving:Connect(function(plr)
	if plr.Team == game.Teams.Juggernaut then
		State.ResetGame() 
		
		
	
	
	end
end)
local GameReset = coroutine.create(function()
	while task.wait() do
		if #game.Players:GetPlayers() < info.Requirements["Players Needed"] and Reset == false then
			State.ResetGame()
			Reset = true
		end
	end
end)

coroutine.resume(GameReset)
game.Players.PlayerAdded:Connect(function(plr)
	plr.Team = game.Teams.Lobby
	if info.Currents["In Round"] or #game.Players:GetPlayers()<info.Requirements["Players Needed"] then return end
	Reset = false
	State.RoundCycle()
end)


local rs=game:GetService('ReplicatedStorage')
rs:WaitForChild('GameData'):WaitForChild('Requests').OnServerEvent:Connect(function(player, Request, ect)
	if Request=='Vote' and info['Currents']['Voting'] then
		require(script:WaitForChild('Phase')).Vote(player,ect)
	elseif Request=='Code' then		
	elseif Request=='Load' then
		rs:WaitForChild('PlayerData'):WaitForChild(player.UserId).Loaded.Value=true
	end
end)
 -- phase script
local rs=game:GetService('ReplicatedStorage')
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")
local MarketplaceService = game:GetService("MarketplaceService")

local gd=rs:WaitForChild('GameData')

local tools = ServerStorage.Tools

local hpBoostId = 206689824
local cashBoostId = 206688041
local vipBoostId = 206687310

local p = {}
--
local data=require(script.Parent:WaitForChild('GameInformation'))
local function plrui(f)
	for i,v:Player in pairs(game.Players:GetPlayers()) do
		f(v.PlayerGui)
	end
end
--

function p.RoundCycle()
	local info=require(script.Parent:WaitForChild('GameInformation'))
	if info.Currents["In Round"] or #game.Players:GetPlayers()<info.Requirements["Players Needed"] then return end
	info.Currents["In Round"]=true
	local Continue = p.Intermisson()
	if not Continue then
		for i,plr in pairs(game.Players:GetPlayers()) do
			plr.PlayerGui.PlayerUI.GameMenus.Vote.GlobalTimer.TextLabel.Text = "Waiting for two players to join the game..."
		end
		return p.RoundCycle()
	end
	p.Map_Vote()
	p.BeginRound()
	info.Currents["In Round"]=false
	p.RoundCycle()
end
function p.ResetGame()
	local info=require(script.Parent:WaitForChild('GameInformation'))
	info.Currents["In Round"] = false
	local SpawnPoint = game.Workspace.Lobby.SpawnLocation
	for i,plr in pairs(game.Players:GetPlayers()) do
		if plr.Character then
			plr.Character.Humanoid.Health = 0
		end
	end
	for i,plr in pairs(game.Players:GetPlayers()) do
		plr.PlayerGui.PlayerUI.GameMenus.Vote.GlobalTimer.TextLabel.Text = "Waiting for  two  players to join the game..."
		plr.Team = game.Teams.Lobby
	end
	p.RoundCycle()
end
p.Intermisson=function()
	local info=require(script.Parent:WaitForChild('GameInformation'))
	
	for i=1,data.Times.Intermission_Duration do
		plrui(function(UI:StarterGui)
			local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
		):WaitForChild('Vote'):WaitForChild('GlobalTimer'):WaitForChild('TextLabel')
			--
			t.Text='Intermission '..data.Times.Intermission_Duration-i
			for i,v:Player in pairs(game.Teams.Juggernaut:GetPlayers()) do
				if not v:IsA('Player') then continue end
				v.Team=game.Teams.Lobby
			end
			for i,v:Player in pairs(game.Teams.Swarms:GetPlayers()) do
				if not v:IsA('Player') then continue end
				v.Team=game.Teams.Lobby
			end
		end)
		wait(1)
		if #game.Players:GetPlayers() < info.Requirements["Players Needed"] then
			return false
		end
	end
	return true
end

p.Vote=function(player,Map:string)
	local vote=gd:WaitForChild('CastedVotes'):FindFirstChild(player.Name)
	if not vote then
		vote = Instance.new('StringValue', gd:WaitForChild('CastedVotes'))
		vote.Name=player.Name
	end
	local t=workspace:WaitForChild('Arenas')
	local found=nil
	--
	for i,v in pairs(gd:WaitForChild('MapsSelected'):GetChildren()) do
		if v.Value:upper()==Map:upper() then
			found=t:FindFirstChild(Map)
			vote.Value=Map
		end
	end
	--
	if not found then
		vote.Value=0
	end
end
p.Map_Vote=function()
	data.Currents['Voting']=true
	local t=workspace:WaitForChild('Arenas'):GetChildren()
	local selected={}
	for i=1,3 do
		local Randome=math.random(1,#t)
		gd:WaitForChild('MapsSelected'):FindFirstChild('Map'..i).Value=t[Randome].Name
		table.remove(t, Randome)
	end
	plrui(function(UI:StarterGui)
		local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
		):WaitForChild('Vote'):WaitForChild('GlobalTimer'):WaitForChild('TextLabel')
		t.Text='Voting... '
	end)
	for i=1,data.Times.Map_Voting_Duration do
		wait(1)
		plrui(function(UI:StarterGui)
			local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
			):WaitForChild('Vote'):WaitForChild('VoteForMap')
			t.Visible=true
			--
			t:WaitForChild('VoteTimer').Text=data.Times.Map_Voting_Duration-i
		end)
	end
	plrui(function(UI:StarterGui)
		local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
		):WaitForChild('Vote'):WaitForChild('VoteForMap')
		t.Visible=false
	end)
	data.Currents['Voting']=false
end
p.Mode_Vote=function()
	local ui:StarterGui=plrui()
	for i=1,data.Times.Gamemode_Vote_Duration do
		wait(1)
	end
end
function p:BeginRound()
	--
	local mapss=gd:WaitForChild('MapsSelected')
	--
	local t={
		[mapss:WaitForChild('Map1').Value]=0;
		[mapss:WaitForChild('Map2').Value]=0;
		[mapss:WaitForChild('Map3').Value]=0;
	}
	--
	local playervotes=gd:WaitForChild('CastedVotes')
	for i,v in pairs(playervotes:GetChildren()) do
		if not v:IsA('StringValue') or v.Value=='' then continue end
		if t[v.Value] then
			local og=t[v.Value]
			t[v.Value]=og+1
		end
		v.Value=''
	end
	--
	local mostvoted={}
	for i,v in pairs(t) do
		local m=table.maxn(mostvoted)
		if m==0 then mostvoted[1]=i 
		elseif t[mostvoted[1]]<v then
			mostvoted={[1]=i}
		elseif t[mostvoted[1]]==v then
			mostvoted[m+1]=i
		end
	end
	warn(mostvoted)
	--
	local map=workspace:WaitForChild('Arenas'):FindFirstChild(mostvoted[math.random(1,table.maxn(mostvoted))])
	--
	local teams=game:GetService('Teams')
	local allp=game.Players:GetPlayers()
	local random=math.random(1,#allp)
	local juggernaught_Spawn=map:FindFirstChild('Juggernaut')
	local SwarmSpawn=map:FindFirstChild('Swarm')
	local spawns={}
	for i,v in pairs(map:GetChildren()) do
		if v.Name=='Swarm' then
			spawns[table.maxn(spawns)+1]=v
		end
	end
	local juggsettings=require(script.Parent:WaitForChild('GameInformation')).JuggernautSettings
	if not juggernaught_Spawn then warn('There is no juggernaught spawn') return end
	local juggdied=false
	local deadConnection=nil
	local choice = nil
	--
	for i,v in pairs(allp) do
		if i==random then
			choice=v
		end
	end
	--
	rs:WaitForChild('GameData'):WaitForChild('Requests'):FireAllClients('spinner', {choice.UserId;os.time()+data.Times.Juggernaught_Spin_Duration})
	--
	for i=1,data.Times.Juggernaught_Spin_Duration do
		if juggdied then break end
		plrui(function(UI:StarterGui)
			local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
			):WaitForChild('Vote'):WaitForChild('GlobalTimer'):WaitForChild('TextLabel')
			--
			t.Text='Choosing Juggernaut '..data.Times.Juggernaught_Spin_Duration-i
		end)
		wait(1)
	end
	local inagame=false
	--
	local characonnection = {}
	for i,v:Player in pairs(allp) do
		local char=v.Character or v.CharacterAdded:Wait()
		local hum=char:FindFirstChildOfClass('Humanoid')
		local pos=char:WaitForChild('HumanoidRootPart').Size
		local plrload=rs:WaitForChild('PlayerData'):WaitForChild(v.UserId).Loaded.Value
		local playerData = rs.PlayerData:FindFirstChild(v.UserId)
		if not plrload then continue end
		--
		v.PlayerGui:WaitForChild('PlayerUI'):WaitForChild('Menus').Visible=false
		char.PrimaryPart.Anchored=true
		

		
		if v == choice then
			local success, hasPass = pcall(function()
				return MarketplaceService:UserOwnsGamePassAsync(v.UserId, hpBoostId)
			end)
			v.Team=teams.Juggernaut
			char:MoveTo(juggernaught_Spawn.Position+Vector3.new(0,(pos.Y+hum.HipHeight)*juggsettings.Scale,0))
			hum.WalkSpeed=juggsettings.WalkSpeed
			hum.MaxHealth= if hasPass then juggsettings.Health + 25 else juggsettings.Health
			hum.Health=hum.MaxHealth
			hum.JumpPower=juggsettings.JumpPower
			deadConnection = hum.Died:Connect(function()
				juggdied=true
				--rs.LifeRemove:FireClient(v, 1)
			end)
			local toolClone = tools[playerData.Inventory.EquippedJuggernaut.Value]:Clone()
			toolClone.Parent = v.Backpack
			wait(.2)
			char:ScaleTo(juggsettings.Scale)
			toolClone:FindFirstChild("Handle").Size = Vector3.new(0.506, 10.681, 0.857)
		else

			
			local lives=3
			local function deatconnection()
				characonnection[i]=v.Character:FindFirstChildOfClass('Humanoid').Died:Connect(function()
					--lives-=1
					--print("Lives: "..lives)
					--rs.LifeRemove:FireClient(v, 1)
					--if lives<=0 then
					v.Team=teams.Spectactor
					rs.EnableSpec:FireClient(v)
				
					v.CharacterAdded:Wait()
					if inagame==true then
						local spaw=math.random(1,#spawns)
						char:MoveTo(spawns[spaw].Position+Vector3.new(0,pos.Y+hum.HipHeight,0))
						deatconnection()
					end
					
				end)
			end
			v.Team=teams.Swarms
			local toolClone = tools[playerData.Inventory.EquippedSwarm.Value]:Clone()
			toolClone.Parent = v.Backpack
			local spaw=math.random(1,#spawns)
			char:MoveTo(spawns[spaw].Position+Vector3.new(0,pos.Y+hum.HipHeight,0))
			deatconnection()
		end
		char.PrimaryPart.Anchored=false
		--rs.Lives:FireClient(v, v.Team)
	end
	--
	inagame=true
	for i=1,data.Times.Round_Duration do
		print("Running")
		if juggdied or #teams.Swarms:GetPlayers()<=0 then
			--for _, player in teams.Swarms:GetPlayers() do
			--	rs.LifeRemove:FireClient(player, 3)
			--end
			--for _, player in teams.Juggernaut:GetPlayers() do
			--	rs.LifeRemove:FireClient(player, 1)
			--end
			break 
		end
		plrui(function(UI:StarterGui)
			local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
			):WaitForChild('Vote'):WaitForChild('GlobalTimer'):WaitForChild('TextLabel')
			--
			t.Text='Round is going on for: '..data.Times.Round_Duration-i
		end)
		Players.PlayerAdded:Connect(function()
			plrui(function(UI:StarterGui)
				local t:TextLabel = UI:WaitForChild('PlayerUI'):WaitForChild('GameMenus'
				):WaitForChild('Vote'):WaitForChild('GlobalTimer'):WaitForChild('TextLabel')
				--
				t.Text='Round is going on for: '..data.Times.Round_Duration-i
			end)
		end)
		wait(1)
	end
	for i,v in pairs(characonnection) do
		if not v then continue end
		v:Disconnect()
	end
	inagame=false
	local jjcsh=gd:WaitForChild('JuggCash')
	local swrmcsh=gd:WaitForChild('SwarmCash')
	if juggdied then
		jjcsh.Value=10+gd:WaitForChild('RoundKills').Value
		swrmcsh.Value=20
	else
		jjcsh.Value=20+gd:WaitForChild('RoundKills').Value
		swrmcsh.Value=10
	end
	---
	gd:WaitForChild('Requests'):FireAllClients('game ended', not juggdied)
	---
	if deadConnection and type(deadConnection)=='function' then
		deadConnection:Disconnect()
	end
	--
	for i,v:Player in pairs(allp) do
		--
		local playerdata=rs:WaitForChild('PlayerData'):FindFirstChild(v.UserId)
		local character = v.Character or v.CharacterAdded:Wait()
		if not playerdata then
			require(script.Parent.Parent:WaitForChild('Player'):WaitForChild('Data')):Setup_Data(v)
			playerdata=rs:WaitForChild('PlayerData'):FindFirstChild(v.UserId)
		end
		if playerdata then
			local cash=playerdata:WaitForChild('Cash')
			local success, hasPass = pcall(function()
				return MarketplaceService:UserOwnsGamePassAsync(v.UserId, cashBoostId)
			end)
			local success, hasVip = pcall(function()
				return MarketplaceService:UserOwnsGamePassAsync(v.UserId, vipBoostId)
			end)
			if v.Team==teams.Juggernaut then
				local totalCash = if hasPass then jjcsh.Value * 2 else jjcsh.Value
				totalCash = if hasVip then jjcsh.Value * 2 else jjcsh.Value 
				cash.Value += totalCash
			elseif v.Team==teams.Swarms or v.Team==teams.Lobby then
				local totalCash = if hasPass then swrmcsh.Value * 2 else swrmcsh.Value
				totalCash = if hasVip then swrmcsh.Value * 2 else swrmcsh.Value 
				cash.Value += totalCash
			end
		end
		
		-- Destroy players tools whether equipped or not.
		for _, tool in v.Backpack:GetChildren() do
			tool:Destroy()
		end
		for _, possibleTool in character:GetChildren() do
			if possibleTool:IsA("Tool") then
				possibleTool:Destroy()
			end
		end
		
		--
		v.Team=teams.Lobby
		print("IN LOBBY")
		rs.DisableSpec:FireClient(v)
		local cahr=v.Character
		v.PlayerGui:WaitForChild('PlayerUI'):WaitForChild('Menus').Visible=true
		if not cahr then continue end
		cahr:ScaleTo(1)
		local _,s = cahr:GetBoundingBox()
		cahr:MoveTo(workspace:WaitForChild('Lobby'):WaitForChild('SpawnLocation').Position+Vector3.new(0,s.Y,0))
		local hum=cahr:FindFirstChildOfClass('Humanoid')
		if hum then
			hum.WalkSpeed=16
			hum.MaxHealth=100
			hum.Health = hum.MaxHealth
			hum.JumpPower=50
		end
	end
end

return p