multiplayer-game

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Multiplayer Game

多人游戏

IMPORTANT: Before doing anything, you MUST read
BASE_SKILL.md
in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.
Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre.
重要提示:在进行任何操作前,你必须阅读本技能目录下的
BASE_SKILL.md
文件。其中包含了调试、错误处理、状态管理、部署及项目搭建的关键指导。这些规则和模式适用于所有RivetKit相关工作。以下所有内容均假设你已阅读并理解该文件。
本文档是使用RivetKit构建多人游戏的实用模式集合,可作为你根据游戏类型调整的参考清单。

Starter Code

起始代码

Start with one of the working examples on GitHub and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows.
Game ClassificationStarter CodeCommon Examples
Battle RoyaleGitHubFortnite, Apex Legends, PUBG, Warzone
ArenaGitHubCall of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League
IO StyleGitHubAgar.io, Slither.io, surviv.io
Open WorldGitHubMinecraft survival servers, Rust-like worlds, MMO zone/chunk worlds
PartyGitHubFall Guys private lobbies, custom game rooms, social party sessions
Physics 2DGitHubTop-down physics brawlers, 2D arena games, platform fighters
Physics 3DGitHubPhysics sandbox sessions, 3D arena games, movement playgrounds
RankedGitHubChess ladders, competitive card games, duel arena ranked queues
Turn-BasedGitHubChess correspondence, Words With Friends, async board games
IdleGitHubCookie Clicker, Idle Miner Tycoon, Adventure Capitalist
GitHub上的可用示例开始,根据你的游戏需求进行适配。不要从零开始开发匹配机制和生命周期流程。
游戏分类起始代码常见示例
大逃杀GitHubFortnite, Apex Legends, PUBG, Warzone
竞技场GitHubCall of Duty TDM/FFA, Halo Slayer, Counter-Strike休闲模式, VALORANT无排位模式, Overwatch快速游戏, Rocket League
IO类游戏GitHubAgar.io, Slither.io, surviv.io
开放世界GitHubMinecraft生存服务器, 类Rust世界, MMO区域/分块世界
派对房间GitHubFall Guys私人房间, 自定义游戏房间, 社交派对会话
2D物理类GitHub俯视角物理格斗游戏, 2D竞技场游戏, 平台格斗游戏
3D物理类GitHub物理沙盒会话, 3D竞技场游戏, 移动玩法沙盒
排位赛GitHub国际象棋天梯, 竞技卡牌游戏, 决斗场排位队列
回合制GitHub异步国际象棋, Words With Friends, 异步桌游
放置类GitHubCookie Clicker, Idle Miner Tycoon, Adventure Capitalist

Server Simulation

服务器模拟

Game Loop And Tick Rates

游戏循环与Tick速率

PatternUse WhenImplementation Guidance
Fixed realtime loopBattle Royale, Arena, IO Style, Open World, RankedRun in
run
with
sleep(tickMs)
and exit on
c.aborted
.
Action-driven updatesParty, Turn-BasedMutate and broadcast only on actions/events rather than scheduled ticks.
Coarse offline progressionAny mode with idle progressionUse
c.schedule.after(...)
with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time.
模式适用场景实现指导
固定实时循环大逃杀、竞技场、IO类游戏、开放世界、排位赛
run
函数中通过
sleep(tickMs)
运行,并在
c.aborted
时退出。
动作驱动更新派对房间、回合制仅在触发动作/事件时修改并广播状态,而非按固定Tick调度。
粗粒度离线进度任何包含放置进度的模式使用
c.schedule.after(...)
设置较长的时间窗口(例如5到15分钟),并根据流逝的实际时间应用进度补全。

Physics

物理引擎

Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes).
Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative.
DimensionPrimary EngineFallback EnginesExample Code
2D
@dimforge/rapier2d
planck-js
,
matter-js
GitHub
3D
@dimforge/rapier3d
cannon-es
,
ammo.js
GitHub
对于简单游戏,先从自定义运动学逻辑开始。当你需要关节、堆叠物体、高碰撞密度或复杂形状(旋转多边形、胶囊体、凸包、三角形网格)时,再切换到完整的物理引擎。
每个模拟仅选择一个引擎。将前端专用库排除在后端模拟流程之外,以服务器状态作为权威来源。
维度首选引擎备选引擎示例代码
2D
@dimforge/rapier2d
planck-js
,
matter-js
GitHub
3D
@dimforge/rapier3d
cannon-es
,
ammo.js
GitHub

Spatial Indexing

空间索引

For non-physics spatial queries, use a dedicated index instead of naive
O(n^2)
checks:
Index TypeRecommendation
AABB indexFor AOI, visibility, and non-collider entities, use
rbush
for dynamic sets or
flatbush
for static-ish sets.
Point indexFor nearest-neighbor or within-radius queries, use
d3-quadtree
.
对于非物理类的空间查询,使用专用索引而非简单的
O(n^2)
检查:
索引类型推荐方案
AABB索引针对兴趣区域(AOI)、可见性和非碰撞实体,动态集合使用
rbush
,半静态集合使用
flatbush
点索引针对最近邻或范围内查询,使用
d3-quadtree

Networking & State Sync

网络与状态同步

Netcode

网络代码

