Alpha–Beta Lab
Rewriting a classic AngularJS and D3 alpha–beta pruning trainer into a zero-dependency React 18, TypeScript, and pure-SVG application把经典的 AngularJS + D3 Alpha–Beta 剪枝练习工具,重写为零额外运行时依赖的 React 18、TypeScript 与纯 SVG 应用
November 20252025年11月
Static textbook trees are terrible at teaching alpha–beta pruning. They show you the final crossed-out branches after the search has already finished, hiding the exact sequence of depth-first visits where alpha and beta tighten enough to trigger a cutoff. UC Berkeley's classic CS61B practice tool (originally built by Aleks Kamko) solved that problem years ago, but its implementation lived in AngularJS and imperative D3 DOM bindings.
I rebuilt the tool from the ground up in React 18, TypeScript 5.6, and Vite with a deliberate constraint: zero runtime dependencies beyond React itself. Dropping D3 meant owning every piece of the stack directly—compiling recursive minimax into a reversible timeline, computing dynamic SVG geometry by hand, and implementing inline keyboard editing inside raw SVG without reaching for an external canvas or diagram library.
教材里的静态博弈树极不适合教 Alpha–Beta 剪枝。它们只给你看搜完之后划掉的叉,却藏起了深度优先遍历里 α 和 β 一步步收紧、最终触发截断的完整过程。UC Berkeley 经典的 CS61B 练习工具(最初由 Aleks Kamko 编写)早年就解决了这个问题,只是代码停在 AngularJS 和命令式 D3 DOM 绑定上。
我用 React 18、TypeScript 5.6 和 Vite 把它从头重写了一遍,并定下条刻意约束:除了 React 本身,零运行时依赖。拿掉 D3 意味着整条链路都得自己扛:把递归极小极大编译成可逆时间线、手算动态 SVG 几何,并在原生 SVG 里做出内联键盘编辑,不借任何外部画布或图表库。
Compiling recursive search into a reversible command queue把递归搜索编译成可逆命令队列
The hardest software design problem in an algorithm visualizer isn't writing alpha–beta pruning—it's making recursion step backward, pause, jump to the end, and scrub at arbitrary speed. Trying to suspend a live recursive call stack with timers or async generators quickly gets messy, and snapshotting the entire tree on every step wastes memory as branching factor and depth grow.
Instead, the solver runs the complete traversal once up front and compiles it into an ActionListQueue—a linear sequence of atomic mutation frames.1 Each frame holds one or more typed Action objects storing (object, key, oldVal, newVal) with symmetric apply() and reverse() methods. Entering a node pushes a frame that highlights both the incoming edge and node while initializing alpha and beta; returning from a child pushes updates to the parent's value and bound; and hitting β ≤ α recursively emits prune actions across every remaining unvisited subtree.
Once the traversal is represented as reversible command frames, every playback control falls out of the same tiny primitive. Stepping forward applies the next frame; stepping backward reverses the current frame in place; jumping to the beginning or end loops until the queue boundary; and Play/Pause simply schedules recursive timeouts against a 25 ms to 1,675 ms speed slider.
That single precomputation pass also pulls double duty as the answer key. While building the command queue, the solver caches each node's ground-truth value, alpha, beta, and pruned flags directly on the graph, so Check Answer and Show Solution verify or fill in a student's work against the exact same traversal without maintaining a second evaluator.2
Treating a recursive search as a compiler that emits reversible mutation frames turns step-forward, step-backward, scrubbing, and answer checking into one small data structure.
算法可视化最难的设计从来不是写 Alpha–Beta 剪枝本身,而是让递归支持单步回退、暂停、直达终点和任意倍速播放。拿定时器或异步生成器硬挂起实时调用栈很快就会乱套,每步深拷贝整棵树又会在分支因子和深度上去后白白吃内存。
于是求解器改成提前一次跑完遍历,把它编译进 ActionListQueue——一条由原子变更帧排成的线性序列。1 每帧装一个或多个类型化 Action(记录 object、key、oldVal、newVal),带对称的 apply() 和 reverse() 方法。进节点时压入高亮入边与节点并初始化 α/β 的帧;子节点返回时压入更新父节点值与边界的帧;一旦命中 β ≤ α,就递归对剩下未访问子树发出剪枝动作。
遍历一旦变成可逆命令帧,所有播放控制都从同一个小原语里自然长出来:单步前进应用下一帧,单步后退原地反转当前帧,跳开头或结尾循环走到队列两端,播放/暂停只是按 25 ms 到 1,675 ms 的速度滑块调度递归定时器。
这遍预计算还顺手兼任标准答案。建命令队列的同时,求解器把每个节点的真值、α、β 和剪枝标记缓存在图上,Check Answer 和 Show Solution 直接对照同一趟遍历核对或填入答案,不用维护第二套求值器。2
把递归搜索当成吐出可逆变更帧的编译器,前进、回退、拖动和答案核对瞬间收束成同一个小数据结构。
Pure-React SVG geometry and fat hit-targets without D3不用 D3 的纯 React SVG 几何与宽触控热区
Removing D3 meant replacing its tree layout and enter/update/exit selections with a small, deterministic recursive layout function inside TreeCanvas. Rather than shrinking triangles until labels collide on deeper trees, the canvas locks each node to a fixed 80-pixel side length—computing equilateral triangle height and centroid offsets analytically, rendering Max nodes upright, rotating Min nodes 180 degrees, and centering leaf squares—and grows the SVG surface dynamically based on total leaf count (branching factor raised to depth minus one) inside a scrollable container.3
Layout itself is a top-down interval subdivision: starting from the usable horizontal span, each node sits at the midpoint of its interval and partitions that width evenly among its children. On top of those coordinates, the component renders either standard α / β bound pairs or Cutoff notation (c ≥ β on Max nodes, c ≤ α on Min nodes), formatting ±Infinity cleanly as ∞ and −∞.
One small SVG detail matters a lot in practice: a 1-to-2-pixel path is frustrating to click when a student is trying to mark pruned edges by hand. Every edge therefore renders as two stacked SVG paths—the visible stroke plus a wider invisible mouselink hit-target that toggles the edge's pruned flag whenever the tree is mutable, and automatically locks out edits the moment an animation starts.
拿掉 D3 意味着在 TreeCanvas 里写一段小巧确定的递归布局替代其树布局和 enter/update/exit 选择器。为了防止树深以后三角形缩成一团、文字撞车,画布把每个节点锁死在 80 像素边长(解析算出等边三角形高和质心偏移,Max 节点正放、Min 节点转 180 度、叶节点居中画方块),再按总叶数(分支因子的深度减一次方)在可滚动容器里动态撑开 SVG 画布。3
布局本身是自顶向下的区间等分:从可用水平跨度出发,每个节点落在区间中点,把宽度均分给子节点。坐标之上,组件可切标准 α / β 边界对或 Cutoff 记法(Max 节点 c ≥ β、Min 节点 c ≤ α),并把 ±Infinity 干净地格式化成 ∞ 与 −∞。
实际用起来有个小细节特别要紧:学生练习手动标剪枝边时,点一根 1–2 像素细线极容易点偏。于是每条边叠画两根 SVG 路径——一根可见描边,加一根更宽的透明 mouselink 热区,树可编辑时一点就能切剪枝标记,动画一开播自动上锁。
Inline keyboard editing inside raw SVG with a Canvas 2D caret在原生 SVG 里用 Canvas 2D 光标做内联键盘编辑
Letting students click any node and type a value directly inside the triangle is where SVG apps usually reach for HTML foreignObject overlays—which notoriously misalign across browser zoom levels and font metrics. I skipped foreignObject completely and handled keyboard input directly on the focusable SVG root: digits, minus signs, decimals, Backspace, Left/Right arrows, Enter to commit, Escape to cancel, and background mousedown to commit the active selection.
The tricky part of SVG-native text editing is positioning the blinking caret inside centered text. Because SVG text doesn't expose a native input cursor, TreeCanvas lazily allocates a single offscreen HTML5 Canvas 2D context and calls measureText() twice—once on the full string to find its half-width offset from center, and once on the substring before the caret index—to position a 1.5-pixel blinking SVG rectangle right between the characters.4
让学生点任意节点直接在三角形里打字,SVG 应用通常会上 HTML foreignObject 浮层,可这东西在不同浏览器缩放比例和字体度量下出了名地容易错位。我干脆跳过 foreignObject,在可聚焦的 SVG 根节点上亲自接管键盘输入:数字、负号、小数点、Backspace、左右方向键、Enter 提交、Escape 取消,以及点空白背景提交当前选中项。
SVG 原生文本编辑最棘手的是把闪烁光标放到居中文本的准确位置。SVG 文本没有原生输入光标,TreeCanvas 便懒加载一个离屏 HTML5 Canvas 2D 上下文,调两次 measureText()——一次量整串宽算出居中左偏移,一次量光标前子串宽——把一根 1.5 像素闪烁 SVG 竖线严丝合缝插进字符之间。4
Honest trade-offs in keeping a mutable graph保留可变图的坦诚工程权衡
Porting a classic imperative tool into React 18 surfaces an interesting architectural tension. Keeping the Tree graph mutable inside a ref—paired with an explicit forceTick counter to trigger React re-renders after each Action.apply() or Action.reverse()—kept the command-pattern port compact, fast, and faithful to the original algorithm with zero deep cloning per step.
The trade-off is that you give up React's pure immutable data flow: every mutation path has to remember to trigger a render and respect the tree.mutable lock while an animation is running, and editing a node after starting an animation requires resetting the queue. For a small, focused zero-dependency teaching tool deployed statically to GitHub Pages, that pragmatic boundary kept the whole codebase under a few hundred lines of readable TypeScript while remaining easy to inspect and extend.
把经典命令式工具迁到 React 18,会碰上一处有意思的架构张力。把 Tree 图作为可变对象放进 ref、每次 Action.apply() 或 Action.reverse() 后靠显式 forceTick 计数触发重渲染,让整套命令模式移植保持短小、飞快,且忠实于原算法,每步零深拷贝。
代价是放弃了 React 纯不可变数据流:每条修改路径都得记得触发渲染、动画跑起来时守住 tree.mutable 锁,开播后再改节点也必须重置队列。对一个静态挂在 GitHub Pages 上的小型零依赖教学工具来说,这道务实边界把整套代码稳稳压在几百行清晰可读的 TypeScript 里,好查也好改。
Notes注释
- Each step in ActionListQueue is an Array<Action>, so compound transitions—like updating a parent's value and alpha bound together when a leaf returns—apply and reverse atomically in a single step.↩︎ActionListQueue 的每一步都是 Array<Action>,所以复合变更(比如叶节点返回时同步更新父节点值与 α 边界)会在单步内原子生效和回退。↩︎
- checkAnswer() recursively verifies every non-leaf node's entered value against its cached ground-truth value and confirms every edge that should have been pruned is marked pruned by the user.↩︎checkAnswer() 递归核对每个非叶节点输入值与缓存真值是否一致,并确认每条应当剪枝的边都已被用户标出。↩︎
- Canvas dimensions scale as width = max(viewportWidth, 2 × marginX + b^(d−1) × 1.6 × nodeSide) and height = max(viewportHeight, marginTop + (d−1) × 2 × nodeSide + marginX), keeping node legibility constant even at higher depths or branching factors.↩︎画布尺寸按 width = max(viewportWidth, 2 × marginX + b^(d−1) × 1.6 × nodeSide) 与 height = max(viewportHeight, marginTop + (d−1) × 2 × nodeSide + marginX) 缩放,高深度或高分支因子下节点依然清晰。↩︎
- Caret x-coordinate is computed as node.x − measureTextWidth(fullText) / 2 + measureTextWidth(fullText.slice(0, charIndex)) using the same font size and family as the rendered SVG value text.↩︎光标横坐标按 node.x − measureTextWidth(fullText) / 2 + measureTextWidth(fullText.slice(0, charIndex)) 计算,与 SVG 数值文本共用完全一致的字号和字族。↩︎
Built with React 18, TypeScript 5.6, Vite, and zero-dependency SVG rendering; deployed statically to GitHub Pages.使用 React 18、TypeScript 5.6、Vite 与零依赖纯 SVG 渲染构建,静态部署于 GitHub Pages。
Stack: React, TypeScript, SVG, Algorithms, Vite.技术栈:React、TypeScript、SVG、Algorithms、Vite。