Pinkstack/roblox-luau-corpus-text huggingface dataset:
--[[Engine (Avxnturador)]]



	-- Everything below can be illustrated and tuned with the graph below.
	-- https://www.desmos.com/calculator/oishj9m1tq
	-- This includes everything, from the engines, to boost, to electric.
	
	-- To import engines prior to AC6C V1.3, consult the README.
	
	-- Naturally Aspirated Engine
	Tune.Engine 		= true		
		
		Tune.Horsepower		= 500
		Tune.IdleRPM		= 750
		Tune.PeakRPM		= 6800
		Tune.Redline		= 8000
		Tune.EqPoint		= 5252
		Tune.PeakSharpness	= 10
		Tune.CurveMult		= 0.4
	
	-- Electric Engine
	Tune.Electric		= false
		
		Tune.E_Redline	= 12700
		Tune.E_Trans1	= 4000
		Tune.E_Trans2	= 7000
		-- Horsepower
		Tune.E_Horsepower	= 223
		Tune.EH_FrontMult	= 0.15
		Tune.EH_EndMult		= 2.9
		Tune.EH_EndPercent	= 7
		-- Torque
		Tune.E_Torque		= 286
		Tune.ET_EndMult		= 1.505
		Tune.ET_EndPercent	= 27.5
		
	-- Turbocharger
	Tune.Turbochargers	= 1				-- Number of turbochargers in the engine
										-- Set to 0 for no turbochargers
		Tune.T_Boost		= 7
		Tune.T_Efficiency	= 8.5
		
		Tune.T_Size			= 80		-- Turbo Size; Bigger size = more turbo lag
		
	-- Supercharger
	Tune.Superchargers	= 1				-- Number of superchargers in the engine
										-- Set to 0 for no superchargers
		Tune.S_Boost		= 7
		Tune.S_Efficiency	= 8.5
		
		Tune.S_Sensitivity	= 0.05		-- Supercharger responsiveness/sensitivity, applied per tick (recommended values between 0.05 to 0.1)
		
	--Misc
	Tune.ThrotAccel		= .05		-- Throttle acceleration, applied per tick (recommended values between 0.05 to 0.1)
	Tune.ThrotDecel		= .2		-- Throttle deceleration, applied per tick (recommended values between 0.1 to 0.3)
	
	Tune.BrakeAccel		= .2		-- Brake acceleration, applied per tick
	Tune.BrakeDecel		= .5		-- Brake deceleration, applied per tick
	
	Tune.RevAccel		= 250		-- RPM acceleration when clutch is off
	Tune.RevDecay		= 75		-- RPM decay when clutch is off
	Tune.RevBounce		= 500		-- RPM kickback from redline
	
	Tune.IdleThrottle	= 3			-- Percent throttle at idle
	Tune.Flywheel		= 500		-- Flywheel weight (higher = faster response, lower = more stable RPM)
	
	Tune.InclineComp	= 1			-- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
--[[--------------------------------------------------------------------
-- state needed to generate code for a given function
-- struct FuncState:
--   f  -- current function header (table: Proto)
--   h  -- table to find (and reuse) elements in 'k' (table: Table)
--   prev  -- enclosing function (table: FuncState)
--   ls  -- lexical state (table: LexState)
--   L  -- copy of the Lua state (table: lua_State)
--   bl  -- chain of current blocks (table: BlockCnt)
--   pc  -- next position to code (equivalent to 'ncode')
--   lasttarget   -- 'pc' of last 'jump target'
--   jpc  -- list of pending jumps to 'pc'
--   freereg  -- first free register
--   nk  -- number of elements in 'k'
--   np  -- number of elements in 'p'
--   nlocvars  -- number of elements in 'locvars'
--   nactvar  -- number of active local variables
--   upvalues[LUAI_MAXUPVALUES]  -- upvalues (table: upvaldesc)
--   actvar[LUAI_MAXVARS]  -- declared-variable stack
----------------------------------------------------------------------]]
--The server will fire the ExitSeat remote to the client when the humanoid has been removed from a seat.
--This script listens to that and uses it to prevent the humanoid tripping when exiting a seat.
--As the player is removed from the seat server side, this scripts listens to the event instead of being
-- inside the ExitSeat function so that:
-- A) The timing is right - the exit seat function will run before the character is unsat by the server
-- B) If a server script removes the player from a seat, the anti-trip will still run


