Okay, let's create a comprehensive round system with intermission, voting, tag gameplay, leaderstats, currency, and UI.
This will be a server-side script, likely placed in ServerScriptService.
Prerequisites:
- Maps Folder: In
ServerStorage, create a folder named Maps. Place your map models inside this folder. Each map model must contain two parts (or models/folders) named exactly TaggerSpawn and RunnerSpawn. You can put multiple of these in a map, the script will pick one randomly. These parts can be invisible and non-collidable.
- RemoteEvents: In
ReplicatedStorage, create a folder named Remotes. Inside Remotes, create two RemoteEvent objects: VoteCast and UpdateGameStatus.
- UI: You'll need client-side UI scripts and ScreenGuis for:
- Displaying the round status and timer.
- Displaying voting options and allowing players to vote (sending votes via the
VoteCast RemoteEvent).
- (Optional but recommended) Displaying coins and wins leaderstats.
- (The Billboard GUI will be handled by the server script spawning them on characters).
Server Script (in ServerScriptService):
--!strict
-- Services
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Lighting = game:GetService("Lighting")
local ServerScriptService = game:GetService("ServerScriptService")
-- Folders and RemoteEvents
local MapsFolder = ServerStorage:FindFirstChild("Maps")
local RemotesFolder = ReplicatedStorage:FindFirstChild("Remotes")
local VoteCastEvent = RemotesFolder:FindFirstChild("VoteCast")
local UpdateGameStatusEvent = RemotesFolder:FindFirstChild("UpdateGameStatus")
-- Configuration
local INTERMISSION_TIME = 15 -- seconds
local VOTING_TIME = 15 -- seconds
local ROUND_TIME = 180 -- seconds (3 minutes)
local WINNER_COINS = 500
local TAGGER_COINS_PER_TAG = 100
local MAP_CLEANUP_NAME = "CurrentMap" -- Name given to the map model in Workspace
local BILLBOARD_GUI_NAME = "RoleBillboard" -- Name for the billboard GUI
-- Game State Variables
local Status: string = "Waiting"
local TimeLeft: number = 0
local PlayersInGame: {Player} = {} -- Players currently active in the round
local TagPeople: {Player} = {} -- Players who are currently taggers
local RunnerPeople: {Player} = {} -- Players who are currently runners
local OriginalTagger: Player? = nil -- The player who started as the sole tagger
local CurrentMap: Model? = nil
local MapVotes: {[string]: number} = {} -- Stores votes for each map name
-- Ensure necessary components exist
if not MapsFolder then warn("ServerStorage does not contain a 'Maps' folder!"); return end
if not RemotesFolder then warn("ReplicatedStorage does not contain a 'Remotes' folder!"); return end
if not VoteCastEvent then warn("ReplicatedStorage/Remotes does not contain a 'VoteCast' RemoteEvent!"); return end
if not UpdateGameStatusEvent then warn("ReplicatedStorage/Remotes does not contain an 'UpdateGameStatus' RemoteEvent!"); return end
-- --- Helper Functions ---
local function CreateLeaderstats(player: Player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local wins = Instance.new("IntValue")
wins.Name = "Wins"
wins.Value = 0
wins.Parent = leaderstats
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Value = 0
coins.Parent = leaderstats
end
local function FindSpawnPoint(mapModel: Model, spawnType: "TaggerSpawn" | "RunnerSpawn"): CFrame?
local spawns = {}
for _, child in ipairs(mapModel:GetDescendants()) do
if child.Name == spawnType and child:IsA("BasePart") then
table.insert(spawns, child.CFrame)
end
end
if #spawns > 0 then
return spawns[math.random(1, #spawns)]
end
return nil
end
local function TeleportPlayerToSpawn(player: Player, spawnType: "TaggerSpawn" | "RunnerSpawn")
if not player or not player.Character or not CurrentMap then return end
local spawnCFrame = FindSpawnPoint(CurrentMap, spawnType)
if spawnCFrame then
local character = player.Character
-- Attempt to move the character using HumanoidRootPart or PrimaryPart
if character.PrimaryPart then
character.PrimaryPart.CFrame = spawnCFrame
elseif character:FindFirstChild("HumanoidRootPart") then
character.HumanoidRootPart.CFrame = spawnCFrame
end
else
warn("Could not find spawn point of type:", spawnType, "on map:", CurrentMap.Name)
-- Fallback: send to lobby/random location if needed
end
end
local function CleanUpMap()
local oldMap = Workspace:FindFirstChild(MAP_CLEANUP_NAME)
if oldMap then
oldMap:Destroy()
end
end
local function LoadMap(mapName: string): Model?
local mapTemplate = MapsFolder:FindFirstChild(mapName)
if mapTemplate and mapTemplate:IsA("Model") then
CleanUpMap() -- Clean up any existing map
local newMap = mapTemplate:Clone()
newMap.Name = MAP_CLEANUP_NAME
newMap.Parent = Workspace
CurrentMap = newMap
print("Loaded map:", mapName)
return newMap
else
warn("Map template not found or is not a model:", mapName)
CurrentMap = nil
return nil
end
end
local function CreateBillboardGUI(player: Player, isTagger: boolean)
local character = player.Character
if not character then return end
local head = character:FindFirstChild("Head")
if not head then return end
-- Remove existing GUI if it exists
local existingGui = head:FindFirstChild(BILLBOARD_GUI_NAME)
if existingGui then
existingGui:Destroy()
end
local billboardGui = Instance.new("BillboardGui")
billboardGui.Name = BILLBOARD_GUI_NAME
billboardGui.Size = UDim2.new(2, 0, 1, 0)
billboardGui.StudsOffset = Vector3.new(0, 1.5, 0)
billboardGui.AlwaysOnTop = true
billboardGui.MaxDistance = 50 -- Only visible up to 50 studs
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0)
textLabel.BackgroundColor3 = isTagger and Color3.fromRGB(255, 0, 0) or Color3.fromRGB(0, 0, 255) -- Red for Tagger, Blue for Runner
textLabel.BackgroundTransparency = 0.5
textLabel.TextScaled = true
textLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
textLabel.TextStrokeTransparency = 0
textLabel.Font = Enum.Font.SourceSansBold
textLabel.Text = isTagger and "TAGGER" or "RUNNER"
textLabel.Parent = billboardGui
billboardGui.Parent = head
end
local function RemoveBillboardGUI(player: Player)
local character = player.Character
if character then
local head = character:FindFirstChild("Head")
if head then
local existingGui = head:FindFirstChild(BILLBOARD_GUI_NAME)
if existingGui then
existingGui:Destroy()
end
end
end
end
local function IsPlayerInList(player: Player, list: {Player}): boolean
for _, p in ipairs(list) do
if p == player then
return true
end
end
return false
end
local function RemovePlayerFromList(player: Player, list: {Player}): {Player}
local newList = {}
for _, p in ipairs(list) do
if p ~= player then
table.insert(newList, p)
end
end
return newList
end
local function GiveRewards(winnerType: "Runners" | "OriginalTagger")
print("Giving rewards. Winner type:", winnerType)
if winnerType == "Runners" then
-- All current runners win
for _, player in ipairs(RunnerPeople) do
if IsPlayerInList(player, PlayersInGame) then -- Ensure player is still in game
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
local wins = leaderstats:FindFirstChild("Wins")
local coins = leaderstats:FindFirstChild("Coins")
if wins and coins then
wins.Value += 1
coins.Value += WINNER_COINS
print(player.Name, "wins as Runner! Awarded 1 Win and", WINNER_COINS, "Coins.")
end
end
end
end
elseif winnerType == "OriginalTagger" and OriginalTagger then
-- Only the original tagger wins
if IsPlayerInList(OriginalTagger, PlayersInGame) then -- Ensure original tagger is still in game
local leaderstats = OriginalTagger:FindFirstChild("leaderstats")
if leaderstats then
local wins = leaderstats:FindFirstChild("Wins")
if wins then
wins.Value += 1
print(OriginalTagger.Name, "wins as Original Tagger! Awarded 1 Win.")
-- Coins were awarded per tag during the round
end
end
end
end
end
local function ResetRound()
print("Resetting round...")
PlayersInGame = {}
TagPeople = {}
RunnerPeople = {}
OriginalTagger = nil
MapVotes = {}
-- Remove Billboard GUIs from all players
for _, player in ipairs(Players:GetPlayers()) do
RemoveBillboardGUI(player)
end
CleanUpMap() -- Remove the map
CurrentMap = nil
end
local function HandleTag(taggerCharacter: Model, taggedCharacter: Model)
local taggerPlayer = Players:GetPlayerFromCharacter(taggerCharacter)
local taggedPlayer = Players:GetPlayerFromCharacter(taggedCharacter)
if not taggerPlayer or not taggedPlayer then return end -- Both players must be valid
-- Check if the tagger is a current tagger and the tagged is a current runner
if IsPlayerInList(taggerPlayer, TagPeople) and IsPlayerInList(taggedPlayer, RunnerPeople) then
print(taggerPlayer.Name, "tagged", taggedPlayer.Name)
-- Move tagged player from Runners to Taggers list
RunnerPeople = RemovePlayerFromList(taggedPlayer, RunnerPeople)
table.insert(TagPeople, taggedPlayer)
-- Update the tagged player's Billboard GUI
CreateBillboardGUI(taggedPlayer, true)
-- Give the tagger player coins
local leaderstats = taggerPlayer:FindFirstChild("leaderstats")
if leaderstats then
local coins = leaderstats:FindFirstChild("Coins")
if coins then
coins.Value += TAGGER_COINS_PER_TAG
print(taggerPlayer.Name, "earned", TAGGER_COINS_PER_TAG, "coins for tagging.")
end
end
-- Check win condition: Have all runners been tagged?
if #RunnerPeople == 0 then
print("All runners tagged! Round ends.")
GiveRewards("OriginalTagger") -- The original tagger wins
Status = "Intermission" -- End the round
TimeLeft = INTERMISSION_TIME -- Start intermission timer
end
end
end
-- Connect Touched event for tagging detection
local function SetupCharacterTagging(character: Model)
local humanoid = character:FindFirstChildOfClass("Humanoid")
local rootPart = character:FindFirstChild("HumanoidRootPart")
if not humanoid or not rootPart then return end
-- Simple debounce for tagging
local lastTagTime = 0
local TAG_DEBOUNCE = 1 -- seconds
local connection = rootPart.Touched:Connect(function(hit: BasePart)
if Status ~= "Round" then return end -- Only allow tagging during the round
local otherCharacter = hit.Parent
if otherCharacter and otherCharacter:FindFirstChildOfClass("Humanoid") then
local currentTime = os.clock()
if currentTime - lastTagTime > TAG_DEBOUNCE then
lastTagTime = currentTime
-- Call the central tag handling function
HandleTag(character, otherCharacter)
end
end
end)
-- Clean up connection when character is removed
character.AncestryChanging:Connect(function(_, newParent)
if not newParent then
connection:Disconnect()
end
end)
end
-- --- State Management and Main Loop ---
local function UpdateStatus(newStatus: string, duration: number)
Status = newStatus
TimeLeft = duration
-- Notify clients about status change (for UI)
UpdateGameStatusEvent:FireAllClients(Status, TimeLeft)
print("Status changed to:", Status, "Time:", TimeLeft)
end
local function Intermission()
UpdateStatus("Intermission", INTERMISSION_TIME)
ResetRound() -- Clean up previous round
local maps = MapsFolder:GetChildren()
if #maps == 0 then
warn("No maps found in ServerStorage/Maps!")
UpdateStatus("Waiting", 5) -- Wait a bit and try again
return
end
print("Starting intermission...")
while TimeLeft > 0 and #Players:GetPlayers() < 2 do -- Wait for at least 2 players
UpdateStatus("Waiting for Players", INTERMISSION_TIME) -- Keep showing waiting status
task.wait(1)
TimeLeft -= 1
if #Players:GetPlayers() >= 2 then
TimeLeft = INTERMISSION_TIME -- Reset timer if players join while waiting
UpdateStatus("Intermission", TimeLeft)
end
end
if #Players:GetPlayers() < 2 then
print("Not enough players. Staying in Waiting.")
UpdateStatus("Waiting", 5) -- Stay in waiting if not enough players
return
end
while TimeLeft > 0 do
UpdateStatus("Intermission", TimeLeft)
task.wait(1)
TimeLeft -= 1
end
print("Intermission end. Moving to Voting.")
Voting()
end
local function Voting()
UpdateStatus("Voting", VOTING_TIME)
MapVotes = {} -- Clear previous votes
local maps = MapsFolder:GetChildren()
if #maps == 0 then
warn("No maps available for voting.")
Intermission() -- Go back to intermission
return
end
-- Send map names to clients for voting UI
local mapNames = {}
for _, map in ipairs(maps) do
if map:IsA("Model") then
table.insert(mapNames, map.Name)
MapVotes[map.Name] = 0 -- Initialize vote count
end
end
-- You would fire a RemoteEvent here to a client script to display these options
print("Starting voting...")
while TimeLeft > 0 do
UpdateStatus("Voting", TimeLeft)
task.wait(1)
TimeLeft -= 1
end
-- Tally votes
local winningMapName: string? = nil
local maxVotes = -1
local tiedMaps = {}
for mapName, votes in pairs(MapVotes) do
if votes > maxVotes then
maxVotes = votes
winningMapName = mapName
tiedMaps = {mapName} -- Start a new list of tied maps
elseif votes == maxVotes and maxVotes > 0 then
table.insert(tiedMaps, mapName) -- Add to the list of tied maps
end
end
if maxVotes == 0 or #tiedMaps > 1 then -- No votes or a tie
print("Voting tie or no votes. Selecting random map.")
winningMapName = maps[math.random(1, #maps)].Name -- Pick a random map if tie or no votes
else
print("Voting complete. Winning map:", winningMapName, "with", maxVotes, "votes.")
end
-- Load the selected map
local mapLoaded = LoadMap(winningMapName)
if not mapLoaded then
warn("Failed to load the selected map:", winningMapName, ". Returning to intermission.")
Intermission()
return
end
Round()
end
local function Round()
UpdateStatus("Round", ROUND_TIME)
print("Starting round!")
PlayersInGame = {}
TagPeople = {}
RunnerPeople = {}
OriginalTagger = nil
local currentPlayers = Players:GetPlayers()
if #currentPlayers == 0 or not CurrentMap then
warn("Not enough players or map not loaded for round start.")
Intermission()
return
end
-- Filter players who are ready (e.g., spawned) and add to PlayersInGame
for _, player in ipairs(currentPlayers) do
if player.Character and player.Character:FindFirstChildOfClass("Humanoid") and player.Character:FindFirstChild("HumanoidRootPart") then
table.insert(PlayersInGame, player)
-- Ensure leaderstats exist for all players starting the round
if not player:FindFirstChild("leaderstats") then
CreateLeaderstats(player)
end
-- Connect character added event for this round's players
player.CharacterAdded:Connect(function(character)
if IsPlayerInList(player, PlayersInGame) then -- Only reconnect if player is still in this round
SetupCharacterTagging(character)
-- Re-create billboard if they respawn during the round
if IsPlayerInList(player, TagPeople) then
CreateBillboardGUI(player, true)
elseif IsPlayerInList(player, RunnerPeople) then
CreateBillboardGUI(player, false)
end
end
end)
-- Initial setup
SetupCharacterTagging(player.Character)
end
end
if #PlayersInGame < 2 then
warn("Not enough *valid* players for round start after filtering. Returning to intermission.")
Intermission()
return
end
-- Select initial tagger
local initialTaggerIndex = math.random(1, #PlayersInGame)
OriginalTagger = PlayersInGame[initialTaggerIndex]
table.insert(TagPeople, OriginalTagger)
print("Initial Tagger selected:", OriginalTagger.Name)
-- Assign runners
for i, player in ipairs(PlayersInGame) do
if i ~= initialTaggerIndex then
table.insert(RunnerPeople, player)
end
end
print(#RunnerPeople, "runners assigned.")
-- Teleport players to spawns and set up Billboard GUIs
for _, player in ipairs(PlayersInGame) do
if IsPlayerInList(player, TagPeople) then
TeleportPlayerToSpawn(player, "TaggerSpawn")
CreateBillboardGUI(player, true)
elseif IsPlayerInList(player, RunnerPeople) then
TeleportPlayerToSpawn(player, "RunnerSpawn")
CreateBillboardGUI(player, false)
end
end
-- Start round timer
while TimeLeft > 0 and #PlayersInGame > 0 do -- Round continues as long as there's time and players
UpdateStatus("Round", TimeLeft)
-- Check for win condition early: All runners tagged
if #RunnerPeople == 0 then
print("All runners tagged! Round ends early.")
GiveRewards("OriginalTagger")
TimeLeft = 0 -- End loop
break
end
task.wait(1)
TimeLeft -= 1
end
-- Round ends (either by time or all runners tagged)
if #RunnerPeople > 0 then
print("Round time ran out. Runners win!")
GiveRewards("Runners") -- Runners win if time runs out and some are left
end
-- If #RunnerPeople == 0, the "OriginalTagger" win was handled inside HandleTag
print("Round ended.")
Intermission() -- Go back to intermission
end
-- --- Event Handling ---
-- Leaderstats for new players
Players.PlayerAdded:Connect(CreateLeaderstats)
-- Handle player leaving during a round
Players.PlayerRemoving:Connect(function(playerLeaving: Player)
if IsPlayerInList(playerLeaving, PlayersInGame) then
print(playerLeaving.Name, "left the game during the round.")
PlayersInGame = RemovePlayerFromList(playerLeaving, PlayersInGame)
TagPeople = RemovePlayerFromList(playerLeaving, TagPeople)
RunnerPeople = RemovePlayerFromList(playerLeaving, RunnerPeople)
-- If the original tagger leaves and no runners are left, the round might need special handling
-- or just end naturally if no taggers remain to finish the job.
-- For this simple version, the round might continue or end based on remaining players.
if Status == "Round" then
-- If all taggers leave (and original tagger left), runners automatically win?
-- Or if the last runner leaves, remaining taggers win?
-- Let's keep it simple: The round continues with remaining players.
-- If #TagPeople == 0, no one can tag. If #RunnerPeople == 0, it already ended.
if #TagPeople == 0 and #RunnerPeople > 0 then
-- All taggers left, but runners remain. Runners win.
print("All taggers left. Runners win by default.")
GiveRewards("Runners")
Status = "Intermission"
TimeLeft = INTERMISSION_TIME
elseif #RunnerPeople == 0 then
-- All runners were tagged (or the last one left). Original tagger wins (if they are still in game - handled in GiveRewards)
print("All runners tagged/left. Original Tagger wins.")
GiveRewards("OriginalTagger")
Status = "Intermission"
TimeLeft = INTERMISSION_TIME
elseif #PlayersInGame < 2 then
-- Not enough players to continue the round
print("Not enough players remaining to continue round.")
Intermission()
end
end
end
-- Also remove their billboard just in case
RemoveBillboardGUI(playerLeaving)
end)
-- Handle incoming votes from clients
if VoteCastEvent then
VoteCastEvent.OnServerEvent:Connect(function(player: Player, mapName: string)
if Status == "Voting" then
local maps = MapsFolder:GetChildren()
local validMapNames = {}
for _, map in ipairs(maps) do
if map:IsA("Model") then
table.insert(validMapNames, map.Name)
end
end
if table.find(validMapNames, mapName) then
-- Optional: Prevent players from voting more than once
-- You'd need to track who voted in a table: {[Player]=hasVoted:boolean}
-- For simplicity here, allowing multiple votes from one player, last one counts.
MapVotes[mapName] = (MapVotes[mapName] or 0) + 1
print(player.Name, "voted for", mapName)
-- You might want to update voting UI for all players here
else
warn(player.Name, "attempted to vote for invalid map:", mapName)
end
else
warn(player.Name, "attempted to vote outside of voting phase.")
end
end)
end
-- Initial state setup
task.wait(5) -- Wait a few seconds for players to join
Intermission()
-- Main game loop
while task.wait(1) do -- This loop primarily handles time updates and state transitions
-- Time update is now handled within each state function (Intermission, Voting, Round)
-- to make the logic clearer and allow for conditional state changes (like waiting for players).
-- The state functions call each other to transition.
end
Explanation:
- Services and Setup: Gets necessary Roblox services, defines constants for times and rewards, and sets up initial game state variables. It also checks if the required folders and RemoteEvents exist.
- Leaderstats:
CreateLeaderstats is connected to Players.PlayerAdded to give every new player Wins and Coins.
- Map Handling:
MapsFolder holds your map models in ServerStorage.
FindSpawnPoint looks for parts named "TaggerSpawn" or "RunnerSpawn" within a given map model and returns a random one's CFrame.
TeleportPlayerToSpawn moves a player's character to a spawn point on the CurrentMap.
CleanUpMap removes the previously loaded map from Workspace.
LoadMap clones a map from ServerStorage to Workspace and sets CurrentMap.
- Billboard GUI:
CreateBillboardGUI creates or updates a BillboardGui above the player's head to show "TAGGER" or "RUNNER" with different colors.
RemoveBillboardGUI cleans up the GUI.
- Player Lists:
PlayersInGame, TagPeople, RunnerPeople are simple Lua tables used to track which players are in the current round and their roles. Helper functions IsPlayerInList and RemovePlayerFromList manage these.
- Rewards:
GiveRewards handles incrementing Wins leaderstat and adding Coins based on the winning condition and role.
- Reset:
ResetRound clears all round-specific state variables, removes Billboard GUIs, and cleans up the map.
- Tag Logic:
HandleTag contains the core tag logic: checks if a tagger touched a runner, moves the runner to the tagger list, updates their GUI, awards coins to the tagger, and checks if the round should end because all runners are tagged.
SetupCharacterTagging is called for each player's character at the start of the round (and on respawn). It connects the HumanoidRootPart.Touched event and includes a simple debounce to prevent instant retags. It calls HandleTag when a valid touch occurs. The connection is cleaned up when the character is removed.
How to use:
- Save the script in
ServerScriptService.
- Create the
Maps folder in ServerStorage.
- Create your map models and place them inside the
Maps folder.
- Inside each map model, create parts named
TaggerSpawn and RunnerSpawn where players should spawn for their roles.
- Create the
Remotes folder in ReplicatedStorage.
- Create
RemoteEvent objects named VoteCast and UpdateGameStatus inside the Remotes folder.
- Implement the necessary client-side UI scripts to:
- Display the status and timer received via
UpdateGameStatusEvent.
- Display map options during the "Voting" phase and send the selected map name via
VoteCastEvent when a player votes.
This setup provides a robust foundation for your round-based tag game! Remember to extensively test the tag detection and player leaving scenarios.