DEV Community

CyberMax
CyberMax

Posted on Originally published at cybermaxtools.com

A Roblox round system with map voting: one server loop, four phases

Round-based games all share one skeleton: wait, vote, play, pay, repeat. This is that skeleton for Roblox in Luau, with a map vote that validates every ballot and a loop that survives a broken map.

The short version

Run one loop on the server with four phases: Waiting, Voting, Playing and Ended. In Voting, offer three random maps, accept one checked vote per player and end early once everyone has voted. Then clone the winning map from ServerStorage, move players to its spawns, run the timer until one player is left, reward the survivors, destroy the map and start again.

Set it up in Studio

  1. In ServerStorage, add a folder named Maps. Put each map in it as a Model containing a folder Spawns with a few parts.
  2. Keep a lobby in Workspace with a SpawnLocation; players wait and vote there.
  3. In ServerScriptService, add a Script and paste the first block.
  4. In StarterPlayer > StarterPlayerScripts, add a LocalScript and paste the second block for the timer and vote buttons.
  5. Test with two players: in Studio use Test > Start with 2 players, since a round needs at least two.

The code

ServerScriptService/RoundLoop (Script)

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

local MIN_PLAYERS = 2
local VOTE_SECONDS = 15
local ROUND_SECONDS = 120
local END_SECONDS = 6
local OPTIONS = 3
local WIN_COINS = 50

local maps = ServerStorage:WaitForChild("Maps") -- one Model per map, each with a folder "Spawns" of parts
local voteRemote = Instance.new("RemoteEvent")
voteRemote.Name = "MapVote"
voteRemote.Parent = ReplicatedStorage

local rng = Random.new()
local options = {} -- map names on this ballot
local votes = {} -- [player] = map name
local lastMap = nil

-- Clients read these three attributes to draw the timer. No remote needed.
local function publish(phase, seconds, info)
    ReplicatedStorage:SetAttribute("Phase", phase)
    ReplicatedStorage:SetAttribute("EndsAt", workspace:GetServerTimeNow() + (seconds or 0))
    ReplicatedStorage:SetAttribute("Info", info or "")
end

