Rust + WebAssembly 实现康威生命游戏

server/2025/3/18 21:21:50/

1. 设计思路

1.1 选择有限的世界

康威生命游戏的世界是 无限二维网格,但由于 计算机内存有限,我们可以选择三种有限宇宙方案:

  1. 动态扩展:仅存储“活跃区域”,按需扩展(可能无限增长)。
  2. 固定大小,无边界扩展:边界处的细胞会被“消灭”。
  3. 固定大小,环绕宇宙(Toroidal Universe (我们采用此方案)

环绕宇宙(Toroidal Universe)允许 滑翔机(Gliders) 无限运行,不会被边界限制:

  • 上边界的细胞连接到下边界
  • 左边界的细胞连接到右边界

2. Rust 代码实现

2.1 定义 Cell 结构

rust">#[wasm_bindgen]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {Dead = 0,Alive = 1,
}

说明

  • #[repr(u8)]:让 Cell 占用 1 字节,减少内存浪费。
  • Dead = 0, Alive = 1:使得 Cell 可以直接用整数加法计算邻居数

2.2 定义 Universe

rust">#[wasm_bindgen]
pub struct Universe {width: u32,height: u32,cells: Vec<Cell>,
}

说明

  • widthheight:宇宙的宽度和高度
  • cells: Vec<Cell>:存储所有细胞状态(0=死,1=活)

2.3 计算网格索引

rust">impl Universe {fn get_index(&self, row: u32, column: u32) -> usize {(row * self.width + column) as usize}
}
  • 计算二维网格一维数组中的索引。

2.4 计算活邻居数量

rust">impl Universe {fn live_neighbor_count(&self, row: u32, column: u32) -> u8 {let mut count = 0;for delta_row in [self.height - 1, 0, 1].iter().cloned() {for delta_col in [self.width - 1, 0, 1].iter().cloned() {if delta_row == 0 && delta_col == 0 {continue;}let neighbor_row = (row + delta_row) % self.height;let neighbor_col = (column + delta_col) % self.width;let idx = self.get_index(neighbor_row, neighbor_col);count += self.cells[idx] as u8;}}count}
}

说明

  • 使用 modulo 计算 环绕宇宙,确保邻居索引不会溢出。
  • 避免 if 语句,减少特殊情况处理,提高性能。

2.5 更新下一代状态

rust">#[wasm_bindgen]
impl Universe {pub fn tick(&mut self) {let mut next = self.cells.clone();for row in 0..self.height {for col in 0..self.width {let idx = self.get_index(row, col);let cell = self.cells[idx];let live_neighbors = self.live_neighbor_count(row, col);let next_cell = match (cell, live_neighbors) {(Cell::Alive, x) if x < 2 => Cell::Dead,(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,(Cell::Alive, x) if x > 3 => Cell::Dead,(Cell::Dead, 3) => Cell::Alive,(otherwise, _) => otherwise,};next[idx] = next_cell;}}self.cells = next;}
}

说明