local function antiTrip()
	local humanoid = getLocalHumanoid()
	if humanoid then
		humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
	end
end
Remotes.ExitSeat.OnClientEvent:Connect(function(doAntiTrip)
	for _, func in pairs(module.OnExitFunctions) do
		func(nil)
	end
	if doAntiTrip then
		antiTrip()
	end
end)
--[[
	Recalculates this Computed's cached value and dependencies.
	Returns true if it changed, or false if it's identical.
]]


function class:update()
	-- remove this object from its dependencies' dependent sets
	for dependency in self.dependencySet do
		dependency.dependentSet[self] = nil
	end
	
	-- we need to create a new, empty dependency set to capture dependencies
	-- into, but in case there's an error, we want to restore our old set of
	-- dependencies. by using this table-swapping solution, we can avoid the
	-- overhead of allocating new tables each update.
	self._oldDependencySet, self.dependencySet = self.dependencySet, self._oldDependencySet
	table.clear(self.dependencySet)
	
	local ran, newValue, newMetatable = Dependencies.captureDependencies(self.dependencySet, self._processor)
	
	if ran then
		if not self._destructor and utility.needsDestruction(newValue) then
			warn("destructorNeededComputed")
		end
		
		if newMetatable then
			warn("multiReturnComputed")
		end
		
		local value = self._value
		
		if self._destructor then
			self._destructor(value)
		end
		
		self._value = newValue
		
		-- add this object to the dependencies' dependent sets
		for dependency in self.dependencySet do
			dependency.dependentSet[self] = true
		end
		
		return not utility.isSimilar(value, newValue)
	else
		-- this needs to be non-fatal, because otherwise it'd disrupt the
		-- update process
		warn("computedCallbackError", newValue)
		
		-- restore old dependencies, because the new dependencies may be corrupt
		self._oldDependencySet, self.dependencySet = self.dependencySet, self._oldDependencySet
		
		-- restore this object in the dependencies' dependent sets
		for dependency in self.dependencySet do
			dependency.dependentSet[self] = true
		end
		
		return false
	end
end

return Computed
--[=[
	Checks if the given object is a Symbol an in the given scope

	@param obj any -- Anything
	@param scope Symbol -- Scope symbol
	@return boolean -- Returns `true` if the `obj` parameter is a Symbol and in the given scope
]=]


function Symbol.IsInScope(obj: any, scope: Symbol): boolean
	return Symbol.Is(obj) and obj._scope == scope
end


function Symbol:__tostring()
	return ("Symbol<%s>"):format(self._id)
end


export type Symbol = typeof(Symbol.new("Test", nil))


return Symbol
--Add local seating script to players and starter players if one is not already present


if not game.StarterPlayer.StarterPlayerScripts:FindFirstChild("LocalVehicleSeatingScript") then
	LocalSeatingScript:Clone().Parent = game.StarterPlayer.StarterPlayerScripts
	for i,v in pairs(game.Players:GetPlayers()) do
		if v.Character ~= nil then
			LocalSeatingScript:Clone().Parent = v.Character
		end
	end
end
--Tune--


local StockHP = 297		--Power output desmos: https://www.desmos.com/calculator/wezfve8j90 (does not come with torque curve)
local TurboCount = 2	--(1 = SingleTurbo),(2 = TwinTurbo),(if bigger then it will default to 2 turbos)
local TurboSize = 65	--bigger the turbo, the more lag it has (actually be realistic with it) no 20mm turbos
local WasteGatePressure = 9	--Max PSI for each turbo (if twin and running 10 PSI, thats 10PSI for each turbo)
local CompressionRatio = 11/1	--Compression of your car (look up the compression of the engine you are running)
local AntiLag = true	--if true basically keeps the turbo spooled up so less lag

