Lesson 4 of 12
The round loop: a state machine
Build a round loop for a Roblox game as a state machine. Read Beacon Yard's RoundService, publish phases with attributes and a remote, and count down the same clock on every client.
By the end you can
- Draw the Idle, Active and Cooldown phases and the condition and side effects of each transition
- Explain why the server publishes the phase both as attributes and on the RoundState remote
- Use a busy flag and GetServerTimeNow to keep one round per server and one shared clock
Before this: Coins: touch, debounce, respawn, leaderstats, Remotes: events, functions, unreliable, buffers
1One press starts it for everyone
Hold E at the beacon for 0.4 seconds. The gates slide open, the sky turns red, and every player's HUD switches from Idle to a countdown that starts at 40. One player pressed a key; the whole server changed.
One player starts the drill. The phase, the gates, the light and the timer all change on the server.
Transcript
- 0:00 One player starts the drill for the server.
- 0:05 Active publishes RoundPhase and RoundEndsAt, and fires RoundState.
- 0:08 The gates move 9 studs on X. The timer starts near 40 seconds.
That is RoundService, added at m05-the-round. It is a small State machineState machineA value that is always in one of a few named states, with rules for moving between them.Think of it as a traffic light. with three phases: Idle, Active and Cooldown.
A player holds E at the beacon. Where is the decision to start the round made?
Answer
On the server, in RoundService, when the prompt's Triggered event fires. The prompt reports the press to the server, and RoundService decides. Clients only watch the result.
Open this step in lesson mode · Link to this step · This confused me
2A traffic light with three colours
A state machine is a value that can be in one of a few named states, plus rules for moving between them. The round can only go Idle to Active, Active to Cooldown, and Cooldown back to Idle.
| In the picture | In Roblox |
|---|---|
| The current colour | The phase: Idle, Active or Cooldown |
| The fixed order of colours | The allowed transitions |
| Everyone at the crossing sees the same colour | The server publishes one phase to every client |
The round is a traffic light. It is always exactly one colour, it changes in a fixed order, and everyone at the crossing sees the same colour at the same time.
Think of it as A traffic light
local NEXT = { Idle = "Active", Active = "Cooldown", Cooldown = "Idle" }
local phase = "Idle"
for step = 1, 4 do
phase = NEXT[phase]
print(step, phase)
end
1 Active
2 Cooldown
3 Idle
4 ActiveShared/Types.luau declares export type RoundPhase = "Idle" | "Active" | "Cooldown". What does that buy you?
Answer
The type checker flags a typo such as "Actve" before you press Play. A string union limits the variable to three exact strings. A misspelled phase is a type error in your editor instead of a round that silently never ends.
Open this step in lesson mode · Link to this step · This confused me
3runRound, one phase at a time
runRound is the whole cycle as straight-line code. It sets the phase, publishes it, does the side effects, waits, and moves on.
Server sideRemember: A round state machine is a traffic light.
local function runRound()
prompt.Enabled = false
local activeSeconds = positiveOverride("TestRoundSeconds") or Config.ROUND_SECONDS
local activeEnds = workspace:GetServerTimeNow() + activeSeconds
phase = "Active"
publish(phase, activeEnds)
Remotes.get("Feedback"):FireAllClients("start", "Drill started")
tweenGates(true)
setDrillLight(true)
waitUntil(activeEnds)
awardSurvival()
local cooldownSeconds = positiveOverride("TestCooldownSeconds") or Config.COOLDOWN_SECONDS
local cooldownEnds = workspace:GetServerTimeNow() + cooldownSeconds
phase = "Cooldown"
publish(phase, cooldownEnds)
tweenGates(false)
setDrillLight(false)
waitUntil(cooldownEnds)
phase = "Idle"
publish(phase, workspace:GetServerTimeNow())
prompt.Enabled = true
Each transition has a condition and side effects:
| From | To | Condition | Side effects |
|---|---|---|---|
| Idle | Active | Prompt triggered and not busy | Prompt off, gates open, red light |
| Active | Cooldown | 40 seconds pass | Survival bonus, gates close, light restored |
| Cooldown | Idle | 8 seconds pass | Prompt back on |
ROUND_SECONDS is 40 and COOLDOWN_SECONDS is 8. How many seconds after a drill starts can the next one start?
Answer
48 seconds. 40 seconds of Active plus 8 seconds of Cooldown. The prompt is re-enabled only when the phase returns to Idle.
Open this step in lesson mode · Link to this step · This confused me
4Two players, one round
Two players can hold E at the same moment. Both Triggered events reach the server. beginRound checks a busy flag and the phase before it starts anything, then runs the round in its own thread with task.spawn so the prompt handler returns at once.
local function beginRound()
if busy or phase ~= "Idle" then
return
end
busy = true
task.spawn(function()
runRound()
busy = false

Select a numbered pin, or a row below, to read what it marks.
The beacon prompt. Enabled turns off while a round runs.
Two players trigger the prompt in the same frame. How many rounds run?
local function beginRound()
if busy or phase ~= "Idle" then
return
end
busy = true
task.spawn(function()
runRound()
busy = false
end)
end
Answer
One. The first call sets busy to true before it yields. The second call sees busy and returns. Turning the prompt off is a second guard, not the only one.
Open this step in lesson mode · Link to this step · This confused me
5Publishing the phase twice
Clients need the phase for the HUD, and other server scripts need it too. publish writes it two ways: as AttributeAttributeA named value you attach to any instance with SetAttribute and read with GetAttribute.Think of it as a sticky note on an instance.s RoundPhase and RoundEndsAt on Workspace, and as a RoundState remote event to every client.
local function publish(phase: RoundPhase, endsAt: number)
Remotes.get("RoundState"):FireAllClients(phase, endsAt)
workspace:SetAttribute("RoundPhase", phase)
workspace:SetAttribute("RoundEndsAt", endsAt)
| In the picture | In Roblox |
|---|---|
| Writing a note | instance:SetAttribute(name, value) |
| Reading the note | instance:GetAttribute(name) |
| The note travels with the instance | Server attributes replicate to clients |
An attribute is a sticky note on an instance. Anyone who can see the instance can read the note, and the note travels with it to every client.
Think of it as Sticky notes on an instance
The attribute is the state; anyone joining late can read it. The remote is the moment of change; the HUD hears it at once. RoundEndsAt is a time, not a count of seconds left, so every client counts down to the same instant.
Both sidesRemember: Attributes is sticky notes on an instance.
A player joins 20 seconds into a drill. How does their HUD know the round is Active?
Answer
It reads the RoundPhase attribute on Workspace, which replicated when they joined. Attributes are part of the instance, so a new client receives the current value with Workspace. A missed remote event is never re-sent.
Open this step in lesson mode · Link to this step · This confused me
6One clock for every screen
The HUD shows Active 31.4s. When RoundState arrives with the phase and endsAt timestamp, the HUD stores them and recomputes endsAt - workspace:GetServerTimeNow() every tenth of a second. GetServerTimeNow is an estimate of the server's clock that every client shares1, so two players see the same number even if their device clocks disagree.

Select a numbered pin, or a row below, to read what it marks.
The HUD during a drill. The seconds come from RoundEndsAt and the shared clock.
local function renderClock()
local remaining = math.max(0, endsAt - workspace:GetServerTimeNow())
if phase == "Active" then
phaseLabel.Text = string.format("Active %.1fs", remaining)
objectiveLabel.Text = ACTIVE_OBJECTIVE
elseif phase == "Cooldown" then
phaseLabel.Text = "Cooldown"
objectiveLabel.Text = string.format("Next drill in %ds", math.max(0, math.ceil(remaining)))
else
phaseLabel.Text = "Idle"
objectiveLabel.Text = IDLE_OBJECTIVE
end
end
local roundState = remoteEvent("RoundState")
roundState.OnClientEvent:Connect(function(...: unknown)
local values: { unknown } = { ... }
local nextPhase = parsePhase(values[1])
local nextEndsAt = values[2]
if nextPhase == nil or typeof(nextEndsAt) ~= "number" then
return
end
phase = nextPhase
endsAt = nextEndsAt
renderClock()
end)
task.spawn(function()
while screen.Parent ~= nil do
renderClock()
task.wait(0.1)
Why does the HUD not use os.time() for the countdown?
Answer
Each device's clock can differ from the server's, so players would see different times. os.time reads the local device clock, which can be minutes off. GetServerTimeNow is synchronised with the server, so RoundEndsAt means the same instant everywhere.
Open this step in lesson mode · Link to this step · This confused me
7Where the pictures break
A traffic light changes on a timer and nothing else happens. The round's transitions have conditions and side effects, which is why they live in one function.
Where does it break?“A traffic light” is a good picture of a round state machine. Where does it stop being true?
It breaks here. A traffic light only changes on a timer, but real transitions have conditions (a press, everyone down, a path blocked) and side effects (gates, lighting, re-pathing) that must run exactly once.
The true model. A state machine is a current state plus a set of transitions. Each transition has a guard condition and side effects. One owner changes the state and publishes it, so no other code can put it in an impossible combination.
Nobody presses the beacon while Beacon Yard is Idle. Does the round start when the server clock reaches a certain time?
Answer
No. The server waits for a valid beacon press.. Cooldown ends on a timer. Idle ends when the server accepts a beacon press and starts the drill.
The sticky-note picture has a different limit. Which side can change the note for everyone?
Where does it break?“Sticky notes on an instance” is a good picture of attributes. Where does it stop being true?
It breaks here. Notes only travel down: a client that writes a note changes its own copy and the server never sees it; and only a few value types fit on a note.
The true model. Attributes are typed key-value pairs on an instance. Server writes replicate to clients; client writes stay local. They suit small state such as a phase or a health value, not tables or instances.
An exploiter runs this in a LocalScript. What does the server's RoundService see?
workspace:SetAttribute("RoundPhase", "Idle")
Answer
Nothing; the change stays on that client and the server's phase is unchanged. Attributes replicate from the server down, never up. The exploiter's HUD may say Idle, but the server's phase, the gates and the drone do not change.
Open this step in lesson mode · Link to this step · This confused me
8Build it: from two sides to a round
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| A loop with waits (RoundService) | One function runs the phases top to bottom with task.wait in between. | Short, linear loops like a drill. Easy to read and to test with shorter timings. | Adding a branch (overtime, early end) means editing the middle of the function. |
| An event-driven state table | A table of states with enter and exit functions; events request transitions. | Many states or transitions triggered by gameplay (all players dead, objective taken). | More code up front, and timers have to be scheduled and cancelled by hand. |
| Value objects or attributes only | Publish the phase as a StringValue or attribute and let clients listen. | When late joiners must always see the current state. | No moment-of-change message with extra data; Beacon Yard pairs it with a remote for that. |
Build along
src/server/RoundService.luausrc/server/init.server.luausrc/client/Hud.luausrc/shared/Config.luausrc/shared/Types.luaudefault.project.json
In the game repo, run
git diff --stat m04-two-sides m05-the-round -- src default.project.json, thengit diff m04-two-sides m05-the-round -- src/shared src/server/Remotes.luau.You should see RoundService.luau is new, Config.luau gains ROUND_SECONDS, COOLDOWN_SECONDS and SURVIVAL_BONUS, and Remotes.luau adds RoundState.
Check out
m05-the-roundand searchdefault.project.jsonforProximityPrompt.You should see default.project.json now has a Beacon with a ProximityPrompt: ActionText Start drill, HoldDuration 0.4, MaxActivationDistance 12.
Run
rojo serve, connect Studio, press Play and hold E at the beacon.You should see The HUD shows Active with a countdown from 40, each gate slides 9 studs outward, and after 40 seconds the HUD shows Cooldown for 8.
Switch to the Server view, select Workspace and read the Attributes section in Properties.
You should see Workspace's attributes list RoundPhase and RoundEndsAt, and RoundPhase reads Active during the drill.
Open this step in lesson mode · Link to this step · This confused me
9Challenges
Level 1, Apprentice
Challenge
Make a drill last 10 seconds two ways: through Config, and through the test attribute. Which one needs a code change?
- Start from
- The game at milestone m06 (download)
Done means
- During Play, a drill lasts about 10 seconds
- The HUD countdown starts at 10
- ROUND_SECONDS is 40 again afterwards
Hints
- ROUND_SECONDS lives in Config.luau.
- Or set the TestRoundSeconds attribute on Workspace in the Server view, and leave Config alone.
positiveOverride("TestRoundSeconds") returns nil when the attribute is 0. What does a round then use?
Answer
Config.ROUND_SECONDS, 40. positiveOverride accepts only numbers above 0. Otherwise the or falls back to Config.ROUND_SECONDS.
Level 2, Builder
Challenge
Add a second condition to the Active to Cooldown transition: everyone is down.
- Start from
- The game at milestone m06 (download)
Done means
- If every player is dead, Active ends early and goes to Cooldown
- No survival bonus is paid in that case
- A normal round still lasts 40 seconds
Hints
- waitUntil loops until a time. Give it a second way out.
- Check humanoid.Health for every player inside the loop.
Level 3, Professional
Challenge
Add an Overtime phase. This is the real test of a state machine: one new state, every transition still correct.
- Start from
- The game at milestone m06 (download)
- Grade it
- To grade work from an earlier milestone, apply your challenge changes to a checkout based on
m14-ship, which includes the Course Runner. In Studio, press Play, then rungame.ServerScriptService.RunGameTests:Invoke("round-loop", "round-overtime")in the server command bar. Copy the pass code from Output.
Done means
- A new phase, Overtime, runs between Active and Cooldown (Active -> Overtime -> Cooldown -> Idle)
- RoundPhase and RoundState publish Overtime like the other phases
- Overtime uses the same length as Active: Config.ROUND_SECONDS (40 s) normally, and the TestRoundSeconds override when it is set, never a hard-coded number
- During Overtime, the drone stays active and the beacon ProximityPrompt stays disabled; the drone clears when Cooldown starts
- The HUD shows Overtime too: Hud.luau's parsePhase accepts the new phase string, so the label does not stay stuck on Active
- The default suite still passes: the Idle wait in round_sequence and round_idle in tests/init.luau grows from 20 s to 36 s so it covers Active, Overtime and Cooldown
- challenges/round-loop.luau prints TEST PASS for overtime_order, overtime_length, overtime_drone and overtime_cooldown
Hints
- Add Overtime to the RoundPhase type first and let the type checker find every place to update.
- Compute the length once, positiveOverride("TestRoundSeconds") or Config.ROUND_SECONDS, and use it for both Active and Overtime so the override shortens both and a normal round gives both 40 s.
- Keep setDroneActive(true) and prompt.Enabled = false through Overtime, and call setDroneActive(false) only when Cooldown begins.
- Two edits live outside RoundService: accept Overtime in parsePhase in Hud.luau, and lengthen the Idle wait in tests/init.luau from 20 to 36 seconds. Read challenges/solutions/round-loop.md only after trying.
Open this step in lesson mode · Link to this step · This confused me
10Recap
Recap
- The round is a state machine: one phase at a time, three transitions, each with a condition and side effects, all on the server.
- publish writes the phase as attributes (state for anyone, including late joiners) and fires RoundState (the moment of change).
- A busy flag keeps one round per server, and RoundEndsAt with GetServerTimeNow gives every client the same countdown.
A round state machine is a traffic light, until a traffic light only changes on a timer, but real transitions have conditions (a press, everyone down, a path blocked) and side effects (gates, lighting, re-pathing) that must run exactly once.
Attributes is sticky notes on an instance, until notes only travel down: a client that writes a note changes its own copy and the server never sees it; and only a few value types fit on a note.
Queued for review
Open this step in lesson mode · Link to this step · This confused me