ModelWhen To UseImplementation
Hybrid (client movement, server combat)Shooters, action sports, ranked duelsClient owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative.
Server-authoritative with interpolationIO Style, persistent worldsClient sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots.
Server-authoritative (basic logic)Turn-based, event-drivenServer validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state.
模型适用场景实现方式
混合模式(客户端控制移动,服务器控制战斗)射击游戏、动作体育游戏、排位决斗客户端拥有移动控制权,并发送限速的位置更新。服务器进行反作弊验证。战斗(投射物、命中、伤害)完全由服务器权威控制。
服务器权威+插值IO类游戏、持久化世界客户端发送输入指令。服务器按固定Tick模拟并发布权威状态快照。客户端在快照之间进行插值。
服务器权威(基础逻辑)回合制、事件驱动类服务器验证并应用离散动作(回合、阶段转换、投票)。客户端显示已确认的状态。

Realtime Data Model

实时数据模型

  • Snapshots and diffs: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates.
  • Batch per tick: Keep events small and typed. Batch high-frequency updates per tick.
  • Avoid UI framework state for game updates: Use
    requestAnimationFrame
    or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms.
  • Broadcast vs per-connection: Use
    c.broadcast(...)
    for shared updates and
    conn.send(...)
    for private/per-player data.
  • 快照与差异更新:将状态作为事件发布。玩家加入/重新同步时发送完整快照,之后在每个Tick发送差异更新。
  • 按Tick批量处理:保持事件小巧且类型明确。将高频更新按Tick批量处理。
  • 避免使用UI框架状态处理游戏更新:使用
    requestAnimationFrame
    或Canvas/Three.js循环处理模拟,而非React状态。仅将UI框架状态用于菜单、HUD和表单。
  • 广播 vs 单连接发送:使用
    c.broadcast(...)
    发送共享更新,使用
    conn.send(...)
    发送私有/玩家专属数据。

Shared Simulation Logic

共享模拟逻辑

