Flappy Birb

Stress-testing Functional Reactive Programming in TypeScript and RxJS 7—where physics, collisions, ghost replays, and SVG DOM writes all flow through pure streams在 TypeScript 与 RxJS 7 里给函数式响应式编程做一次压力测试:物理、碰撞、幽灵回放与 SVG DOM 写入全部流经纯数据流

Tutorials make functional reactive programming look effortless on debounced search boxes and counter buttons. A real-time arcade game is a much harsher stress test: a fixed-rate tick clock, keyboard jumps, restarts, gravity, boundary knockbacks, pipe collisions, invulnerability timers, semi-transparent ghost replays of every prior run, and a leaderboard all collide on every frame.

Flappy Birb was built in TypeScript, Vite, and RxJS 7 with zero UI frameworks under one strict engineering rule: every piece of game logic lives as a pure (State) -> State transformation, and every DOM mutation is quarantined inside a single terminal subscribe() boundary.

教程总能把函数式响应式编程讲得云淡风轻,因为例子不过是防抖搜索框和计数器。实时街机游戏则是苛刻得多的试金石:固定节拍时钟、键盘跳跃、重开、重力、边界反弹、管道碰撞、无敌计时、每一局历史轨迹的半透明幽灵回放与排行榜,全在每一帧迎面相撞。

Flappy Birb 用 TypeScript、Vite 与 RxJS 7 零 UI 框架写成,只守一条死规矩:全部游戏逻辑都是纯函数 (State) -> State 变换,所有 DOM 写入严格关在唯一一个末端 subscribe() 边界里。

Folding ticks, jumps, and restarts into one immutable stream把节拍、跳跃与重开折叠成一条不可变状态流

Instead of a mutable game loop updating module-level variables, three independent source Observables drive the entire simulation: tick$ fires on a fixed interval, jump$ fires on the Space key, and restart$ listens to R, Enter, and Escape while guarding itself with gameEnd(state) so stray keystrokes mid-flight are no-ops. Each stream maps raw events into pure state-transformer functions (State) -> State, merges them into allActions$, and folds them with scan() to produce a single immutable gameState$ stream.

Inside tick(state), every frame executes a four-stage pure pipeline: first, advance bird kinematics, horizontal scroll offset, and elapsed time; second, check top and bottom boundary collisions when the bird is not invulnerable; third, advance pipe statuses from pending to passed or collision (recording impact direction) and detect newly collided pipes by diffing pre- and post-update statuses; fourth, tick down the invulnerability timer.1

Even randomness had to be made pure. Early drafts called Math.random() to vary bounce velocity after a hit, which broke referential transparency and made collision tests flaky. Refactoring bounce physics to inject a deterministic RNG provider seeded by state.elapsedTime kept knockback impulses varied during play yet completely reproducible in unit tests.

Once every game event is just a pure function from old state to new state, physics, collisions, invulnerability, and restarts stop fighting over shared mutable variables.

这里没有一边循环一边改模块全局变量的传统游戏主循环,而是三条独立源 Observable 驱动整场模拟:tick$ 按固定间隔触发,jump$ 监听空格键,restart$ 监听 R、Enter、Escape 并用 gameEnd(state) 守卫,飞行途中误触直接空操作。每条流先把原始事件映成纯状态变换函数 (State) -> State,再经 merge 汇成 allActions$,最后用 scan() 折叠出唯一一条不可变 gameState$ 流。

在 tick(state) 里,每帧跑四段纯流水线:一、推进小鸟运动学、水平滚动偏移与已过时间;二、非无敌时检上下边界碰撞;三、推进管道状态(从 pending 到 passed 或 collision 并记下撞击方向),对比前后差值找出本帧新撞管道;四、递减无敌计时器。1

连随机数都得纯化。初版撞击后调 Math.random() 变反弹初速度,破坏了引用透明性,碰撞单测也跟着时好时坏。把反弹物理改成注入以 state.elapsedTime 为种子的确定性随机数提供器后,玩起来弹跳依然有变化,单元测试则百分之百可复现。