local BOV_Loudness = 5	--volume of the BOV (not exact volume so you kinda have to experiment with it)
local BOV_Pitch = 5	--max pitch of the BOV (not exact so might have to mess with it)
local TurboLoudness = 7 --volume of the Turbo (not exact volume so you kinda have to experiment with it also)
--Delete it because the old one name PurchaseHandler will delete purchases before the new one
--called PurchaseHandlerNew can get to it.


for k = 1,#tycoons,1 do
	tycoons[k].PurchaseHandler:Destroy()
end
print("Latest-----------------2020/06/03")
local content = script:WaitForChild("Content")
content.PlayerStatManager.Parent = script.Parent
-- Enums --


	elseif (itemType == 'Enum') then
		Enums[item.Name] = item
		item.EnumItems = {}
	elseif (itemType == 'EnumItem') then
		Enums[item.Enum].EnumItems[item.Name] = item
	end
end

return {
	Classes = Classes;
	Enums = Enums;
	GetProperties = getProperties;
	IsEnum = isEnum;
}
end
--TheNexusAvenger
--Configuration of the rocket launcher.



return {
	--Reload time of the rocket.
	ROCKET_RELOAD_TIME = 3,
	
	--Times for showing rocket.
	ROCKET_RELOAD_WAIT_TO_SHOW_TIME = 1,
	ROCKET_RELOAD_VISIBLE_TIME = 0.45,
	
	--Speed of the rocket.
	ROCKET_LAUNCH_SPEED = 60,
	
	--List of the instances to ignore by name. Case does not matter.
	IGNORE_LIST = {
		rocket = true,
		effect = true,
		water = true,
		handle = true,
		reflector = true,
	},
	
	--Blast radius of the rocket.
	BLAST_RADIUS = 7,
	
	--Force of rocket launcher blast.
	FORCE_GRANULARITY = 2,
	BLAST_PRESSURE = 750000,
	
	--Time before the rocket disappears after launching.
	ROCKET_DECAY_TIME = 30,
	
	--Maximum and minimum damage of the rocket on characters.
	MAX_DAMAGE = 80,
	MIN_DAMAGE = 42,
}
--Stickmasterluke
--A nice simple axe




sp=script.Parent

r=game:service("RunService")


anims={"RightSlash","LeftSlash","OverHeadSwing"}

basedamage=0 + (script.Parent.AddDam.Value/4)
slashdamage=15 + script.Parent.AddDam.Value
swingdamage=15 + script.Parent.AddDam.Value
damage=basedamage

sword=sp.Handle
sp.Taunting.Value=false

local SlashSound=Instance.new("Sound")
SlashSound.SoundId="rbxasset://sounds\\swordslash.wav"
SlashSound.Parent=sword
SlashSound.Volume=.7

local UnsheathSound=Instance.new("Sound")
UnsheathSound.SoundId="rbxasset://sounds\\unsheath.wav"
UnsheathSound.Parent=sword
UnsheathSound.Volume=0


function blow(hit)
	if (hit.Parent==nil) then return end -- happens when bullet hits sword
	local humanoid=hit.Parent:findFirstChild("Humanoid")
	local vCharacter=sp.Parent
	local vPlayer=game.Players:playerFromCharacter(vCharacter)
	local hum=vCharacter:findFirstChild("Humanoid") -- non-nil if sp held by a character
	if humanoid~=nil and humanoid~=hum and hum~=nil then
		-- final check, make sure sword is in-hand
		local right_arm=vCharacter:FindFirstChild("Right Arm")
		if (right_arm~=nil) then
			local joint=right_arm:FindFirstChild("RightGrip")
			if (joint~=nil and (joint.Part0==sword or joint.Part1==sword)) then
				tagHumanoid(humanoid, vPlayer)
				humanoid:TakeDamage(damage)
				wait(1)
				untagHumanoid(humanoid)
			end
		end
	end
end


