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.

Concept lesson, about 70 minutes, 10 steps

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.

Figure 1.1.

One player starts the drill. The phase, the gates, the light and the timer all change on the server.

Transcript
  1. 0:00 One player starts the drill for the server.
  2. 0:05 Active publishes RoundPhase and RoundEndsAt, and fires RoundState.
  3. 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?

  1. On the server, in RoundService, when the prompt's Triggered event fires
  2. On that player's client, which then tells the others
  3. On every client at once
  4. In the HUD script
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.

Server sideA round state machine is a traffic light.
In the pictureIn Roblox
The current colourThe phase: Idle, Active or Cooldown
The fixed order of coloursThe allowed transitions
Everyone at the crossing sees the same colourThe server publishes one phase to every client

See the whole analogy cast

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

Luau
local NEXT = { Idle = "Active", Active = "Cooldown", Cooldown = "Idle" }
local phase = "Idle"
for step = 1, 4 do
	phase = NEXT[phase]
	print(step, phase)
end
Figure 2.1. Expected output: 1 Active 2 Cooldown 3 Idle 4 Active

Shared/Types.luau declares export type RoundPhase = "Idle" | "Active" | "Cooldown". What does that buy you?

  1. The type checker flags a typo such as "Actve" before you press Play
  2. The server refuses to run with a wrong phase
  3. Clients cannot change the phase
  4. Nothing; types are comments
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
Figure 3.1

Each transition has a condition and side effects:

FromToConditionSide effects
IdleActivePrompt triggered and not busyPrompt off, gates open, red light
ActiveCooldown40 seconds passSurvival bonus, gates close, light restored
CooldownIdle8 seconds passPrompt 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
Figure 4.1
Roblox Studio
Roblox Studio with the beacon's ProximityPrompt selected in Explorer and its HoldDuration and Enabled properties in the Properties window.

Select a numbered pin, or a row below, to read what it marks.

Figure 4.2.

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
  1. One
  2. Two, one after the other
  3. Two at the same time
  4. None
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)
Figure 5.1
Both sidesAttributes is sticky notes on an instance.
In the pictureIn Roblox
Writing a noteinstance:SetAttribute(name, value)
Reading the noteinstance:GetAttribute(name)
The note travels with the instanceServer attributes replicate to clients

See the whole analogy cast

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?

  1. It reads the RoundPhase attribute on Workspace, which replicated when they joined
  2. It waits for the next RoundState event, which comes in 20 seconds
  3. It asks the server with a RemoteFunction
  4. It cannot know until the next round
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.

Roblox Studio
Beacon Yard HUD during an Active drill, showing the coin total, the phase with seconds remaining and the objective line.

Select a numbered pin, or a row below, to read what it marks.

Figure 6.1.

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)
Figure 6.2

Why does the HUD not use os.time() for the countdown?

  1. Each device's clock can differ from the server's, so players would see different times
  2. os.time() is not available in Luau
  3. os.time() only counts whole minutes
  4. os.time() is slower
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?

  1. No. The server waits for a valid beacon press.
  2. Yes. Idle advances on the same timer as Cooldown.
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")
  1. Nothing; the change stays on that client and the server's phase is unchanged
  2. The round ends for everyone
  3. The round ends for that player only, on the server
  4. An error, because clients cannot call SetAttribute
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

OptionWhat it isWhen pros pick itTrade-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 tableA 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 onlyPublish 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.
  • src/server/RoundService.luau
  • src/server/init.server.luau
  • src/client/Hud.luau
  • src/shared/Config.luau
  • src/shared/Types.luau
  • default.project.json
  1. In the game repo, run git diff --stat m04-two-sides m05-the-round -- src default.project.json, then git 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.

  2. Check out m05-the-round and search default.project.json for ProximityPrompt.

    You should see default.project.json now has a Beacon with a ProximityPrompt: ActionText Start drill, HoldDuration 0.4, MaxActivationDistance 12.

  3. 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.

  4. 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

  1. ROUND_SECONDS lives in Config.luau.
  2. 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?

  1. Config.ROUND_SECONDS, 40
  2. 0 seconds
  3. The last value it had
  4. It errors
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

  1. waitUntil loops until a time. Give it a second way out.
  2. 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 run game.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

  1. Add Overtime to the RoundPhase type first and let the type checker find every place to update.
  2. 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.
  3. Keep setDroneActive(true) and prompt.Enabled = false through Overtime, and call setDroneActive(false) only when Cooldown begins.
  4. 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

  1. The round is a state machine: one phase at a time, three transitions, each with a condition and side effects, all on the server.
  2. publish writes the phase as attributes (state for anyone, including late joiners) and fires RoundState (the moment of change).
  3. 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.

Next The drone: movement, targeting, damage

Open this step in lesson mode · Link to this step · This confused me