  • 规则翻译
    • 活细胞 < 2 → 死亡(过少
    • 活细胞 = 2 or 3 → 存活(繁衍
    • 活细胞 > 3 → 死亡(过度拥挤
    • 死细胞 = 3 → 复活(繁殖

2.6 初始化宇宙

rust">#[wasm_bindgen]
impl Universe {pub fn new() -> Universe {let width = 64;let height = 64;let cells = (0..width * height).map(|i| if i % 2 == 0 || i % 7 == 0 { Cell::Alive } else { Cell::Dead }).collect();Universe {width,height,cells,}}pub fn render(&self) -> String {self.to_string()}
}
  • 初始化:创建 64x64 网格,细胞 随机分布
  • 实现 render():在 JavaScript 中调用,返回网格字符串。

3. JavaScript 前端

wasm-game-of-life/www/index.js 编写 Canvas 渲染 代码。

3.1 JavaScript 初始化

import { Universe, Cell, memory } from "wasm-game-of-life";const CELL_SIZE = 5;
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";const universe = Universe.new();
const width = universe.width();
const height = universe.height();

3.2 绘制网格

const drawGrid = () => {ctx.beginPath();ctx.strokeStyle = GRID_COLOR;for (let i = 0; i <= width; i++) {ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1);}for (let j = 0; j <= height; j++) {ctx.moveTo(0, j * (CELL_SIZE + 1) + 1);ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1);}ctx.stroke();
};

3.3 读取 WebAssembly 内存

const drawCells = () => {const cellsPtr = universe.cells();const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);ctx.beginPath();for (let row = 0; row < height; row++) {for (let col = 0; col < width; col++) {const idx = row * width + col;ctx.fillStyle = cells[idx] === Cell.Dead ? DEAD_COLOR : ALIVE_COLOR;ctx.fillRect(col * (CELL_SIZE + 1) + 1, row * (CELL_SIZE + 1) + 1, CELL_SIZE, CELL_SIZE);}}ctx.stroke();
};

3.4 动画渲染

const renderLoop = () => {universe.tick();drawGrid();drawCells();requestAnimationFrame(renderLoop);
};drawGrid();
drawCells();
requestAnimationFrame(renderLoop);

4.运行项目

wasm-pack build
cd www
npm install
npm run start

打开 http://localhost:8080/,你会看到 动态演化的生命游戏
在这里插入图片描述


http://www.ppmy.cn/server/176054.html

相关文章

Java Stream API 的使用

java8引入的java.util.stream.Stream流操作&#xff0c;使得访问和操作数组&#xff08;Array&#xff09;、集合&#xff08;Collection&#xff09;变得非常方便和优雅。 1、过滤元素和转化元素类型 private static void filterMapToInt() {List<String> list new Arr…

深度学习技巧

胡适的英语老师、出版家王云五先生是这样自学英语写作的&#xff1a;找一篇英文的名家佳作&#xff0c;熟读几次以后&#xff0c;把它翻译成中文&#xff1b;一星期之后&#xff0c;再将中文反过来翻译成英文&#xff0c;翻译期间绝不查阅英语原文&#xff1b;翻译好后再与原文…

CF 230B. T-primes

题目 time limit per test&#xff1a;2 seconds&#xff1b;memory limit per test&#xff1a;256 megabytes We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, well call a positive integer t Т-prime,…

时间有限,如何精确设计测试用例?5种关键方法

精确设计测试用例能够迅速识别并修复主要缺陷&#xff0c;确保产品质量&#xff0c;降低后期维护成本&#xff0c;并通过专注于核心功能来提升用户体验&#xff0c;为项目的成功奠定坚实基础。若未能精确设计测试用例&#xff0c;可能会导致关键功能测试不充分&#xff0c;使得…

Pandas与PySpark混合计算实战:突破单机极限的智能数据处理方案

引言&#xff1a;大数据时代的混合计算革命 当数据规模突破十亿级时&#xff0c;传统单机Pandas面临内存溢出、计算缓慢等瓶颈。PySpark虽能处理PB级数据&#xff0c;但在开发效率和局部计算灵活性上存在不足。本文将揭示如何构建PandasPySpark混合计算管道&#xff0c;在保留…

定义模型生成数据表

1. 数据库配置 js import { Sequelize, DataTypes } from sequelize; // 创建一个 Sequelize 实例&#xff0c;连接到 SQLite 数据库。 export const sequelize new Sequelize(test, sa, "123456", { host: localhost, dialect: sqlite, storage: ./blog.db })…

第十五届蓝桥杯C/C++B组拔河问题详解

解题思路 这道题目的难点在于枚举所有区间&#xff0c;并且区间不能重合&#xff0c;那么这样感觉就很难了。但是用下面这种方法就会好很多。 我们只需要将左边的所有区间的各种和放在一个set中&#xff0c;然后我们在枚举右边的所有区间的和去和它进行比较&#xff0c;然后…

DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加列宽调整功能,示例Table14_13可展开行的固定表头表格

前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加列宽调整功能,示例Table14_13可展开行的固…