一、前言
在前期的实现中,我们使用 Rust 编写核心逻辑,并通过 WebAssembly 将其引入到 Web 环境中,再利用 JavaScript 进行渲染。接下来,我们将在这一基础上增加用户交互功能,使模拟过程不仅能够自动演化,还能支持用户对细胞状态进行手动修改。
二、实现暂停与恢复游戏
1. 在 HTML 中添加按钮
首先,在 wasm-game-of-life/www/index.html
文件中,在 <canvas>
上方添加一个按钮,用于控制游戏的暂停与恢复:
<button id="play-pause"></button>
2. 在 JavaScript 中管理动画
为了控制动画,我们需要保存 requestAnimationFrame
返回的标识符,以便后续通过 cancelAnimationFrame
取消动画调用。在 wasm-game-of-life/www/index.js
中,新增如下代码:
let animationId = null;// renderLoop 函数负责绘制网格、细胞并更新状态
const renderLoop = () => {drawGrid();drawCells();universe.tick();animationId = requestAnimationFrame(renderLoop);
};// 判断游戏是否暂停
const isPaused = () => {return animationId === null;
};const playPauseButton = document.getElementById("play-pause");// 开始游戏,设置按钮图标并启动动画
const play = () => {playPauseButton.textContent = "⏸";renderLoop();
};// 暂停游戏,更新按钮图标并取消下一帧动画
const pause = () => {playPauseButton.textContent = "▶";cancelAnimationFrame(animationId);animationId = null;
};// 根据当前状态切换播放和暂停
playPauseButton.addEventListener("click", event => {if (isPaused()) {play();} else {pause();}
});// 初始化时调用 play() 启动动画
play();
通过这段代码,我们可以根据 animationId
的状态判断游戏是否在播放,并相应地启动或暂停动画。同时,按钮的图标也会显示对应的状态。
三、实现点击切换细胞状态
为了让用户能直接在画布上点击修改细胞状态,我们需要在 Rust 和 JavaScript 端分别进行处理。
1. Rust 端的修改
在 wasm-game-of-life/src/lib.rs
文件中,为 Cell
添加一个 toggle
方法,用于切换细胞状态:
impl Cell {fn toggle(&mut self) {*self = match *self {Cell::Dead => Cell::Alive,Cell::Alive => Cell::Dead,};}
}
接着,在 Universe
的公开接口中添加 toggle_cell
方法,这样 JavaScript 就能调用它来切换指定行列上的细胞状态:
#[wasm_bindgen]
impl Universe {pub fn toggle_cell(&mut self, row: u32, column: u32) {let idx = self.get_index(row, column);self.cells[idx].toggle();}
}
通过 #[wasm_bindgen]
标注,该方法会被导出至 JavaScript 环境中。
2. JavaScript 端的处理
在 wasm-game-of-life/www/index.js
中,为 <canvas>
添加点击事件监听器,完成以下步骤:
- 获取点击事件相对于页面的坐标;
- 将页面坐标转换为
<canvas>
内部的坐标; - 根据坐标计算出对应的行和列;
- 调用
universe.toggle_cell
切换细胞状态; - 重新绘制网格和细胞以更新界面显示。
具体实现如下:
canvas.addEventListener("click", event => {const boundingRect = canvas.getBoundingClientRect();const scaleX = canvas.width / boundingRect.width;const scaleY = canvas.height / boundingRect.height;const canvasLeft = (event.clientX - boundingRect.left) * scaleX;const canvasTop = (event.clientY - boundingRect.top) * scaleY;const row = Math.min(Math.floor(canvasTop / (CELL_SIZE + 1)), height - 1);const col = Math.min(Math.floor(canvasLeft / (CELL_SIZE + 1)), width - 1);universe.toggle_cell(row, col);drawGrid();drawCells();
});
通过以上代码,当用户点击 <canvas>
时,就能实现对对应位置细胞状态的即时切换,从而自由绘制自定义图案。
四、效果预览
完成上述步骤后,使用 wasm-pack build
重建项目,然后刷新 http://localhost:8080/
。你将会看到:
- 点击页面上的按钮可以暂停或恢复游戏的动画;
- 在暂停状态下,点击画布即可改变相应位置细胞的状态,实现自定义图案的绘制。
五、总结
通过本文,我们实现了基于 WebAssembly 的 Game of Life 模拟的交互功能:
- 利用 JavaScript 控制动画的暂停和恢复,使得用户能够在需要时停下演化过程进行编辑;
- 通过点击
<canvas>
切换细胞状态,让自定义图案的绘制变得直观便捷。
这种前后端技术的紧密结合展示了现代 Web 开发中多技术协作的魅力,为进一步扩展和优化应用提供了坚实基础。希望这篇博客能为你提供有价值的参考,激发你探索更多有趣的功能扩展和优化方案。
Happy coding!