一旦每个游戏事件都只是从旧状态到新状态的纯函数,物理、碰撞、无敌和重开就再也不会去抢共享可变变量。

Multi-run ghost replays as a pure derived Observable作为纯派生 Observable 的多局幽灵回放

One of the cleanest payoffs of keeping game state immutable is the ghost replay system. Rather than pushing coordinates into a global history array whenever a run ends, createObservableGhostSystem(gameState$) is simply a second pure scan() derived from gameState$.

During an active run, the accumulator records the bird's world coordinates (bird.x + scrollOffset, bird.y) keyed by elapsedTime only when the bird actually moves. The moment state.session.currentRun increments on restart, handleRunTransition archives the completed run's immutable PositionMap alongside a pre-sorted timestamp index and resets the active recorder. On every subsequent tick, findAllGhostPositions looks up the latest recorded timestamp at or before elapsedTime for every completed run, projects each ghost back into screen space by subtracting the current scrollOffset, drops ghosts that have scrolled past the left margin, and deduplicates emissions with distinctUntilChanged(ghostMapEqual).2

守住状态不可变最利落的回报之一,就是幽灵回放系统。我们没在每局结束时往全局历史数组里推坐标,而是把 createObservableGhostSystem(gameState$) 做成直接派生自 gameState$ 的第二条纯 scan() 流。

单局进行时,累加器只在小鸟真实位移时按 elapsedTime 记下世界坐标(bird.x + scrollOffset, bird.y)。重开令 state.session.currentRun 递增那一刻,handleRunTransition 就把刚结束那一局的不可变 PositionMap 连同预排序时间戳索引归档,并重置当前记录器。此后每帧,findAllGhostPositions 为每局历史找不晚于当前 elapsedTime 的最新坐标,减去当前 scrollOffset 投回屏幕空间,剔掉滚出左边界的幽灵,再经 distinctUntilChanged(ghostMapEqual) 去重输出。2

Pure SVG descriptors, dynamic pipe weights, and quarantined DOM writes纯 SVG 描述符、动态管道权重与被隔离的 DOM 写入

To keep rendering just as testable as physics, rendering.ts never touches document during computation. Level geometry arrives from assets/map.csv via RxJS fromFetch—waiting for the first click outside #themeToggle through switchMap—and parsePipeData precomputes gap-height percentile thresholds once up front: the narrowest 10% of pipe gaps earn 3 points, the next 30% earn 2 points, and the rest earn 1 point, turning runtime scoring into a single reduce() over passed pipes.3

On every frame, createRenderDataPipeline combines gameState$ and ghostPositions$ into a plain RenderData structure made of SvgElementData descriptors ({ namespace, name, props }) for visible pipes (body, stripe, overhanging cap, centered score weight label, and omitting the struck top or bottom half on impact), visible ghost birds, the player sprite (dimmed during invulnerability), and HUD text. Only at the single terminal subscribe() boundary do we call Object.freeze(state) and Object.freeze(renderData) as a runtime immutability guard before flushing the SVG DOM. Non-game chrome—the light/dark #themeToggle and the top-scores leaderboard—runs in a separate attachUiEffects stream so UI plumbing never leaks into physics.4