local function pickOptions()
    local all = maps:GetChildren()
    local pool = {}
    for _, map in all do
        if map.Name ~= lastMap or #all <= OPTIONS then -- no repeat of the last map when there are enough maps
            table.insert(pool, map.Name)
        end
    end
    local picked = {}
    while #picked < OPTIONS and #pool > 0 do
        table.insert(picked, table.remove(pool, rng:NextInteger(1, #pool)))
    end
    return picked
end

local function countVotes()
    local count, voters = {}, 0
    for _, name in options do
        count[name] = 0
    end
    for player, name in votes do
        if player.Parent == Players and count[name] then
            count[name] += 1
            voters += 1
        end
    end
    return count, voters
end

local function pickWinner(count)
    local best, leaders = -1, {}
    for _, name in options do
        if count[name] > best then
            best, leaders = count[name], { name }
        elseif count[name] == best then
            table.insert(leaders, name)
        end
    end
    return leaders[rng:NextInteger(1, #leaders)] -- a tie is broken at random
end

voteRemote.OnServerEvent:Connect(function(player, choice)
    if ReplicatedStorage:GetAttribute("Phase") ~= "Voting" then
        return
    end
    if type(choice) ~= "string" or not table.find(options, choice) then
        return -- never trust what a client sends
    end
    votes[player] = choice -- a second vote replaces the first
    voteRemote:FireAllClients("Counts", (countVotes()))
end)

Players.PlayerAdded:Connect(function(player)
    if ReplicatedStorage:GetAttribute("Phase") == "Voting" then
        voteRemote:FireClient(player, "Options", options) -- late joiners still get the ballot
    end
end)

Players.PlayerRemoving:Connect(function(player)
    votes[player] = nil
end)

local function runVote()
    options = pickOptions()
    table.clear(votes)
    publish("Voting", VOTE_SECONDS)
    voteRemote:FireAllClients("Options", options)

    local deadline = os.clock() + VOTE_SECONDS
    while os.clock() < deadline do
        task.wait(0.5)
        local _, voters = countVotes()
        if voters > 0 and voters >= #Players:GetPlayers() then
            break -- everyone has voted: no need to wait out the clock
        end
    end
    return pickWinner((countVotes()))
end

local function alive(list)
    local out = {}
    for _, player in list do
        local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
        if player.Parent == Players and humanoid and humanoid.Health > 0 then
            table.insert(out, player)
        end
    end
    return out
end

local function runRound(mapName)
    local map = maps[mapName]:Clone()
    map.Name = "ActiveMap"
    map.Parent = workspace
    lastMap = mapName

    local spawns = map.Spawns:GetChildren()
    local contestants = Players:GetPlayers()
    for i, player in contestants do
        local spawn = spawns[(i - 1) % #spawns + 1]
        if player.Character then
            player.Character:PivotTo(spawn.CFrame + Vector3.new(0, 4, 0))
        end
    end

    publish("Playing", ROUND_SECONDS, mapName)
    local deadline = os.clock() + ROUND_SECONDS
    while os.clock() < deadline and #alive(contestants) > 1 do
        task.wait(0.5)
    end

    local names = {}
    for _, player in alive(contestants) do
        table.insert(names, player.DisplayName)
        local stats = player:FindFirstChild("leaderstats")
        if stats and stats:FindFirstChild("Coins") then
            stats.Coins.Value += WIN_COINS
        end
    end
    publish("Ended", END_SECONDS, if #names > 0 then table.concat(names, ", ") else "Nobody")
    task.wait(END_SECONDS)

    map:Destroy()
    for _, player in Players:GetPlayers() do
        task.spawn(player.LoadCharacter, player) -- everyone respawns at the lobby SpawnLocation
    end
end

while true do
    if #Players:GetPlayers() < MIN_PLAYERS then
        publish("Waiting")
        task.wait(1)
    else
        local ok, err = pcall(function()
            runRound(runVote())
        end)
        if not ok then
            -- one broken map must not stop the game: clean up and start the next vote
            warn("Round failed, starting again:", err)
            local stuck = workspace:FindFirstChild("ActiveMap")
            if stuck then
                stuck:Destroy()
            end
            task.wait(3)
        end
    end
end
Enter fullscreen mode Exit fullscreen mode

StarterPlayerScripts/RoundHud (LocalScript)

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

local voteRemote = ReplicatedStorage:WaitForChild("MapVote")

local gui = Instance.new("ScreenGui")
gui.Name = "RoundHud"
gui.ResetOnSpawn = false

local label = Instance.new("TextLabel")
label.Size = UDim2.new(0, 320, 0, 36)
label.Position = UDim2.new(0.5, -160, 0, 8)
label.BackgroundTransparency = 0.3
label.TextScaled = true
label.Parent = gui

local row = Instance.new("Frame")
row.Size = UDim2.new(0, 480, 0, 44)
row.Position = UDim2.new(0.5, -240, 0, 52)
row.BackgroundTransparency = 1
row.Parent = gui

local layout = Instance.new("UIListLayout")
layout.FillDirection = Enum.FillDirection.Horizontal
layout.Padding = UDim.new(0, 8)
layout.Parent = row

gui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")

local buttons = {} -- [map name] = TextButton

voteRemote.OnClientEvent:Connect(function(kind, payload)
    if kind == "Options" then
        for _, button in buttons do
            button:Destroy()
        end
        table.clear(buttons)
        for _, name in payload do
            local button = Instance.new("TextButton")
            button.Size = UDim2.new(0, 150, 1, 0)
            button.Text = name
            button.Parent = row
            button.Activated:Connect(function()
                voteRemote:FireServer(name)
            end)
            buttons[name] = button
        end
    elseif kind == "Counts" then
        for name, button in buttons do
            button.Text = name .. " (" .. (payload[name] or 0) .. ")"
        end
    end
end)

while true do
    local phase = ReplicatedStorage:GetAttribute("Phase") or "Waiting"
    local endsAt = ReplicatedStorage:GetAttribute("EndsAt") or 0
    local info = ReplicatedStorage:GetAttribute("Info") or ""
    local left = math.max(0, math.ceil(endsAt - workspace:GetServerTimeNow()))

    row.Visible = phase == "Voting"
    if phase == "Waiting" then
        label.Text = "Waiting for players"
    elseif phase == "Voting" then
        label.Text = "Vote for the next map: " .. left
    elseif phase == "Playing" then
        label.Text = info .. ": " .. left
    else
        label.Text = "Winner: " .. info
    end
    task.wait(0.25)
end
Enter fullscreen mode Exit fullscreen mode

One loop, four phases

The whole game state is three attributes on ReplicatedStorage: the phase, the server time it ends, and one line of information. Attributes replicate to every client on their own, so a player who joins in the middle of a round sees the right timer at once, with no remote to request it.

Sending the end time instead of a countdown matters. Each client subtracts the shared server clock, so all timers agree and none drifts when a message arrives late.

A vote that cannot be cheated or stalled

The server keeps the ballot. A vote is accepted only during the Voting phase, only as a string, and only if it is one of the three options on offer; anything else is dropped. Votes are stored by player, so voting again changes your vote instead of adding one.

Votes from players who have left are not counted, a tie is broken at random, and the vote closes as soon as every player in the server has voted, so a full lobby is not kept waiting.

Why the loop is wrapped in pcall

A round system that stops is worse than one with a bug in it: every player is stuck in the lobby until the server restarts. If a map is missing its Spawns folder or anything else throws, the loop logs the error, removes the half-loaded map and starts the next vote.

Players who join late or leave early

Only players present when the round starts are contestants. Someone who joins later waits in the lobby, sees the timer, and gets a ballot if a vote is running. A contestant who leaves or dies is no longer counted as alive, and the round ends when one is left or the time runs out.

Good to know

  • Maps live in ServerStorage, which clients cannot see, so the next map is not downloaded or readable until it is cloned into Workspace.
  • If time runs out with several players alive, they all win. To require a single winner, compare a score instead, or add sudden death.
  • Rewards are added once, at the single point where the round ends. Paying inside a Died or Touched handler is how double rewards happen.

Questions

How do I add teams?

Create Team objects, assign each contestant in runRound before the teleport, and change the end condition to "only one team has players alive".

How do I stop the same map being picked twice in a row?

This script already leaves the last map off the ballot whenever there are more maps than options.

Can players vote for a game mode too?

Yes. Run a second ballot the same way with mode names as the options, and pass the winner into runRound.

Why are my players not teleported?

PivotTo needs a character. If a player is respawning at that moment they are skipped; give the phase change a second before the teleport, or teleport in CharacterAdded for contestants.

If you would rather not write it

Start free: the free Roundmoor sampler: two real modules from the kit (Format, for timers and scores, and Signal) with the .rbxmx to drag into Studio. The full kit is on the same page. Roundmoor is the full round and match system: lobby, intermission, map and mode vote, fair teams, spawn protection, win checks for four modes, an MVP scoreboard and rewards paid exactly once per match. Free sampler first, then the kit: https://cybermaxtools.com/roblox/kits/roundmoor/?utm_source=devto&utm_medium=article&utm_campaign=rbxtut-roblox-round-system-with-map-voting

Roblox is a trademark of Roblox Corporation. CyberMax is not affiliated with or endorsed by Roblox.


Published automatically by CyberMax. Every number above comes from the linked public data; nothing is estimated.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The EndsAt detail is the part I would steal first — sending one shared end time instead of ticking a countdown down to every client quietly fixes a whole class of drift bugs. Same with keeping the ballot server-side and closing the vote as soon as everyone has voted; the 15-second wait becomes a ceiling, not a tax on every round. One edge I am curious about: a player who joins mid-vote gets the options sent to them, but if the vote already closed early because everyone else voted, does their client just sit on a stale ballot until the next phase? Have you thought about sending a joining player the current phase and EndsAt as well, so their HUD never shows a vote that is already over?