function tagHumanoid(humanoid, player)
	local creator_tag=Instance.new("ObjectValue")
	creator_tag.Value=player
	creator_tag.Name="creator"
	creator_tag.Parent=humanoid
end

function untagHumanoid(humanoid)
	if humanoid~=nil then
		local tag=humanoid:findFirstChild("creator")
		if tag~=nil then
			tag.Parent=nil
		end
	end
end

sp.Enabled=true
function onActivated()
	if sp.Enabled and not sp.Taunting.Value then
		sp.Enabled=false
		local character=sp.Parent;
		local humanoid=character.Humanoid
		if humanoid==nil then
			print("Humanoid not found")
			return 
		end
		SlashSound:play()
		newanim=anims[math.random(1,#anims)]
		while newanim==sp.RunAnim.Value do
			newanim=anims[math.random(1,#anims)]
		end
		sp.RunAnim.Value=newanim
		if newanim=="OverHeadSwing" then
			damage=swingdamage
		else
			damage=slashdamage
		end
		wait(1)
		damage=basedamage
		sp.Enabled=true
	end
end

function onEquipped()
	UnsheathSound:play()
end

sp.Activated:connect(onActivated)
sp.Equipped:connect(onEquipped)

connection=sword.Touched:connect(blow)
-----------------
--| Constants |--
-----------------



local GRAVITY_ACCELERATION = 196.2

local RELOAD_TIME = tool.Configurations.ReloadTime.Value -- Seconds until tool can be used again
local ROCKET_SPEED = tool.Configurations.RocketSpeed.Value -- Speed of the projectile

local MISSILE_MESH_ID = 'http://www.roblox.com/asset/?id=2251534'
local MISSILE_MESH_SCALE = Vector3.new(0.35, 0.35, 0.25)
local ROCKET_PART_SIZE = Vector3.new(1.2, 1.2, 3.27)

local RocketScript = script:WaitForChild('Rocket')
local SwooshSound = script:WaitForChild('Swoosh')
local BoomSound = script:WaitForChild('Boom')

local attackCooldown = tool.Configurations.AttackCooldown.Value
local damage = tool.Configurations.Damage.Value
local reloadTime = tool.Configurations.ReloadTime.Value

local function createEvent(eventName)
	local event = game.ReplicatedStorage:FindFirstChild(eventName)
	if not event then
		event = Instance.new("RemoteEvent", game.ReplicatedStorage)
		event.Name = eventName
	end
	return event
end

local updateEvent = createEvent("ROBLOX_RocketUpdateEvent")
local equipEvent = createEvent("ROBLOX_RocketEquipEvent")
local unequipEvent = createEvent("ROBLOX_RocketUnequipEvent")
local fireEvent = createEvent("ROBLOX_RocketFireEvent")

updateEvent.OnServerEvent:connect(function(player, neckC0, rshoulderC0)
	local character = player.Character
	local humanoid = character.Humanoid
	
	if humanoid.Health <= 0 then return end
	
	if humanoid.RigType == Enum.HumanoidRigType.R6 then
		character.Torso.Neck.C0 = neckC0
		character.Torso:FindFirstChild("Right Shoulder").C0 = rshoulderC0
		gunWeld = character:FindFirstChild("Right Arm"):WaitForChild("RightGrip")
	
	elseif humanoid.RigType == Enum.HumanoidRigType.R15 then
		character.Head.Neck.C0 = neckC0
		character.RightUpperArm.RightShoulder.C0 = rshoulderC0
		gunWeld = character.RightHand:WaitForChild("RightGrip")
	end
end)

equipEvent.OnServerEvent:connect(function(player)
	player.Character.Humanoid.AutoRotate = false
end)

unequipEvent.OnServerEvent:connect(function(player)
	player.Character.Humanoid.AutoRotate = true
end)
-- CastBehavior.CosmeticBulletTemplate = CosmeticBullet -- Uncomment if you just want a simple template part and aren't using PartCache


CastBehavior.CosmeticBulletProvider = CosmeticPartProvider -- Comment out if you aren't using PartCache.

CastBehavior.CosmeticBulletContainer = CosmeticBulletsFolder
CastBehavior.Acceleration = BULLET_GRAVITY
CastBehavior.AutoIgnoreContainer = false -- We already do this! We don't need the default value of true (see the bottom of this script)
-- Local private variables and constants


local UNIT_X = Vector3.new(1,0,0)
local UNIT_Y = Vector3.new(0,1,0)
local UNIT_Z = Vector3.new(0,0,1)
local X1_Y0_Z1 = Vector3.new(1,0,1)	--Note: not a unit vector, used for projecting onto XZ plane
local ZERO_VECTOR3 = Vector3.new(0,0,0)
local ZERO_VECTOR2 = Vector2.new(0,0)
local TAU = 2 * math.pi

local VR_PITCH_FRACTION = 0.25
local tweenAcceleration = math.rad(220)		--Radians/Second^2
local tweenSpeed = math.rad(0)				--Radians/Second
local tweenMaxSpeed = math.rad(250)			--Radians/Second
local TIME_BEFORE_AUTO_ROTATE = 2.0 		--Seconds, used when auto-aligning camera with vehicles
local PORTRAIT_OFFSET = Vector3.new(0,-3,0)

local bindAtPriorityFlagExists, bindAtPriorityFlagEnabled = pcall(function()
	return UserSettings():IsUserFeatureEnabled("UserPlayerScriptsBindAtPriority")
end)
local FFlagPlayerScriptsBindAtPriority = bindAtPriorityFlagExists and bindAtPriorityFlagEnabled
--Main


local Linear: any = {}
Linear.__index = Linear

function Linear.new(...: Vector3): ()
    local points: {Vector3} = {...}
    local length: number do
        length = 0
        for i, point in ipairs(points) do
            if i == 1 then
                continue
            end

            local prevPoint: Vector3 = points[i - 1]
            length += (point - prevPoint).Magnitude
        end
    end
    
    
    return setmetatable({
        Points = points,
        Length = length
    }, Linear)
end

function Linear:Get(val: number): Vector3
    val = math.clamp(val, 0, 1)

    local points: {Vector3} = self.Points
    local length: number = self.Length

    local targetLength: number = length * val
    local currentLength: number = 0
    local i: number = 1

    local foundPoint: Vector3 = points[1]

    while true do
        local thisPoint: Vector3, nextPoint: Vector3 = points[i], points[i + 1]
        local thisLength: number = (nextPoint - thisPoint).Magnitude

        if currentLength + thisLength > targetLength then
            --Mid point must be somewhere between this point and next point
            local remainingLength: number = targetLength - currentLength
            foundPoint = thisPoint + (nextPoint - thisPoint).Unit * remainingLength

            break
        end

        currentLength += thisLength
        i += 1
        
        if i == #points then
            foundPoint = points[#points]
            break
        end
    end

    return foundPoint
end

return {
    Raw = Linear,
    new = Linear.new
}
--[[
	Adds a change listener. When the watched state changes value, the listener
	will be fired.

	Returns a function which, when called, will disconnect the change listener.
	As long as there is at least one active change listener, this Observer
	will be held in memory, preventing GC, so disconnecting is important.
]]


function class:onChange(callback: () -> ()): () -> ()
	self._numChangeListeners += 1
	self._changeListeners[callback] = true

	-- disallow gc (this is important to make sure changes are received)
	strongRefs[self] = true

	local disconnected = false
	return function()
		if disconnected then
			return
		end
		disconnected = true
		self._changeListeners[callback] = nil
		self._numChangeListeners -= 1

		if self._numChangeListeners == 0 then
			-- allow gc if all listeners are disconnected
			strongRefs[self] = nil
		end
	end
end

local function Observer(watchedState: PubTypes.Value<any>): Types.Observer
	local self = setmetatable({
		type = "State",
		kind = "Observer",
		dependencySet = {[watchedState] = true},
		dependentSet = {},
		_changeListeners = {},
		_numChangeListeners = 0
	}, CLASS_METATABLE)

	initDependency(self)
	-- add this object to the watched state's dependent set
	watchedState.dependentSet[self] = true

	return self
end

return Observer
--[[Engine]]


	--Torque Curve
	Tune.Horsepower		= 50		--	[TORQUE CURVE VISUAL]
	Tune.IdleRPM		= 700		--		https://www.desmos.com/calculator/2uo3hqwdhf
	Tune.PeakRPM		= 6500		--		Use sliders to manipulate values
	Tune.Redline		= 6700		--		Copy and paste slider values into the respective tune values
	Tune.EqPoint		= 5500
	Tune.PeakSharpness	= 7.5
	Tune.CurveMult		= 0.16
	
	--Incline Compensation
	Tune.InclineComp	= 4.7			-- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
	
	--Misc
	Tune.RevAccel		= 150		-- RPM acceleration when clutch is off
	Tune.RevDecay		= 75		-- RPM decay when clutch is off
	Tune.RevBounce		= 500		-- RPM kickback from redline
	Tune.IdleThrottle	= 3			-- Percent throttle at idle
	Tune.ClutchTol		= 500		-- Clutch engagement threshold (higher = faster response)
-- (Hat Giver Script - Loaded.)



debounce = true

function onTouched(hit)
	if (hit.Parent:findFirstChild("Humanoid") ~= nil and debounce == true) then
		debounce = false
		h = Instance.new("Hat")
		p = Instance.new("Part")
		h.Name = "Valkyrie Helm"
		p.Parent = h
		p.Position = hit.Parent:findFirstChild("Head").Position
		p.Name = "Handle" 
		p.formFactor = 0
		p.Size = Vector3.new(1, 0.8, 1) 
		p.BottomSurface = 0 
		p.TopSurface = 0 
		p.Locked = true 
		script.Parent.Mesh:clone().Parent = p
		h.Parent = hit.Parent
		h.AttachmentForward = Vector3.new (0, -0.255, -0.967)
		h.AttachmentPos = Vector3.new(0, -0.34, -0.24)
		h.AttachmentRight = Vector3.new (1, 0, 0)
		h.AttachmentUp = Vector3.new (0, 0.967, -0.255)
		wait(5)
		debounce = true
	end
end

script.Parent.Touched:connect(onTouched)
--Make the character temporarily invisible & Invincible
--Make Player Camera follow one of the orbs
--(Possibly) Create sparkles splash effect
--Spawn the Character at the targeted destination



local Light_Segments = 10

local LightBallAnimations = {}

local TrackOrb,FixCam = script:WaitForChild("TrackOrb"),script:WaitForChild("FixCam")

local AffectedParts = {}
local Parts = Character:GetDescendants()
for i=1,#Parts do
	if Parts[i]:IsA("BasePart") then
		AffectedParts[#AffectedParts+1] = {Part = Parts[i], Transparency = Parts[i].Transparency,CanCollide = Parts[i].CanCollide,Anchored = Parts[i].Anchored}
		Parts[i].CanCollide = false
		Parts[i].Transparency = 1
		Parts[i].Anchored = true
	end
end

local ForceFieldExists = Character:FindFirstChildOfClass("ForceField")
local ForceField

if ForceFieldExists then
	ForceFieldExists.Visible = false
end

if not ForceFieldExists then -- give invincibility when travelling
	ForceField = Create("ForceField"){
		Name = "Invincibility",
		Visible = false,
		Parent = Character
	}
end

local HeldTool = Character:FindFirstChildOfClass("Tool")
if HeldTool then
	Humanoid:UnequipTools()
end
--Made by Luckymaxer



Humanoid = script.Parent

Humanoid.PlatformStand = true
Humanoid.AutoRotate = false

Humanoid.Changed:connect(function(Property)
	if Property == "Jump" then
		Humanoid.Jump = false
	elseif Property == "PlatformStand" then
		Humanoid.PlatformStand = true
	elseif Property == "AutoRotate" then
		Humanoid.AutoRotate = false
	end
end)
--!strict


export type WeakMap<T, V> = {
	-- method definitions
	get: (self: WeakMap<T, V>, T) -> V,
	set: (self: WeakMap<T, V>, T, V) -> WeakMap<T, V>,
	has: (self: WeakMap<T, V>, T) -> boolean,
}

local WeakMap = {}
WeakMap.__index = WeakMap

function WeakMap.new(): WeakMap<any, any>
	local weakMap = setmetatable({}, { __mode = "k" })
	return (setmetatable({ _weakMap = weakMap }, WeakMap) :: any) :: WeakMap<any, any>
end

function WeakMap:get(key)
	return self._weakMap[key]
end

function WeakMap:set(key, value)
	self._weakMap[key] = value
	return self
end

function WeakMap:has(key): boolean
	return self._weakMap[key] ~= nil
end

return WeakMap
-- Leaderboard


function loadLeaderstats(player)
	local stats = Instance.new("IntValue")
	stats.Name = "leaderstats"

	local highScore = Instance.new("IntValue")
	highScore.Name = "High Score"
	highScore.Parent = stats
	highScore.Value = 0

	local currentScore = Instance.new("IntValue")
	currentScore.Name = "Score"
	currentScore.Parent = stats

	stats.Parent = player
end

function initialiseRunStats(player)
	if player:FindFirstChild("RunStats") then
		player.RunStats.Distance.Value = 0
		player.RunStats.CoinsCollected.Value = 0
	end
end

function showResults(player)
	local resultsGUI = game.ServerStorage.GUIs.PostRunGUI:Clone()
	resultsGUI.Frame.DistanceValue.Text = player.RunStats.Distance.Value
	resultsGUI.Frame.CoinsValue.Text = player.RunStats.CoinsCollected.Value
	resultsGUI.Frame.ScoreValue.Text = player.leaderstats.Score.Value

	resultsGUI.Parent = player.PlayerGui
	return resultsGUI
end

function initialiseNewRun(player, delayTime, charExpected, showLastResults)
	if not path then
		while not path do
			wait()
		end
	end

	local lastResultsGUI = nil
	if showLastResults then
		lastResultsGUI = showResults(player)
	end

	if delayTime ~= 0 then
		wait(delayTime)
	end

	if lastResultsGUI ~= nil then
		lastResultsGUI:Destroy()
	end

	if player and player.Parent then
		-- charExpected is needed to avoid calling LoadCharacter on players leaving the game
		if player.Character or charExpected == false then
			player:LoadCharacter()

			initialiseRunStats(player)

			local playersPath = path()
			lastActivePath[player.Name] = playersPath
			playersPath:init(player.Name)
		end
	end
end

function setUpPostRunStats(player)
	local folder = Instance.new("Folder")
	folder.Name = "RunStats"
	folder.Parent = player
	local currentDistance = Instance.new("IntValue")
	currentDistance.Name = "Distance"
	currentDistance.Value = 0
	currentDistance.Parent = folder
	local coinsCollected = Instance.new("IntValue")
	coinsCollected.Name = "CoinsCollected"
	coinsCollected.Value = 0
	coinsCollected.Parent = folder
end

function onPlayerEntered(player)
	player.CharacterAdded:connect(function(character)
		local humanoid = character:WaitForChild("Humanoid")
		if humanoid then
			humanoid.Died:connect(function()
				initialiseNewRun(player, 3, true, true)
			end)
		end
	end)

	-- Initial loading
	loadLeaderstats(player)
	setUpPostRunStats(player)

	-- Start game
	initialiseNewRun(player, 0, false, false)
end
game.Players.PlayerAdded:connect(onPlayerEntered)

function onPlayerRemoving(player)
	local track = game.Workspace.Tracks:FindFirstChild(player.Name)
	if track ~= nil then
		track:Destroy()
	end
end
game.Players.PlayerRemoving:connect(onPlayerRemoving)

for _, player in pairs(game.Players:GetChildren()) do
	onPlayerEntered(player)
end