为了让渲染和物理一样好单测,rendering.ts 计算阶段绝不碰 document。关卡几何经 RxJS fromFetch 从 assets/map.csv 拉取(通过 switchMap 等 #themeToggle 之外的首次点击),parsePipeData 提前一次算出缝隙高度百分位阈值:最窄 10% 的管道缝隙值 3 分,接下来 30% 值 2 分,其余 1 分,运行时计分直接缩成对已通过管道的一次 reduce()。3

每帧 createRenderDataPipeline 把 gameState$ 和 ghostPositions$ 合成纯数据 RenderData,由 SvgElementData 描述符({ namespace, name, props })表达可见管道(管身、条纹、凸檐、居中分值标签,以及撞击后省略被撞的半截)、可见幽灵鸟、玩家精灵(无敌时变暗)与 HUD 文案。直到唯一末端 subscribe() 边界,才先调 Object.freeze(state) 和 Object.freeze(renderData) 作运行时不可变守卫,再刷新 SVG DOM。非游戏外框(浅/深色 #themeToggle 与高分榜)走单独的 attachUiEffects 流,绝不让界面杂务渗进物理核心。4

Where strict statelessness shines—and where it trades off彻底无状态渲染的甜头与代价

Keeping the renderer completely stateless—clearing previous SVG children (while preserving the #gameOver overlay on top) and mounting fresh elements from RenderData every tick—eliminates an entire class of stale-DOM bugs and makes every frame a pure function of state. For an arcade viewport with a handful of visible pipes and ghosts, it runs smoothly at 60 FPS.

The trade-off is clear if you imagine scaling up: rebuilding DOM nodes on every tick wouldn't survive hundreds of active sprites without keyed reconciliation or Canvas 2D, and keeping every completed run inside immutable Map copies in scan works cleanly for short sessions but would eventually need a bounded ring buffer for marathon play. As a compact FRP engineering exercise in TypeScript and RxJS 7, though, holding that pure-core / single-sink line made the whole game unusually easy to reason about and test in Vitest.

把渲染器做成彻底无状态(每帧清空旧 SVG 子节点、保留置顶 #gameOver 遮罩,再按 RenderData 重新挂载),直接消灭一整类脏 DOM Bug,让每帧都成为状态的纯函数。面对街机视口里寥寥几根可见管道和几只幽灵,60 FPS 跑得很稳。

往大处想代价也明白:同屏要是有几百个活跃精灵,每帧重建 DOM 节点不靠 keyed diff 或 Canvas 2D 肯定撑不住;在 scan 里把每一局都留成不可变 Map 拷贝适合短局,马拉松连玩早晚需要有界环形缓冲。作为一次紧凑的 TypeScript 与 RxJS 7 函数式响应式工程实践,死守纯核心 / 单订阅边界让整款游戏格外好推理,也好在 Vitest 里测透。

Notes注释

  1. Pipe passing triggers as soon as the bird's right edge clears the pipe's right edge—even while invulnerable—with an off-screen fallback so no pipe stays stuck in pending state and prevents gameEnd(state) from completing.↩︎只要小鸟右缘越过管道右缘即触发通过(哪怕处于无敌期),并配出屏兜底,确保没有管道卡死在 pending 状态而阻止 gameEnd(state) 正常结束。↩︎
  2. Ghost recording stops immediately once gameEnd(state) turns true, matching the same guard in jump(state) so post-collision keystrokes can't corrupt a run's final recorded coordinates.↩︎gameEnd(state) 为真时幽灵录制立刻停止,与 jump(state) 的守卫保持一致,防止撞击后的按键污染本局最终坐标。↩︎
  3. A companion npm run generate-pipes script generates randomized CSV pipe maps into assets/map.csv with normalized gapY, gapHeight, and spawn time columns.↩︎配套脚本 npm run generate-pipes 可往 assets/map.csv 生成带归一化 gapY、gapHeight 与生成时间列的随机管道地图。↩︎
  4. The SVG viewBox is initialized once via renderData$.pipe(take(1)) rather than rewritten on every frame, keeping one-time setup cleanly separated from per-frame DOM updates.↩︎SVG viewBox 通过 renderData$.pipe(take(1)) 只初始化一次,不每帧重写,把一次性初始化与逐帧 DOM 更新干净拆开。↩︎

Built with Vite, TypeScript, RxJS 7, Vitest, and pure SVG rendering under a strict pure-core / single-subscription FRP architecture.在严格的纯核心 / 单订阅 FRP 架构下,使用 Vite、TypeScript、RxJS 7、Vitest 与纯 SVG 渲染构建。

Stack: RxJS, TypeScript, SVG, Functional Reactive Programming, Vitest.技术栈:RxJS、TypeScript、SVG、Functional Reactive Programming、Vitest。