Advertisement
WackoMcGoose

What was I on when I wrote this

Aug 18th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.34 KB | None | 0 0
  1. --MainGameLoop.lua
  2. game.Workspace.Remote:WaitForChild("ServerLocal"):WaitForChild("VarsSanCheck"):Fire() --Oh geez I better run this at game start O_O
  3.  
  4. local Const = require(script.Parent.Parent.Constants.Const)
  5. local LibCommon = require(script.Parent.Parent.Lib.LibCommon)
  6. local LibInit = require(script.Parent.Parent.Lib.LibInit)
  7. local LibModel = require(game.Workspace.Lib.LibModel)
  8. local LibString = require(script.Parent.Parent.Lib.LibString)
  9. local Remote = require(script.Parent.Parent.Remote.Remote)
  10. local TrackGeneratorFactory = require(script.Parent.Parent.TrackGenerator.TrackGeneratorFactory)
  11. local Vars = game.Workspace:WaitForChild("Vars")
  12.  
  13.  
  14.  
  15.  
  16. --Important pointers
  17. local announcementText = game.StarterGui.AnnouncerBillboard.BillboardGui.GameStatus
  18. LibInit.gameStateInit()
  19. local gameState = script.Parent.Parent.GameState
  20. local playerLocScript = Const.LocalScripts.PlayerLocator:Clone()
  21. local loadingScreenScript = Const.LocalScripts.LoadingScreen:Clone()
  22. local cameraConfigScript = Const.LocalScripts.RaceCameraConfig:Clone()
  23. local listeners = {}
  24. local themeList = { "Theme_RoArena", "Theme_Desert", "Theme_Jungle", "Theme_Tundra", "Theme_Trollplanet" }
  25.  
  26. --One-time inits
  27. if game.Workspace:FindFirstChild("ArenaStands") == nil then LibModel.regenStands(Vars.FieldSize.Value.x, Vars.FieldSize.Value.z) end
  28.  
  29. --Race running
  30. function raceLogic()
  31.     local finishLine = game.Workspace.CourseModels.FinishLinePointer.Value.trigger_finishline
  32.     local numPlayersFinished = 0
  33.     finishLine.Touched:connect(function(part)
  34.         if part.Name ~= "HumanoidRootPart" then return end
  35.         local player = game.Players:FindFirstChild(part.Parent.Name)
  36.         if player == nil then return end
  37.         local playerData = Const.getRaceDataForPlayer(player)
  38.         if playerData == nil then return end
  39.         if not playerData.IsRacing.Value then return end
  40.         if playerData.CurrentLap.Value < 1 then playerData.CurrentLap.Value = 1 end
  41.         if playerData.CurrentLap.Value > Const.getTrackData().NumLaps.Value then playerData.CurrentLap.Value = Const.getTrackData().NumLaps.Value end
  42.         local nodeCount = #(playerData.VisitedNodes:GetChildren())
  43.         if nodeCount > #(Const.getTrackNodes():GetChildren()) * 0.75 then
  44.             if playerData.CurrentLap.Value == Const.getTrackData().NumLaps.Value then
  45.                 playerData.IsRacing.Value = false
  46.                 playerData.CurrentLap.Value = playerData.CurrentLap.Value + 1 --Needs to go to 4 to trigger the final lap-recording
  47.                 game.Workspace.GameState.PlayersStillRacing:FindFirstChild(player.Name):Remove()
  48.                 numPlayersFinished = numPlayersFinished + 1
  49.                 playerData.FinishPosition.Value = numPlayersFinished
  50.                 playerData.PlayerRaceState.Value = "Finish"
  51.                 updateAnnouncementTextRacerCount()
  52.                 delay(0, function()
  53.                     local kart = player.Character:FindFirstChild(player.Name.."'s Kart")
  54.                     if kart then while kart.VehicleSeat.MaxSpeed > 0 do kart.VehicleSeat.MaxSpeed = kart.VehicleSeat.MaxSpeed - 1 wait() end end
  55.                 end)
  56.             else
  57.                 playerData.CurrentLap.Value = playerData.CurrentLap.Value + 1
  58.                 playerData.VisitedNodes:ClearAllChildren()
  59.             end
  60.             --HUD stuff, this is AFTER lap incrementing.
  61.             if playerData.CurrentLap.Value == Const.getTrackData().NumLaps.Value and playerData.PlayerRaceState.Value ~= "Finish" then
  62.                 playerData.PlayerRaceState.Value = "FinalLap"
  63.             elseif playerData.PlayerRaceState.Value ~= "Finish" then
  64.                 playerData.PlayerRaceState.Value = "Lap"..playerData.CurrentLap.Value
  65.             end
  66.         end
  67.     end)
  68.     local continueRace = true
  69.     --Race-place tracker
  70.     delay(0, function()
  71.         while continueRace do
  72.             local playerTable = game.Workspace.PlayerData:GetChildren()
  73.             local count = #playerTable
  74.             for i = 1, count do
  75.                 local most = playerTable[1].RaceDistance.Value
  76.                 local mostPlayer = playerTable[1].Name
  77.                 local index = 1
  78.                 for j = 1, #playerTable do
  79.                     if playerTable[j].RaceDistance.Value > most then
  80.                         most = playerTable[j].RaceDistance.Value
  81.                         mostPlayer = playerTable[j].Name
  82.                         index = j
  83.                     end
  84.                 end
  85.                 game.Workspace.PlayerData:FindFirstChild(mostPlayer).Position.Value = i
  86.                 table.remove(playerTable, index)
  87.             end
  88.             wait()
  89.         end
  90.     end)
  91.     --Check for players finishing
  92.     game.Workspace.GameState.PlayersStillRacing.ChildRemoved:connect(function()
  93.         pcall(function() if #(game.Workspace.GameState.PlayersStillRacing:GetChildren()) == 0 then continueRace = false end end)
  94.     end)
  95.     while continueRace do wait() end
  96.     --Verify that no players left after crossing finish line, and adjust if necessary
  97.     local playerTable = game.Workspace.PlayerData:GetChildren()
  98.     if #playerTable ~= numPlayersFinished then
  99.         local numPlayers = #playerTable
  100.         for i = 1, numPlayers do
  101.             local leastPlayer = playerTable[1]
  102.             local leastIndex, iterations = 1, 1
  103.             --Get the lowest-numbered-finish player, since the /order/ of finishing is still valid
  104.             for _, player in pairs(playerTable) do
  105.                 if player.FinishPosition.Value < leastPlayer.FinishPosition.Value then leastPlayer = player leastIndex = iterations end
  106.                 iterations = iterations + 1
  107.             end
  108.             leastPlayer.FinishPosition.Value = i
  109.             table.remove(playerTable, leastIndex) --This is valid because playerTable is merely a list of object pointers, not PlayerData directly
  110.         end
  111.         --In theory, the table should now be "compacted"
  112.     end
  113. end
  114.  
  115. function deregisterRacer(player, playerList, playerData)
  116.     --Find the player index, to remove them
  117.     local playerWasRacer = false
  118.     for i = 1, #playerList do if playerList[i] == player then playerWasRacer = true table.remove(playerList, i) break end end
  119.     if playerWasRacer then
  120.         pcall(function() playerData:FindFirstChild(player.Name):Remove() end)
  121.         pcall(function() game.Workspace.GameState.PlayersStillRacing:FindFirstChild(player.Name):Remove() end)
  122.     end
  123.     gameState.RacingPlayerCount.Value = #playerList
  124.     updateAnnouncementTextRacerCount()
  125. end
  126.  
  127. function updateAnnouncementTextRacerCount()
  128.     local playersRacing = #(game.Workspace.GameState.PlayersStillRacing:GetChildren())
  129.     local playersFinished = #(game.Workspace.PlayerData:GetChildren()) - #(game.Workspace.GameState.PlayersStillRacing:GetChildren())
  130.     local racingText, finishText
  131.     if playersRacing == 0 then racingText = "" elseif playersRacing == 1 then racingText = "1 Player is Racing!" else
  132.         racingText = playersRacing.." Players are Racing!" end
  133.     if playersFinished == 0 then finishText = "" elseif playersFinished == 1 then finishText = "\n1 Player has Finished!" else
  134.         finishText = "\n"..playersFinished.." Players have Finished!" end
  135.     announcementText.Text = racingText..finishText
  136. end
  137.  
  138. --Aaaand let's-a-go!
  139. while true do
  140.     --Once-per-race inits
  141.     game.Workspace.Remote:WaitForChild("ServerLocal"):WaitForChild("VarsSanCheck"):Fire()
  142.     LibInit.gameStateInit()
  143.     fieldSize = Vars.FieldSize.Value
  144.     gameState = script.Parent.Parent.GameState
  145.     Remote.setGameState("NotRacing")
  146.     gameState.RacingPlayerCount.Value = 0
  147.     gameState.RacingPlayersPreloaded.Value = 0
  148.     gameState.RacingPlayersSeated.Value = 0
  149.     LibInit.timerStartReset()
  150.     LibInit.trackDataInit(fieldSize.x, fieldSize.z)
  151.     LibInit.regenBaseTiles(fieldSize.x, fieldSize.z)
  152.     listeners = {}
  153.    
  154.     --Wait for playercount to be nonzero
  155.     announcementText.Text = "Waiting for Players..."
  156.     while game.Players.NumPlayers < 1 do wait(1) end
  157.     for i = Vars.TimeBetweenRounds.Value or 15, 0, -1 do
  158.         announcementText.Text = "Intermission ("..i..")"
  159.         wait(1)
  160.     end
  161.     announcementText.Text = "Generating Track..."
  162.     Remote.setGameState("Loading")
  163.     wait(1)
  164.     local success = false
  165.     while not success do
  166.         local didItFailed = false
  167.         success, caught = pcall(function()
  168.             local genseed = math.random(0, 2147483647)
  169.             Vars.WorldSeed.Value = genseed
  170.             Vars.RandomCalls.Value = 0
  171.             Vars.CurrentTheme.Value = themeList[(Vars.NumRaces.Value % #themeList) + 1]
  172.             local generator = TrackGeneratorFactory.getGenerator(Vars.GeneratorName.Value)
  173.             if generator.GeneratorVersion == "Version2" then LibInit.trackgenGuiInit(fieldSize.x, fieldSize.z) end
  174.             announcementText.Text = "Generating Track...\n[ID: "..LibString.encodeNumberAsTrackCode(genseed).."]"
  175.             local oops = generator:generate(genseed)
  176.             generator:model()
  177.             if oops ~= "OK" then
  178.                 return "Generator exploded!"
  179.             end
  180.         end)
  181.         if (not success) or didItFailed then
  182.             print(caught)
  183.             wait(10)
  184.             for k, v in pairs(game.Workspace.BaseTiles:GetChildren()) do v.BrickColor = BrickColor.new("Medium stone grey") end
  185.             pcall(function() game.Workspace.TrackData:Remove() end)
  186.             LibInit.trackDataInit(fieldSize.x, fieldSize.z)
  187.         end
  188.     end
  189.     announcementText.Text = "Track Generated. Starting..."
  190.     Vars.RandomCalls.Value = 0
  191.     wait(1)
  192.    
  193.     --Game start stuff
  194.     --Note: This is the point of no return. Any further players joining after this point, will NOT be in the active race.
  195.     --Also I'm pretty sure Past Me was smart enough to do this already, but: don't do any playercount checks on game.Players directly.
  196.     local playerList = game.Players:GetChildren()
  197.     for _, v in pairs(playerList) do loadingScreenScript:Clone().Parent = v.PlayerGui end
  198.     wait()
  199.     Remote.setGameState("PrepareToStart")
  200.     local _, playerData = LibInit.playerRaceDataInit(playerList)
  201.     require(game.Workspace.CourseModels.FinishLinePointer.Value.KartSpawner).spawnKarts(#playerList)
  202.     --Player race cleanup if exit mid-race
  203.     table.insert(listeners, game.Players.ChildRemoved:connect(function(player) deregisterRacer(player, playerList, playerData) end))
  204.     for _, player in pairs(playerList) do table.insert(listeners, player.CharacterAdded:connect(function() deregisterRacer(player, playerList, playerData) end)) end
  205.     wait(1)
  206.     updateAnnouncementTextRacerCount()
  207.     gameState.RacingPlayerCount.Value = #playerList
  208.     local id = 0
  209.     for k, v in pairs(playerList) do
  210.         pcall(function()
  211.             id = id + 1
  212.             local kart = game.Workspace:FindFirstChild("KartyThing"..id)
  213.             v.Character.HumanoidRootPart.CFrame = kart.VehicleSeat.CFrame
  214.             kart.VehicleSeat.Anchored = true
  215.             delay(0, function()
  216.                 --wait()
  217.                 cameraConfigScript:Clone().Parent = v.Character
  218.                 while not v.Character.Humanoid.Sit do v.Character.Humanoid.Jump = true wait() end
  219.                 gameState.RacingPlayersSeated.Value = gameState.RacingPlayersSeated.Value + 1
  220.                 kart.VehicleSeat.Anchored = false
  221.             end)
  222.             v.Character.Humanoid.WalkSpeed = 0
  223.             v.PlayerGui.AnnouncerBillboard.BillboardGui.GameStatus.Visible = false
  224.             kart.Name = v.Name.."'s Kart"
  225.             kart.Parent = v.Character
  226.             kart.VehicleSeat.MaxSpeed = 0
  227.             Const.LocalScripts.ScoreHud:Clone().Parent = v.PlayerGui.RaceHud.HudFrame
  228.             playerLocScript:Clone().Parent = v.Character
  229.         end)
  230.     end
  231.     --Respawn stands formatted to currently active theme
  232.     game.Workspace.ArenaStands:Destroy()
  233.     LibModel.regenStands(fieldSize.x, fieldSize.z)
  234.     --Player race cleanup if respawned after placed in kart
  235.     for _, player in pairs(playerData:GetChildren()) do player.IsRacing.Value = true end
  236.     local tooLongWaiting = 0
  237.     local loadedPlayers = {}
  238.     local preloaderCon
  239.     preloaderCon = game.Workspace.Remote.ToServer.ClientLoaded.OnServerEvent:connect(function(player) table.insert(loadedPlayers, player) end)
  240.     while gameState.RacingPlayersPreloaded.Value < gameState.RacingPlayerCount.Value
  241.         or gameState.RacingPlayersSeated.Value < gameState.RacingPlayerCount.Value do
  242.             wait(0.1) gameState.RacingPlayersPreloaded.Value = #loadedPlayers
  243.             tooLongWaiting = tooLongWaiting + 1
  244.             if tooLongWaiting >= 100 then game.Workspace.Remote.ToClient.LoadingTimeout:FireAllClients() break end --Ten seconds of loading, 8r8k it already!
  245.     end
  246.     preloaderCon:disconnect()
  247.     for k, v in pairs(game.Workspace:GetChildren()) do if string.sub(v.Name, 1, 10) == "KartyThing" then v:Remove() end end
  248.     gameState.RacingPlayersPreloaded:ClearAllChildren()
  249.     --Fix a thing
  250.     for _, fixDis in pairs(game.Workspace.CourseModels:GetChildren()) do
  251.         if string.sub(fixDis.Name, string.len(fixDis.Name) - 4) == "[1,5]" then
  252.             fixDis.Parent = nil
  253.             wait()
  254.             fixDis.Parent = game.Workspace.CourseModels
  255.         end
  256.     end
  257.     Remote.setGameState("LoadComplete")
  258.     wait(1)
  259.     wait(3)
  260.     Remote.setGameState("GetReady")
  261.     for _, player in pairs(playerData:GetChildren()) do player.PlayerRaceState.Value = "GetReady" end
  262.     wait(2)
  263.     for k, v in pairs(playerList) do
  264.         pcall(function()
  265.             local kart = v.Character:FindFirstChild(v.Name.."'s Kart")
  266.             if kart then kart.VehicleSeat.MaxSpeed = kart.VehicleSeat.NormalMaxSpeed.Value end
  267.         end)
  268.     end
  269.     game.Workspace.GameState.RaceInProgress.Value = true
  270.     Remote.setGameState("Go")
  271.     for _, player in pairs(playerData:GetChildren()) do player.PlayerRaceState.Value = "Go" end
  272.    
  273.     --Go Speed Racer!
  274.     raceLogic()
  275.    
  276.     --End race results
  277.     game.Workspace.GameState.RaceInProgress.Value = false
  278.     announcementText.Text = "Race Over"
  279.     Remote.setGameState("ShowResults")
  280.     for _, v in pairs(playerList) do Const.LocalScripts.RaceResults:Clone().Parent = v.PlayerGui.ResultsScreen end
  281.     wait(1)
  282.     local scoreboardData = LibInit.endRaceResults(playerData)
  283.     wait(8)
  284.    
  285.     --Exploderate players!
  286.     Remote.setGameState("BoomBaby")
  287.     for _, player in pairs(playerList) do
  288.         player.Character:BreakJoints()
  289.         player.Character.PlayerLocator:Remove()
  290.         if player.Character:FindFirstChild(player.Name.."'s Kart"):FindFirstChild("BoundingBox") then
  291.             player.Character:FindFirstChild(player.Name.."'s Kart").BoundingBox:Remove()
  292.         end
  293.         player.PlayerGui.ResultsScreen.BGFrame.Visible = false
  294.         player.PlayerGui.ResultsScreen.ResultsFrame.Visible = false
  295.     end
  296.     game.Players.CharacterAutoLoads = false --<haaaaaaaax>
  297.     delay(3, function() for _, player in pairs(playerList) do player:LoadCharacter() end --Force-respawn all after 3 sec
  298.         wait() game.Players.CharacterAutoLoads = true --</haaaaaaaax>
  299.     end)
  300.    
  301.     --Data cleanup
  302.     wait()
  303.     pcall(function() game.Workspace.TrackData:Remove() playerData:Remove() scoreboardData:Remove() gameState:Remove() end)
  304.     --print("Disconnecting "..#listeners.." listeners")
  305.     for _, v in pairs(listeners) do pcall(function() v:disconnect() end) end listeners = {} --Disconnect all those now-useless listeners
  306.    
  307.     --Model cleanup
  308.     wait(2)
  309.     announcementText.Text = "Cleaning Track..."
  310.     Remote.setGameState("Cleanup")
  311.     wait(2)
  312.     local trackModels = game.Workspace.CourseModels:GetChildren()
  313.     for k, v in pairs(trackModels) do v:Remove() wait() end game.Workspace.CourseModels:Remove()
  314.     for k, v in pairs(game.Workspace.BaseTiles:GetChildren()) do v.BrickColor = BrickColor.new("Medium stone grey") end
  315.     if game.Workspace:FindFirstChild("TrackgenGuiData") ~= nil then game.Workspace.TrackgenGuiData:Remove() end
  316.     Vars.NumRaces.Value = Vars.NumRaces.Value + 1
  317. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement