Open Sesame: Doors, Switches, Locks and Chests Kit
README.md
MatchFlow
The match loop every multiplayer game needs, as one component. Add MatchFlow to a synced entity, set format = "timed" and roundSeconds = 30, and the world runs:
waiting for players → lobby countdown → 3-2-1-GO → round with timer → results → break → next round
One machine is in charge, so every player sees the same countdown, clock, round end and results at the same moment. Players are whoever has joined the world. Eight match formats sit behind one field. Ten countdown styles with their own 3-2-1-GO sounds, four results screens, a HUD and a lobby panel each come in minimal, sci-fi and cartoon looks. Swapping any of them is a one-field change.
Five-minute start
- Install the package from ZeroMind (search "MatchFlow match flow kit", then install). It lands at
/source/MatchFlow.package. - Put it on a synced entity in your scene's
build.luau, or from any script that runs on every machine:
local match = entity.spawnSynced("Match")
match.component.add("MatchFlow", { format = "timed", roundSeconds = 30 })
- Press play with two people in the world. That's a working match: the lobby, the countdown with sound, a 30 s timer, a podium and a five-second break. Every score is 0 until you report some (see the next section).
To switch the match type, change one field: format = "firstToScore", "bestOf", "lastStanding", and so on. The kit's screens are restyled the same way:
match.component.add("MatchFlow", {
format = "bestOf", rounds = 3, targetScore = 5,
countdownStyle = "trafficLight", resultsScreen = "recap",
resultsLook = "cartoon", hudLook = "cartoon", lobbyLook = "cartoon",
})
Hooking your game in
Get the component from any script, report what happens, and listen for what changes:
local m = entity.find("Match").component.get("MatchFlow")
-- report (call from any machine; non-authority calls are forwarded to the one in charge)
m:addScore(avatar, 1) -- who = peer id, an entity (its owner is the player) or nil for "me"
m:knockOut(victimAvatar) -- lastStanding, or a player going down in waves
m:finish(avatar) -- race: crossing the line
m:clearWave() -- waves: the team cleared a wave
m:endTurn() -- turnBased: the local player ends their turn early
m:setOnHill(avatar, true) -- kingOfTheHill: standing on / off the hill
-- listen
m.events.onStateChanged:connect(function(e) print(e.previous, "->", e.phase) end)
m.events.onRoundEnded:connect(function(e) print("round", e.round, "won by", e.winnerName, e.outcome) end)
m.events.onMatchEnded:connect(function(e) print("match won by", e.winnerName) end)
m.events.onCountdown:connect(function(e) if e.n == 0 then unfreezePlayers() end end)
A typical game spawns its pickups, enemies or checkpoints only while m:getPhase() == "playing", and only on the machine where m:isAuthority() is true. The example game/OrbRush.component in this kit's world does exactly that in about 100 lines: synced orbs, and m:addScore(body, 1) on pickup.
A score reported outside playing, or for a player who is out or watching, is ignored. You don't need to guard your calls.
Formats
format | Round ends when | Winner | Fields it reads |
|---|---|---|---|
timed | the clock runs out | highest score | roundSeconds |
firstToScore | someone reaches the target (or time runs out) | first to targetScore | targetScore, roundSeconds |
bestOf | as firstToScore, per round | most round wins over up to rounds rounds; a majority ends it early | rounds, targetScore, roundSeconds |
lastStanding | one player (or none) is left | the survivor; earlier knockouts place lower | roundSeconds (0 = no limit) |
kingOfTheHill | someone holds the hill alone for targetScore seconds | longest uncontested hold | targetScore, roundSeconds |
race | everyone has finished (or time runs out) | finish order | roundSeconds |
waves | waves waves cleared (victory), or everyone down or out of time (defeat) | the team; the top scorer is shown as MVP | waves, roundSeconds |
turnBased | every player has had turns turns | highest score | turnSeconds, turns |
A round with no time limit (roundSeconds = 0) shows elapsed time. A turn-based round shows the current turn's clock.
Every field and its default
| Field | Default | What it does |
|---|---|---|
format | "timed" | one of the eight formats above |
roundSeconds | 30 | round length (0 = no limit; timed treats 0 as 60) |
targetScore | 10 | score to win firstToScore/bestOf, seconds to hold in kingOfTheHill |
rounds | 3 | maximum rounds in bestOf |
waves | 5 | waves to clear in waves |
turnSeconds / turns | 10 / 3 | turn length and turns per player in turnBased |
minPlayers | 2 | players needed before the lobby counts down |
lobbySeconds | 5 | lobby countdown once enough players are in |
countdownSeconds | 3 | the 3-2-1-GO before each round (0 skips it) |
resultsSeconds | 7 | how long results stay up |
breakSeconds | 5 | break before the next round |
autoStart | true | start by itself at minPlayers; when false, call m:start() |
includePeers | true | everyone in the world is a player; when false, call m:addPlayer(id, name) yourself |
countdownStyle | "bold" | one of the ten countdown styles |
resultsScreen | "podium" | podium, table, banner or recap |
resultsLook / hudLook / lobbyLook | "scifi" | minimal, scifi or cartoon |
showUi | true | false draws nothing, so you can build your own UI from getState() |
sounds / volume | true / 0.8 | the countdown's tick and GO sounds |
Countdown styles
Every style has its own tick (3, 2, 1) and GO sound. The ticks climb a little in pitch as the count nears GO (2 plays a step above 3, 1 a step above that), so the last second sounds urgent. In a match the sounds play on every machine, at the moment each number appears on its screen.
countdownStyle | Look | Sound |
|---|---|---|
bold | big bold slam-in numbers with a glow streak | punch |
trafficLight | red → amber → green racing lights | race beeps |
pixel | 8-bit block digits on a CRT panel | chiptune |
hologram | cyan sci-fi ring, scanlines, "ENGAGE" | sci-fi sweep |
cartoon | bouncy number on a starburst, "GO!" | toy boing |
minimal | thin progress ring, clean type | soft tone |
fantasy | golden runic circle, "BEGIN" | bell |
flipClock | split-flap cards that flip each second | mechanical click |
neon | buzzing neon tube sign | synth |
broadcast | sports-TV lower-third with a LIVE tag | stadium beeps and an air horn |
A countdown on its own
Countdown is the same visuals and sounds as a standalone component, for any other timer in your game: a respawn, a bomb or a door. It is local to each machine.
local cd = entity.spawn("RespawnTimer").component.add("Countdown", { style = "neon", seconds = 5, autoStart = false, anchor = "top" })
cd.events.onFinished:connect(respawn)
cd:start() -- or cd:start(10)
Fields: style, seconds (3), autoStart (true), loop / loopDelay, goText and caption (override the words), sounds, volume, showUi, anchor (center/top/bottom), scale, layer. Events: onTick{n}, onFinished. Methods: start(seconds?), stop(), isRunning(), timeLeft().
To draw one inside your own UI, call require("MatchFlow.countdowns").render(style, secondsLeft, { w = 420, h = 320 }), which returns a widget node.
Screens
| Screen | Choices | Looks |
|---|---|---|
Results (resultsScreen) | podium (top three on steps, then the rest), table (full standings with places, score and rounds won), banner (one big winner card), recap (round-by-round grid with each round's winner) | minimal, scifi, cartoon |
| In-play HUD | timer with progress bar and urgency pulse in the last 5 s, format info ("Round 2 of 3", "Wave 3 of 5", "Nova's turn · 7s"), live scoreboard with your row highlighted | minimal, scifi, cartoon |
| Lobby / break panel | "Waiting for players 1 / 2" with player chips, "Starting in 5", "Next round in 5" | minimal, scifi, cartoon |
All of them are plain functions over data (results.render(kind, look, data), hud.render, lobby.render), so you can draw them yourself with showUi = false.
Small screens and the browser
- Every panel sizes itself from the screen. MatchFlow reads the safe area (the part no notch or system bar covers) each frame through
require("MatchFlow.theme").viewport(), which returns{ w, h, narrow, short }in UI points.narrowis a phone held upright (under 640 wide),shortis one held sideways (under 480 tall). - Phones get compact layouts, not smaller text. On a narrow screen the HUD board moves under the timer and keeps to four rows, always including you. The podium lists 4th place onwards under the steps, the standings table folds its detail column into each row, the banner stacks the runners-up, and the round-by-round recap turns on its side (a row per player). The lobby title shrinks only as far as it must to fit. Pass
narrow = trueorfalsein the opts ofresults.renderandhud.renderto choose for yourself. - Checked at a 412 × 892 pt phone (1080 × 2340 at density 2.625), a 248 pt sliver, and 1280 × 702 desktop. A test renders every screen at phone and desktop sizes through its whole entrance animation.
- Fonts are engine-bundled families (Anton, Archivo Black, Arimo, Bricolage Grotesque, Comic Neue, EB Garamond, JetBrains Mono), so a browser draws them on the first frame with no fallback flash.
- Sound in the browser plays once the page has had a click or tap: browsers keep audio locked until then. Launching the world is normally that click.
- Drawing your own panels? The UI reads a plain number strictly between 0 and 1 in
width,height,left,top(and their min/max/right/bottom/flexBasis cousins) as a fraction of the parent:height = 0.5is half the parent, not half a point. A hairline scaled down on a phone (1.5 * 0.6) balloons into a slab. Wrap your tree inrequire("MatchFlow.theme").solid(node), as every kit panel does, to snap those to whole points.
Methods
| Method | |
|---|---|
addScore(who?, amount?), setScore(who?, value) | add to or set a player's score |
knockOut(who?), finish(who?), setOnHill(who?, on) | knockouts, race finishes, hill presence |
clearWave(), endTurn(who?) | waves and turns |
addPlayer(id, name), removePlayer(id) | add bots or hand-picked players (any id that is not a peer id) |
start(), reset() | start now regardless of head-count; throw the match away and wait again |
getState(), getStandings(), getPhase(), timeLeft() | read the match as it is on screen (see How multiplayer works) |
syncInfo() | clock offset, round trip, display delay and grace on this machine, for checking a multiplayer setup |
isAuthority(), localPlayer() | whether this machine is in charge; the local player's id |
Events: onStateChanged{phase, previous}, onCountdown{n} (3, 2, 1, then 0 = GO), onRoundEnded{round, winner, winnerName, outcome}, onMatchEnded{winner, winnerName, outcome}, onTurn{player, name}, onWave{wave}. Events fire on every machine. outcome is one of time, target, lastStanding, allFinished, victory, defeat, turns or empty.
How multiplayer works
- One machine is in charge: the owner of the synced
Matchentity, normally whoever created it. Only it runs the rules. It keeps a match clock and publishes the whole match (phase, clock, players, scores, history) in a synced snapshot stamped with that clock. It publishes whenever something changes, and at least four times a second. - Every screen shows the same moment. Each machine matches its clock to the match clock by pinging the machine in charge; the quickest of the last eight round trips sets it. It keeps the last few snapshots and shows the match as it stood a short display delay ago. The machine in charge shows it that way too. Every snapshot has landed before its moment comes up, so the countdown numbers, the timer, the round end and the results change on every screen at the same instant. The tests check this with two simulated machines whose clocks are 20 minutes apart, with 40–90 ms of uneven latency each way: every change lands within two frames on both screens.
- The display delay is long enough for the slowest player's snapshots to have landed. Every machine not in charge measures how late each snapshot reaches it (from the change it carries to its arrival, on the matched clock) and reports the worst of the last 20 s with its pings. The delay is that plus 0.05 s, or half the slowest round trip plus 0.1 s if that is longer, kept between 0.15 and 0.6 s. Lateness usually decides it: a snapshot also waits for the engine's sync tick, which a ping never does. On a live two-machine test with a 60–70 ms round trip it sat at 0.18–0.21 s and rose to 0.4 s while the network was jittery. When it changes, the new value is published half a second ahead and slides in at 0.2 s per second, the same way on every machine, so screens never fall out of step.
- Reads trail by the same delay.
getState(),getStandings(),getPhase(),timeLeft()and every event describe the match as it is on screen. A score, areset()or a phase change shows up one display delay after the machine in charge makes it, on that machine as well. - The 0:00 hold. A timed round stays open for a short grace after 0:00: the display delay, plus half the slowest round trip, plus 0.05 s, about 0.2–0.3 s in practice. The timer sits at 0:00 on every screen for that moment, then the results appear everywhere at once.
- Reports (
addScoreand the rest) are sent to the machine in charge, stamped with the time on the reporter's screen. A score, knockout, finish or cleared wave counts if it was made on screen after GO and before 0:00, and is dropped if not, however long the network took. A race finish time is the time on the finisher's screen. Calling a report on every machine for the same event would count it more than once, so report each event from one place, typically the authority as OrbRush does. - Players are the peers in the room the
Matchentity lives in: in play, the people playing this scene, not everyone who has the world open in an editor. Someone who joins mid-round sees "Watching · you join next round" on the HUD and plays from the next round. Someone who leaves mid-round is counted out of that round, and drops off the board when the match ends. - A machine coming back into play can find its engine still claiming the
Matchentity it owned before, while another machine took charge in between and the relay refuses its writes. MatchFlow notices the other machine's snapshots arriving, follows that machine instead of starting a match of its own, and only claims the entity once that machine has left. - A machine in charge whose connection drops and comes back is handed a new peer id. It stays in charge and carries the same match clock on under the new id, so the countdown, its sounds and the timer keep running on every screen.
- Checking a setup:
m:syncInfo()returns whether this machine is in charge, its clock offset and round trip, the display delay and grace, the newest snapshot's age, and the player count. It is cheap enough to call every frame. - Measured live, two machines in one 30 s timed round, one in charge: every countdown number, timer second and phase change appeared on both screens within 19 ms of each other (36 of 37 within one frame), and the results appeared at the same frame on both. Standings matched on both screens in every round played, a score made 0.13–0.15 s before 0:00 counted, and one made 0.08–0.1 s after 0:00 was dropped.
If the person in charge leaves mid-match
The match carries on and does not restart.
- Every machine already holds the last snapshot the leaver published, at most a quarter of a second old.
- Within about half a second of the owner disappearing, the remaining player with the lowest peer id claims the
Matchentity. If that machine is slow to do so, any other player claims it after 4 s. - The new machine in charge continues from that snapshot on the same match clock: same phase, same round, same scores, and the timer picks up where it was. The other machines keep the clock they already matched, so nothing jumps; they start pinging the new machine. The leaver is counted out of the round, as any leaver is.
- Players keep seeing the timer run during the gap, because every machine runs the clock forward from the last snapshot. A phase change that falls due inside the gap (the clock reaching zero, say) waits until the new machine takes charge, then happens on every screen at once. Any report made in the instant between the old host leaving and the new one taking over is lost.
In a live test, the person in charge left 13 s into a 30 s round with the score at 2–1. The other machine took charge about a second later, the round ran out on the same clock, and both players' results came out as scored (4–2). With one player left the match then went back to waiting for players, and back to the lobby when the leaver returned.
If everyone leaves, the round ends with outcome empty, and the match waits for players again.
Using it offline or in single-player
With nobody else connected, the local machine is in charge. Set minPlayers = 1 to play solo, or add bots with m:addPlayer(1001, "Bot") and drive their scores yourself.
What's inside
| Asset | Role |
|---|---|
MatchFlow.component | the match: the rules, sync, events, UI |
Countdown.component | standalone countdown |
rules.module | pure state machine for all eight formats (no engine calls, unit tested) |
timeline.module | the shared clock and display delay that keep every screen on the same moment (pure, tested with simulated latency) |
countdowns.module | the ten countdown styles as widget-tree renderers |
results.module, hud.module, lobby.module | the screens |
theme.module | the minimal, sci-fi and cartoon design tokens and helpers, viewport() and solid() |
view.module | turns match state into the data each screen draws |
audio.module + sounds/ | 20 short tick and GO clips, two for each of the ten sound sets |
matchflow.testSuite | 44 tests: every format, the roster rules, every renderer at desktop and phone sizes, the sound sets and pitch, two simulated machines over a jittery network, how a snapshot is read off the wire, and the delay and rival rules |
Run the tests with tools.use("tests", "run", { suite = "matchflow" }) in edit mode.