Shared simulation logic runs on both the client and the server. For example, an
applyInput(state, input, dt)
function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation.
  • Hybrid modes: Client runs shared movement as primary authority, server runs it for anti-cheat validation.
  • Server-authoritative modes: Client uses shared logic for interpolation and prediction only.
  • Keep it pure: Movement integration, input transforms, collision helpers, and constants only.
  • Put shared code in
    src/shared/
    : Keep deterministic helpers in
    src/shared/sim/*
    with no side effects.
共享模拟逻辑同时在客户端和服务器运行。例如,
applyInput(state, input, dt)
函数用于整合速度并限制在世界边界内,可在客户端用于预测,在服务器用于验证。
  • 混合模式:客户端将共享移动逻辑作为主要权威,服务器将其用于反作弊验证。
  • 服务器权威模式:客户端仅将共享逻辑用于插值和预测。
  • 保持纯函数特性:仅包含移动整合、输入转换、碰撞辅助函数及常量。
  • 将共享代码放入
    src/shared/
    目录
    :将确定性辅助函数放在
    src/shared/sim/*
    中,且无副作用。

Interest Management

兴趣管理

Control what each client receives to reduce bandwidth and prevent information leaks.
控制每个客户端接收的数据,以减少带宽消耗并防止信息泄露。

Per-Player Replication Filters

按玩家复制过滤

  • Filter by relevance: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase).
  • Shooters and action games: Limit replication by proximity and optional field-of-view checks.
  • Server-side only: Clients should never receive data they should not see.
  • 按相关性过滤:仅向每个客户端发送与该玩家相关的状态(距离、视野、队伍或游戏阶段)。
  • 射击游戏和动作游戏:通过距离和可选的视野检查限制数据复制。
  • 仅在服务器端处理:客户端绝不能接收其不应看到的数据。

Sharded Worlds

分块世界

  • Partition large worlds: Use chunk actors keyed by
    worldId:chunkX:chunkY
    .
  • Subscribe to nearby chunks: Clients connect only to nearby partitions (for example a 3x3 chunk window).
  • Use sparingly: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches.
  • 分割大型世界:使用以
    worldId:chunkX:chunkY
    为键的分块Actor。
  • 订阅附近分块:客户端仅连接到附近的分块(例如3x3分块窗口)。
  • 谨慎使用:仅在世界庞大且状态繁重时使用(沙盒建造游戏、MMO),不要作为小型匹配的默认方案。

Backend Infrastructure

后端基础设施

Persistence

持久化

  • In-memory state: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores).
  • SQLite (
    rivetkit/db
    )
    : Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently.
  • 内存状态:最适合每Tick变化的实时游戏状态(玩家位置、输入、匹配阶段、分数)。
  • SQLite (
    rivetkit/db
    )
    :更适合需要查询、索引或长期持久化的大型或表格状状态(地图块、 inventory、匹配池)。由于多个动作可能同时访问同一个Actor,需通过队列序列化数据库操作。

Matchmaking Patterns

匹配模式

Common building blocks used across the architecture patterns below.
以下是架构模式中常用的基础组件。

Actor Topology

Actor拓扑结构

PrimitiveUse WhenTypical Ownership
matchmaker["main"]
+
match[matchId]
Session-based multiplayer (battle royale, arena, ranked, party, turn-based)Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state.
chunk[worldId,chunkX,chunkY]
Large continuous worlds that need shardingEach chunk owns local players, chunk state, and local simulation.
world[playerId]
Per-player progression loops (idle/solo world state)Per-player resources, buildings, timers, and progression.
player[username]
Canonical profile/rating reused across matchesDurable player stats (for example rating and win/loss).
leaderboard["main"]
Shared rankings across many matches/playersGlobal ordered score rows and top lists.
基础组件适用场景典型所有权
matchmaker["main"]
+
match[matchId]
基于会话的多人游戏(大逃杀、竞技场、排位赛、派对房间、回合制)匹配器负责发现/分配。匹配会话负责生命周期和游戏玩法状态。
chunk[worldId,chunkX,chunkY]
需要分块的大型连续世界每个分块负责本地玩家、分块状态和本地模拟。
world[playerId]
按玩家划分的进度循环(放置/单人世界状态)玩家专属资源、建筑、计时器和进度。
player[username]
跨匹配复用的标准档案/评级持久化玩家统计数据(例如评级和胜负记录)。
leaderboard["main"]
跨多个匹配/玩家的共享排名全局有序分数行和排行榜。

Queueing Strategy

排队策略

  • Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races.
  • Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker.
  • 多个玩家可能同时访问匹配器,因此查找/创建、排队/取消排队、关闭等动作需通过Actor队列序列化,以避免竞争条件。
  • 匹配本地动作(游戏玩法、计分)无需排队,除非需要写回匹配器。

Security And Anti-Cheat

安全与反作弊

Start with this baseline, then harden further for competitive or high-risk environments.
先从以下基线开始,然后针对竞技或高风险环境进一步强化。

Baseline Checklist

基础检查清单

  • Identity: Use
    c.conn.id
    as the authoritative transport identity. Treat
    playerId
    /
    username
    in params as untrusted input and bind through server-issued assignment/join tickets.
  • Authorization: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions).
  • Input validation: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode).
  • Rate limiting: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates).
  • State integrity: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals.
  • 身份验证:使用
    c.conn.id
    作为权威传输身份。将参数中的
    playerId
    /
    username
    视为不可信输入,并通过服务器颁发的分配/加入凭证进行绑定。
  • 授权验证:验证调用者是否有权修改目标实体(房间成员、回合所有权、仅房主可执行的动作)。
  • 输入验证:限制大小/长度、验证枚举值、验证用户名(长度、允许字符、避免无界Unicode)。
  • 速率限制:对频繁触发的动作(聊天、加入/离开、射击、移动更新)按连接设置速率限制。
  • 状态完整性:服务器重新计算派生状态(分数、胜利条件、排名)。绝不允许客户端修改inventory/货币/排行榜总数。

Movement Validation

移动验证

For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must:
  • Enforce max delta per update (speed cap) based on elapsed time.
  • Reject or clamp teleports.
  • Enforce world bounds (and basic collision if applicable).
  • Rate limit update frequency (for example 20Hz max).
对于任何客户端拥有移动权威的模式(混合流程),客户端可能会发送位置/旋转更新以保证流畅性,但服务器必须:
  • 根据流逝时间,限制每次更新的最大变化量(速度上限)。
  • 拒绝或限制瞬移操作。
  • 强制执行世界边界(如有必要,还需基础碰撞检查)。
  • 限制更新频率(例如最高20Hz)。

Architecture Patterns

架构模式

Each game type below starts with a quick summary table, then details actors and lifecycle.
以下每种游戏类型均以快速摘要表开头,随后详细介绍Actor和生命周期。

Battle Royale

大逃杀

TopicSummary
MatchmakingImmediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts.
NetcodeHybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement.
Tick Rate10 ticks/sec (
100ms
) with a fixed loop for zone progression and lifecycle checks.
PhysicsClient owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use
@dimforge/rapier3d
for 3D or
@dimforge/rapier2d
for top-down 2D.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Finds or creates lobbies, tracks pending reservations, and maintains occupancy.
  • Actions
    • findMatch
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • Queues
    • findMatch
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • State
    • SQLite
    • matches
    • pending_players
    • player_count
      includes connected and pending players
  • Key:
    match[matchId]
  • Responsibility: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations.
  • Actions
    • connect
    • Movement and combat actions
  • Queues
    • None
  • State
    • JSON
    • phase
    • players
    • zone
    • eliminations
    • snapshot data
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: findMatch()
	alt no open lobby
		MM->>M: create(matchId)
	end
	MM-->>C: {matchId, playerId}
	C->>M: connect(playerId)
	M->>MM: pendingPlayerConnected(matchId, playerId)
	MM-->>M: accepted
	Note over M: lobby countdown -> live
	M-->>C: snapshot + shoot events
	M->>MM: closeMatch(matchId)
主题摘要
匹配机制立即路由到未满员且未开始的最旧房间;玩家在房间中等待直到满员,然后开始匹配。
网络代码混合模式。客户端拥有移动、相机和本地预测权。服务器拥有区域状态、投射物、命中判定、淘汰、战利品和最终排名权。
Tick速率10次/秒(
100ms
),固定循环用于区域推进和生命周期检查。
物理引擎客户端拥有移动权,服务器进行反作弊验证;投射物、命中和伤害由服务器权威控制。3D游戏使用
@dimforge/rapier3d
,俯视角2D游戏使用
@dimforge/rapier2d
Actors
  • matchmaker["main"]
  • 职责:查找或创建房间,跟踪待处理的预留,维护房间占用情况。
  • 动作
    • findMatch
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • 队列
    • findMatch
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • 状态
    • SQLite
    • matches
    • pending_players
    • player_count
      包含已连接和待处理的玩家
  • match[matchId]
  • 职责:运行房间/进行中/结束阶段,管理玩家状态、区域推进和淘汰记录。
  • 动作
    • connect
    • 移动和战斗动作
  • 队列
  • 状态
    • JSON
    • phase
    • players
    • zone
    • eliminations
    • snapshot data
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: findMatch()
	alt no open lobby
		MM->>M: create(matchId)
	end
	MM-->>C: {matchId, playerId}
	C->>M: connect(playerId)
	M->>MM: pendingPlayerConnected(matchId, playerId)
	MM-->>M: accepted
	Note over M: lobby countdown -> live
	M-->>C: snapshot + shoot events
	M->>MM: closeMatch(matchId)

Arena

竞技场

TopicSummary
MatchmakingMode-based fixed-capacity queues (
duo
,
squad
,
ffa
) that build only full matches and pre-assign teams (except FFA).
NetcodeHybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring.
Tick Rate20 ticks/sec (
50ms
) with a tighter loop for live team and FFA snapshots.
PhysicsMedium to high intensity; client movement with server validation and server-authoritative combat/entities.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Runs mode queues, builds full matches, assigns teams, and publishes assignments.
  • Actions
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • Queues
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • State
    • SQLite
    • player_pool
    • matches
    • assignments
      keyed by connection and player
  • Key:
    match[matchId]
  • Responsibility: Runs match phases and in-match player/team state for score and win conditions.
  • Actions
    • connect
    • Gameplay actions
  • Queues
    • None
  • State
    • JSON
    • phase
    • players
    • team assignments
    • score and win state
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: queueForMatch(mode)
	Note over MM: enqueue in player_pool
	Note over MM: fill when capacity reached
	MM->>M: create(matchId, assignments)
	Note over MM: persist assignments
	MM-->>C: assignmentReady
	C->>M: connect(playerId)
	Note over M: waiting -> live when all players connect
	M->>MM: matchCompleted(matchId)
主题摘要
匹配机制基于模式的固定容量队列(
双人
小队
自由对战
),仅组建满员匹配,并预先分配队伍(自由对战除外)。
网络代码混合模式。客户端拥有移动权及预测和平滑处理。服务器拥有队伍或自由对战分配、投射物、命中判定、阶段转换和计分权。
Tick速率20次/秒(
50ms
),更紧凑的循环用于实时队伍和自由对战快照。
物理引擎中高强度;客户端移动由服务器验证,战斗/实体由服务器权威控制。
Actors
  • matchmaker["main"]
  • 职责:运行模式队列,组建满员匹配,分配队伍,并发布分配结果。
  • 动作
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • 队列
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • 状态
    • SQLite
    • player_pool
    • matches
    • assignments
      按连接和玩家键存储
  • match[matchId]
  • 职责:运行匹配阶段和匹配内玩家/队伍的分数及胜利条件状态。
  • 动作
    • connect
    • 游戏玩法动作
  • 队列
  • 状态
    • JSON
    • phase
    • players
    • team assignments
    • score and win state
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: queueForMatch(mode)
	Note over MM: enqueue in player_pool
	Note over MM: fill when capacity reached
	MM->>M: create(matchId, assignments)
	Note over MM: persist assignments
	MM-->>C: assignmentReady
	C->>M: connect(playerId)
	Note over M: waiting -> live when all players connect
	M->>MM: matchCompleted(matchId)

IO Style

IO类游戏

TopicSummary
MatchmakingOpen-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed.
NetcodeServer-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots.
Tick Rate10 ticks/sec (
100ms
) with lightweight periodic room snapshots.
PhysicsLow to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Routes players into the fullest open lobby and tracks reservations and occupancy.
  • Actions
    • findLobby
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • Queues
    • findLobby
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • State
    • SQLite
    • matches
    • pending_players
    • Occupancy includes pending reservations
  • Key:
    match[matchId]
  • Responsibility: Runs per-match movement simulation and broadcasts snapshots.
  • Actions
    • connect
    • setInput
  • Queues
    • None
  • State
    • JSON
    • players
    • inputs
    • movement state
    • snapshot cache
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: findLobby()
	alt no open lobby
		MM->>M: create(matchId)
	end
	MM-->>C: {matchId, playerId}
	C->>M: connect(playerId)
	M->>MM: pendingPlayerConnected(matchId, playerId)
	MM-->>M: accepted
	Note over M: fixed tick simulation
	M-->>C: snapshot events
	M->>MM: closeMatch(matchId)
主题摘要
匹配机制开放房间路由到未满员的最满房间;房间数量通过心跳更新,必要时自动创建新房间。
网络代码服务器权威+插值。客户端发送输入意图并进行插值。服务器拥有移动、边界、房间成员资格和权威快照权。
Tick速率10次/秒(
100ms
),轻量级周期性房间快照。
物理引擎中低强度;服务器权威运动学移动,仅在碰撞变得复杂时升级到物理引擎。
Actors
  • matchmaker["main"]
  • 职责:将玩家路由到最满的开放房间,并跟踪预留和占用情况。
  • 动作
    • findLobby
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • 队列
    • findLobby
    • pendingPlayerConnected
    • updateMatch
    • closeMatch
  • 状态
    • SQLite
    • matches
    • pending_players
    • 占用情况包含待处理预留
  • match[matchId]
  • 职责:运行每个匹配的移动模拟并广播快照。
  • 动作
    • connect
    • setInput
  • 队列
  • 状态
    • JSON
    • players
    • inputs
    • movement state
    • snapshot cache
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant M as match

	C->>MM: findLobby()
	alt no open lobby
		MM->>M: create(matchId)
	end
	MM-->>C: {matchId, playerId}
	C->>M: connect(playerId)
	M->>MM: pendingPlayerConnected(matchId, playerId)
	MM-->>M: accepted
	Note over M: fixed tick simulation
	M-->>C: snapshot events
	M->>MM: closeMatch(matchId)

Open World

开放世界

TopicSummary
MatchmakingClient-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections.
NetcodeHybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state.
Tick Rate10 ticks/sec per chunk actor (
100ms
), so load scales with active chunks.
PhysicsMedium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like).
Actors
  • Key:
    chunk[worldId,chunkX,chunkY]
  • Responsibility: Owns chunk-local players, blocks, movement tick, and chunk membership.
  • Actions
    • connect
    • enterChunk
    • addPlayer
    • setInput
    • leaveChunk
    • removePlayer
  • Queues
    • None
  • State
    • JSON
    • connections
    • players
    • blocks
      scoped to one chunk key
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant CH as chunk

	Note over C: resolve chunk keys from world position
	loop each visible chunk
		C->>CH: connect(worldId, chunkX, chunkY, playerId)
		Note over CH: store connection metadata
	end
	C->>CH: enterChunk/addPlayer
	loop movement updates
		C->>CH: setInput(...)
		CH-->>C: snapshot
	end
	C->>CH: leaveChunk/removePlayer or disconnect
	Note over CH: remove membership and metadata
主题摘要
匹配机制客户端根据世界坐标驱动分块路由,通过相邻分块连接预加载附近的分块窗口。
网络代码沙盒游戏使用混合模式(客户端移动+验证),MMO类流程使用服务器权威模式。服务器拥有分块路由、持久化和权威世界状态权。
Tick速率每个分块Actor 10次/秒(
100ms
),因此负载随活跃分块数量扩展。
物理引擎规模扩大时为中高强度;分块本地模拟可以是服务器权威(类MMO)或客户端移动+服务器验证(类沙盒)。
Actors
  • chunk[worldId,chunkX,chunkY]
  • 职责:管理分块本地玩家、方块、移动Tick和分块成员资格。
  • 动作
    • connect
    • enterChunk
    • addPlayer
    • setInput
    • leaveChunk
    • removePlayer
  • 队列
  • 状态
    • JSON
    • connections
    • players
    • blocks
      限定在一个分块键范围内
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant CH as chunk

	Note over C: resolve chunk keys from world position
	loop each visible chunk
		C->>CH: connect(worldId, chunkX, chunkY, playerId)
		Note over CH: store connection metadata
	end
	C->>CH: enterChunk/addPlayer
	loop movement updates
		C->>CH: setInput(...)
		CH-->>C: snapshot
	end
	C->>CH: leaveChunk/removePlayer or disconnect
	Note over CH: remove membership and metadata

Party

派对房间

TopicSummary
MatchmakingHost-created private party flow using party codes and explicit joins.
NetcodeServer-authoritative (basic logic). Server owns membership, host permissions, and phase transitions.
Tick RateNo continuous tick; updates are event-driven (
join
,
start
,
finish
).
PhysicsLow intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Handles party create/join flow, validates join tickets, and tracks party size.
  • Actions
    • createParty
    • joinParty
    • verifyJoin
    • updatePartySize
    • closeParty
  • Queues
    • createParty
    • joinParty
    • verifyJoin
    • updatePartySize
    • closeParty
  • State
    • SQLite
    • parties
    • join_tickets
      for party lookup and join validation
  • Key:
    match[matchId]
  • Responsibility: Owns party members, host role, ready flags, and phase transitions.
  • Actions
    • connect
    • startGame
    • finishGame
  • Queues
    • None
  • State
    • JSON
    • members
    • host
    • ready state
    • phase
    • party events
Lifecycle
主题摘要
匹配机制房主创建的私人派对流程,使用派对代码和明确的加入操作。
网络代码服务器权威(基础逻辑)。服务器拥有成员资格、房主权限和阶段转换权。
Tick速率无连续Tick;更新由事件驱动(
加入
开始
结束
)。
物理引擎低强度(以房间为主的流程);通常无需专用物理引擎或索引,除非添加实时小游戏。
Actors
  • matchmaker["main"]
  • 职责:处理派对创建/加入流程,验证加入凭证,并跟踪派对规模。
  • 动作
    • createParty
    • joinParty
    • verifyJoin
    • updatePartySize
    • closeParty
  • 队列
    • createParty
    • joinParty
    • verifyJoin
    • updatePartySize
    • closeParty
  • 状态
    • SQLite
    • parties
    • join_tickets
      用于派对查找和加入验证
  • match[matchId]
  • 职责:管理派对成员、房主角色、准备状态和阶段转换。
  • 动作
    • connect
    • startGame
    • finishGame
  • 队列
  • 状态
    • JSON
    • members
    • host
    • ready state
    • phase
    • party events
生命周期

Host Flow

房主流程

mermaid
sequenceDiagram
	participant H as Host Client
	participant MM as matchmaker
	participant M as match

	H->>MM: createParty()
	MM-->>H: {matchId, partyCode, playerId, joinToken}
	H->>M: connect(playerId, joinToken)
	M->>MM: verifyJoin(...)
	MM-->>M: allowed
	M->>MM: updatePartySize(playerCount)
	H->>M: startGame() / finishGame()
	M->>MM: closeParty(matchId)
mermaid
sequenceDiagram
	participant H as Host Client
	participant MM as matchmaker
	participant M as match

	H->>MM: createParty()
	MM-->>H: {matchId, partyCode, playerId, joinToken}
	H->>M: connect(playerId, joinToken)
	M->>MM: verifyJoin(...)
	MM-->>M: allowed
	M->>MM: updatePartySize(playerCount)
	H->>M: startGame() / finishGame()
	M->>MM: closeParty(matchId)

Joiner Flow

加入者流程

mermaid
sequenceDiagram
	participant J as Joiner Client
	participant MM as matchmaker
	participant M as match

	J->>MM: joinParty(partyCode)
	MM-->>J: {matchId, playerId, joinToken}
	J->>M: connect(playerId, joinToken)
	M->>MM: verifyJoin(...)
	MM-->>M: allowed / denied
	M->>MM: updatePartySize(playerCount)
mermaid
sequenceDiagram
	participant J as Joiner Client
	participant MM as matchmaker
	participant M as match

	J->>MM: joinParty(partyCode)
	MM-->>J: {matchId, playerId, joinToken}
	J->>M: connect(playerId, joinToken)
	M->>MM: verifyJoin(...)
	MM-->>M: allowed / denied
	M->>MM: updatePartySize(playerCount)

Ranked

排位赛

TopicSummary
MatchmakingELO-based queue pairing with a widening search window as wait time increases.
NetcodeHybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates.
Tick Rate20 ticks/sec (
50ms
) with fixed live ticks for deterministic pacing and broadcast cadence.
PhysicsMedium to high intensity; client movement with server validation and server-authoritative combat/hit resolution.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Runs rating-based queueing, pairing, assignment persistence, and completion fanout.
  • Actions
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • Queues
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • State
    • SQLite
    • player_pool
    • matches
    • assignments
      with rating window and connection scoping
  • Key:
    match[matchId]
  • Responsibility: Runs ranked match phase, score, and winner reporting.
  • Actions
    • connect
    • Gameplay actions
  • Queues
    • None
  • State
    • JSON
    • phase
    • players
    • score
    • winner
    • completion payload
  • Key:
    player[username]
  • Responsibility: Stores canonical player MMR and win/loss profile.
  • Actions
    • initialize
    • getRating
    • applyMatchResult
  • Queues
    • None
  • State
    • JSON
    • rating
    • wins
    • losses
    • match counters
  • Key:
    leaderboard["main"]
  • Responsibility: Stores and serves top-ranked players.
  • Actions
    • updatePlayer
  • Queues
    • None
  • State
    • SQLite
    • Leaderboard score rows
    • Top-list ordering
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant P as player
	participant M as match
	participant LB as leaderboard

	C->>MM: queueForMatch(username)
	MM->>P: initialize/getRating
	P-->>MM: rating
	Note over MM: store queue row + retry pairing
	MM->>M: create(matchId, assigned players)
	MM-->>C: assignmentReady
	C->>M: connect(username)
	M->>MM: matchCompleted(...)
	MM->>P: applyMatchResult(...)
	MM->>LB: updatePlayer(...)
	Note over MM: remove matches + assignments rows
主题摘要
匹配机制基于ELO的队列配对,随着等待时间增加扩大搜索范围。
网络代码混合模式。客户端拥有移动权及本地预测和插值。服务器拥有投射物、命中判定、匹配结果和评级更新权。
Tick速率20次/秒(
50ms
),固定实时Tick用于确定性节奏和广播频率。
物理引擎中高强度;客户端移动由服务器验证,战斗/命中判定由服务器权威控制。
Actors
  • matchmaker["main"]
  • 职责:运行基于评级的排队、配对、分配持久化和完成结果分发。
  • 动作
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • 队列
    • queueForMatch
    • unqueueForMatch
    • matchCompleted
  • 状态
    • SQLite
    • player_pool
    • matches
    • assignments
      包含评级窗口和连接范围
  • match[matchId]
  • 职责:运行排位匹配阶段、计分和胜者报告。
  • 动作
    • connect
    • 游戏玩法动作
  • 队列
  • 状态
    • JSON
    • phase
    • players
    • score
    • winner
    • completion payload
  • player[username]
  • 职责:存储标准玩家MMR和胜负档案。
  • 动作
    • initialize
    • getRating
    • applyMatchResult
  • 队列
  • 状态
    • JSON
    • rating
    • wins
    • losses
    • match counters
  • leaderboard["main"]
  • 职责:存储并提供顶级玩家排名。
  • 动作
    • updatePlayer
  • 队列
  • 状态
    • SQLite
    • Leaderboard score rows
    • Top-list ordering
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant MM as matchmaker
	participant P as player
	participant M as match
	participant LB as leaderboard

	C->>MM: queueForMatch(username)
	MM->>P: initialize/getRating
	P-->>MM: rating
	Note over MM: store queue row + retry pairing
	MM->>M: create(matchId, assigned players)
	MM-->>C: assignmentReady
	C->>M: connect(username)
	M->>MM: matchCompleted(...)
	MM->>P: applyMatchResult(...)
	MM->>LB: updatePlayer(...)
	Note over MM: remove matches + assignments rows

Turn-Based

回合制

TopicSummary
MatchmakingAsync private-invite and public-queue pairing in the same pattern.
NetcodeServer-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state.
Tick RateNo continuous tick; move submission and turn transitions drive updates.
PhysicsVery low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale.
Actors
  • Key:
    matchmaker["main"]
  • Responsibility: Handles private invite and public queue pairing for async matches.
  • Actions
    • createGame
    • joinByCode
    • queueForMatch
    • unqueueForMatch
    • closeMatch
  • Queues
    • createGame
    • joinByCode
    • queueForMatch
    • unqueueForMatch
    • closeMatch
  • State
    • SQLite
    • matches
    • player_pool
    • assignments
      for invite and queue mapping
  • Key:
    match[matchId]
  • Responsibility: Owns board state, turn order, move validation, and final result.
  • Actions
    • connect
    • makeMove
  • Queues
    • None
  • State
    • JSON
    • board
    • turns
    • players
    • connection presence
    • result
Lifecycle
主题摘要
匹配机制异步私人邀请和公共队列配对使用相同模式。
网络代码服务器权威(基础逻辑)。客户端可在提交前草拟走法。服务器拥有回合所有权、已提交走法日志、回合顺序和完成状态权。
Tick速率无连续Tick;走法提交和回合转换驱动更新。
物理引擎极低强度;无实时物理循环,仅需离散规则验证。索引为可选,主要用于大规模下的棋盘或查询便利。
Actors
  • matchmaker["main"]
  • 职责:处理异步匹配的私人邀请和公共队列配对。
  • 动作
    • createGame
    • joinByCode
    • queueForMatch
    • unqueueForMatch
    • closeMatch
  • 队列
    • createGame
    • joinByCode
    • queueForMatch
    • unqueueForMatch
    • closeMatch
  • 状态
    • SQLite
    • matches
    • player_pool
    • assignments
      用于邀请和队列映射
  • match[matchId]
  • 职责:管理棋盘状态、回合顺序、走法验证和最终结果。
  • 动作
    • connect
    • makeMove
  • 队列
  • 状态
    • JSON
    • board
    • turns
    • players
    • connection presence
    • result
生命周期

Public Queue

公共队列

mermaid
sequenceDiagram
	participant A as Client A
	participant B as Client B
	participant MM as matchmaker
	participant M as match

	A->>MM: queueForMatch()
	B->>MM: queueForMatch()
	Note over MM: pair first two queued players
	MM->>M: create(matchId) + seed X/O players
	MM-->>A: assignment/match info
	MM-->>B: assignment/match info
	A->>M: connect(playerId)
	B->>M: connect(playerId)
	A->>M: makeMove()
	B->>M: makeMove()
	opt all players disconnected for timeout
		Note over M: destroy after idle timeout
	end
	M->>MM: closeMatch(matchId)
mermaid
sequenceDiagram
	participant A as Client A
	participant B as Client B
	participant MM as matchmaker
	participant M as match

	A->>MM: queueForMatch()
	B->>MM: queueForMatch()
	Note over MM: pair first two queued players
	MM->>M: create(matchId) + seed X/O players
	MM-->>A: assignment/match info
	MM-->>B: assignment/match info
	A->>M: connect(playerId)
	B->>M: connect(playerId)
	A->>M: makeMove()
	B->>M: makeMove()
	opt all players disconnected for timeout
		Note over M: destroy after idle timeout
	end
	M->>MM: closeMatch(matchId)

Private Invite

私人邀请

mermaid
sequenceDiagram
	participant A as Client A
	participant B as Client B
	participant MM as matchmaker
	participant M as match

	A->>MM: createGame()
	MM-->>A: {matchId, playerId, inviteCode}
	B->>MM: joinByCode(inviteCode)
	MM->>M: create(matchId) + seed X/O players
	MM-->>A: assignment/match info
	MM-->>B: assignment/match info
	A->>M: connect(playerId)
	B->>M: connect(playerId)
	A->>M: makeMove()
	B->>M: makeMove()
	M->>MM: closeMatch(matchId)
mermaid
sequenceDiagram
	participant A as Client A
	participant B as Client B
	participant MM as matchmaker
	participant M as match

	A->>MM: createGame()
	MM-->>A: {matchId, playerId, inviteCode}
	B->>MM: joinByCode(inviteCode)
	MM->>M: create(matchId) + seed X/O players
	MM-->>A: assignment/match info
	MM-->>B: assignment/match info
	A->>M: connect(playerId)
	B->>M: connect(playerId)
	A->>M: makeMove()
	B->>M: makeMove()
	M->>MM: closeMatch(matchId)

Idle

放置类

TopicSummary
MatchmakingNo matchmaker; each player uses a direct per-player actor and a shared leaderboard actor.
NetcodeServer-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals.
Tick RateNo continuous tick; use
c.schedule.after(...)
for coarse intervals and compute offline catch-up from elapsed wall time.
PhysicsNone for standard idle loops; transitions are discrete (
build
,
collect
,
upgrade
) and do not need spatial indexing.
Actors
  • Key:
    world[playerId]
  • Responsibility: Owns one player's progression, buildings, production scheduling, and state updates.
  • Actions
    • initialize
    • build
    • collectProduction
  • Queues
    • None
  • State
    • JSON
    • Per-player buildings
    • resources
    • timers
    • progression state
  • Key:
    leaderboard["main"]
  • Responsibility: Stores global scores and serves leaderboard updates.
  • Actions
    • updateScore
  • Queues
    • updateScore
  • State
    • SQLite
    • scores
      table keyed by player
    • Current leaderboard totals
Lifecycle
mermaid
sequenceDiagram
	participant C as Client
	participant W as world
	participant LB as leaderboard

	C->>W: getOrCreate(playerId) + initialize()
	Note over W: seed state + schedule collection
	W-->>C: stateUpdate
	loop gameplay loop
		C->>W: build() / collectProduction()
		W->>LB: updateScore(...)
	Note over LB: upsert scores
	LB-->>C: leaderboardUpdate
	W-->>C: stateUpdate
	end
主题摘要
匹配机制无匹配器;每个玩家使用专属的Actor和共享的排行榜Actor。
网络代码服务器权威(基础逻辑)。客户端拥有UI和建造意图权。服务器拥有资源、生产速率、建造验证和排行榜总数权。
Tick速率无连续Tick;使用
c.schedule.after(...)
设置粗粒度间隔,并根据流逝的实际时间计算离线进度补全。
物理引擎标准放置循环无需物理引擎;转换为离散操作(
建造
收集
升级
),无需空间索引。
Actors
  • world[playerId]
  • 职责:管理单个玩家的进度、建筑、生产调度和状态更新。
  • 动作
    • initialize
    • build
    • collectProduction
  • 队列
  • 状态
    • JSON
    • 玩家专属建筑
    • resources
    • timers
    • progression state
  • leaderboard["main"]
  • 职责:存储全局分数并提供排行榜更新。
  • 动作
    • updateScore
  • 队列
    • updateScore
  • 状态
    • SQLite
    • scores
      表按玩家键存储
    • 当前排行榜总数
生命周期
mermaid
sequenceDiagram
	participant C as Client
	participant W as world
	participant LB as leaderboard

	C->>W: getOrCreate(playerId) + initialize()
	Note over W: seed state + schedule collection
	W-->>C: stateUpdate
	loop gameplay loop
		C->>W: build() / collectProduction()
		W->>LB: updateScore(...)
	Note over LB: upsert scores
	LB-->>C: leaderboardUpdate
	W-->>C: stateUpdate
	end

Reference Map

参考地图

Actors

Actors

  • Access Control
  • Actions
  • Actor Keys
  • Actor Scheduling
  • AI and User-Generated Rivet Actors
  • Authentication
  • Cloudflare Workers Quickstart
  • Communicating Between Actors
  • Connections
  • Debugging
  • Design Patterns
  • Destroying Actors
  • Ephemeral Variables
  • Errors
  • External SQL Database
  • Fetch and WebSocket Handler
  • Helper Types
  • Icons & Names
  • In-Memory State
  • Input Parameters
  • Lifecycle
  • Limits
  • Low-Level HTTP Request Handler
  • Low-Level KV Storage
  • Low-Level WebSocket Handler
  • Metadata
  • Next.js Quickstart
  • Node.js & Bun Quickstart
  • Queues & Run Loops
  • React Quickstart
  • Realtime
  • Scaling & Concurrency
  • Sharing and Joining State
  • SQLite
  • SQLite + Drizzle
  • Testing
  • Types
  • Vanilla HTTP API
  • Versions & Upgrades
  • Workflows
  • 访问控制
  • 动作
  • Actor键
  • Actor调度
  • AI与用户生成Rivet Actors
  • 身份验证
  • Cloudflare Workers快速入门
  • Actor间通信
  • 连接
  • 调试
  • 设计模式
  • 销毁Actor
  • 临时变量
  • 错误处理
  • 外部SQL数据库
  • Fetch与WebSocket处理器
  • 辅助类型
  • 图标与名称
  • 内存状态
  • 输入参数
  • 生命周期
  • 限制
  • 底层HTTP请求处理器
  • 底层KV存储
  • 底层WebSocket处理器
  • 元数据
  • Next.js快速入门
  • Node.js & Bun快速入门
  • 队列与运行循环
  • React快速入门
  • 实时功能
  • 扩展与并发
  • 状态共享与加入
  • SQLite
  • SQLite + Drizzle
  • 测试
  • 类型
  • 原生HTTP API
  • 版本与升级
  • 工作流

Clients

客户端

  • Node.js & Bun
  • React
  • Swift
  • SwiftUI
  • Node.js & Bun
  • React
  • Swift
  • SwiftUI

Connect

部署

  • Deploy To Amazon Web Services Lambda
  • Deploying to AWS ECS
  • Deploying to Cloudflare Workers
  • Deploying to Freestyle
  • Deploying to Google Cloud Run
  • Deploying to Hetzner
  • Deploying to Kubernetes
  • Deploying to Railway
  • Deploying to Vercel
  • Deploying to VMs & Bare Metal
  • Supabase
  • 部署到Amazon Web Services Lambda
  • 部署到AWS ECS
  • 部署到Cloudflare Workers
  • 部署到Freestyle
  • 部署到Google Cloud Run
  • 部署到Hetzner
  • 部署到Kubernetes
  • 部署到Railway
  • 部署到Vercel
  • 部署到虚拟机与裸金属服务器
  • Supabase

Cookbook

实践指南

  • Multiplayer Game
  • 多人游戏

General

通用

  • Actor Configuration
  • Architecture
  • Cross-Origin Resource Sharing
  • Documentation for LLMs & AI
  • Edge Networking
  • Endpoints
  • Environment Variables
  • HTTP Server
  • Logging
  • Registry Configuration
  • Runtime Modes
  • Actor配置
  • 架构
  • 跨域资源共享
  • 面向LLM与AI的文档
  • 边缘网络
  • 端点
  • 环境变量
  • HTTP服务器
  • 日志
  • 注册中心配置
  • 运行时模式

Self Hosting

自托管

  • Configuration
  • Docker Compose
  • Docker Container
  • File System
  • Installing Rivet Engine
  • Kubernetes
  • Multi-Region
  • PostgreSQL
  • Railway Deployment
  • 配置
  • Docker Compose
  • Docker容器
  • 文件系统
  • 安装Rivet Engine
  • Kubernetes
  • 多区域部署
  • PostgreSQL
  • Railway部署