康威生命游戏(Conway's Game of Life,又称康威生命棋)是一个模拟生物细胞存活、繁殖与灭亡的游戏。虽然这个称为「游戏」,但它其实不怎么好玩,它是透过电脑来模拟出一个培养皿空间,这个培养皿中在一开始会被放置一些虚拟细胞,而这些细胞会遵循一些「游戏规则」来决定其在下一个阶段是持续生存、还是要繁殖、抑或是毁灭。借由图像化这个培养皿,我们可以从中观察到一些有趣(?)的图像。
康威生命游戏的规则
康威生命游戏的培养皿是一个二维矩形空间,矩形被整齐划分成无数个小方形格子,一个格子可以容纳一个活细胞。
如上图,表示一个大小为 5x5 的培养皿。如果正中间的格子有活细胞存在,以黑色来填满它,如下图:
每个格子都会与其周围 8 格的空间进行交互。如下图,绿色的格子会与红色的格子进行交互:
格子与格子间交互的结果会影响着下一个阶段培养皿中活细胞的数量以及分布。以下继续介绍交互规则。
规则一:若绿色格子有活细胞,且红色格子的区域中的活细胞数量未满两个时,绿色格子的活细胞将会死亡。(模拟生命数量稀少)
规则二:若绿色格子有活细胞,且红色格子的区域中的活细胞数量为两个或是三个时,绿色格子的活细胞将继续存活。(模拟生命数量适中)
规则三:若绿色格子有活细胞,且红色格子的区域中的活细胞数量超过三个时,绿色格子的活细胞将会死亡。(模拟生命数量过多)
上图的例子还有用到底下的规则四。
规则四:若绿色格子没有活细胞,且红色格子的区域中的活细胞数量刚好为三个时,绿色格子会出现新的活细胞。(模拟生命繁殖)
再举个例子,如下图:
这张图的格子中,紫色的文字(R1、R2、R4),表示该格子符合第几条规则。
动手做
理解康威生命游戏的规则后,就可以开始动手写程序了!
创建项目目录
按照先前的章节介绍的方式,利用 wasm-pack-template 模板创建出一个新的 Cargo 程序项目,名为 wasm-game-of-life。
指令如下:
Rust 程序实作
结构化游戏世界
用 Block 枚举来表示培养皿中的每个格子,这个枚举会有两个变体,表示该格子有活细胞或是没有活细胞。程序如下:
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Block {
NoCell,
HasCell,
}
用 Universe 结构体来表示整个培养皿。程序如下:
#[derive(Debug)]
pub struct Universe {
width: u32,
height: u32,
blocks: Vec<Block>,
}
这边的 blocks 字段所保存的 Vec 数组大小应为 width * height,用一维空间来模拟二维空间。
功能实作
接下来要实作 Universe 结构体基本的关联函数和方法。程序如下:
impl Universe {
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn blocks(&self) -> &[Block] {
&self.blocks
}
}
impl Universe {
pub fn new(width: u32, height: u32) -> Universe {
assert!(width > 0);
assert!(height > 0);
let capacity = width as usize * height as usize;
let blocks = vec![Block::NoCell; capacity];
Universe {
width,
height,
blocks,
}
}
pub fn default_cells(&mut self) {
for (i, block) in self.blocks.iter_mut().enumerate() {
if i % 2 == 0 || i % 7 == 0 {
*block = Block::HasCell;
} else {
*block = Block::NoCell;
}
}
}
}
impl Universe {
pub fn get_index(&self, row: u32, column: u32) -> usize {
(row * self.width + column) as usize
}
}
impl Universe {
pub fn has_cell(&self, index: usize) -> bool {
matches!(self.blocks[index], Block::HasCell)
}
}
impl Universe {
pub fn tick(&mut self) {
let mut next_blocks = self.blocks.clone();
let width_dec = self.width - 1;
let height_dec = self.height - 1;
for row in 0..self.height {
for column in 0..self.width {
let index = self.get_index(row, column);
let has_cell = self.has_cell(index);
let live_neighbor_cells_count = {
let mut counter = 0;
let left = if column > 0 { column - 1 } else { column };
let right = if column < width_dec { column + 1 } else { column };
let top = if row > 0 { row - 1 } else { row };
let bottom = if row < height_dec { row + 1 } else { row };
for r in top..=bottom {
for c in left..=right {
if row == r && column == c {
continue;
}
let index = self.get_index(r, c);
if self.has_cell(index) {
counter += 1;
}
}
}
counter
};
if has_cell {
if !(2..=3).contains(&live_neighbor_cells_count) {
// R1, R3
next_blocks[index] = Block::NoCell;
}
// R2 can be ignored
} else if live_neighbor_cells_count == 3 {
// R4
next_blocks[index] = Block::HasCell;
}
}
}
self.blocks = next_blocks;
}
}
加入 #[wasm_bindgen] 属性
接下来就是把我们想要暴露给 JavaScript 程序使用的结构体、枚举、关联函数和方法都加上 #[wasm_bindgen] 属性。如下:
#[wasm_bindgen]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Block {
NoCell,
HasCell,
}
#[wasm_bindgen]
#[derive(Debug)]
pub struct Universe {
width: u32,
height: u32,
blocks: Vec<Block>,
}
#[wasm_bindgen]
impl Universe {
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn blocks(&self) -> &[Block] {
&self.blocks
}
}
#[wasm_bindgen]
impl Universe {
#[wasm_bindgen(constructor)]
pub fn new(width: u32, height: u32) -> Universe {
assert!(width > 0);
assert!(height > 0);
let capacity = width as usize * height as usize;
let blocks = vec![Block::NoCell; capacity];
Universe {
width,
height,
blocks,
}
}
pub fn default_cells(&mut self) {
for (i, block) in self.blocks.iter_mut().enumerate() {
if i % 2 == 0 || i % 7 == 0 {
*block = Block::HasCell;
} else {
*block = Block::NoCell;
}
}
}
}
#[wasm_bindgen]
impl Universe {
pub fn get_index(&self, row: u32, column: u32) -> usize {
(row * self.width + column) as usize
}
}
#[wasm_bindgen]
impl Universe {
pub fn has_cell(&self, index: usize) -> bool {
matches!(self.blocks[index], Block::HasCell)
}
}
#[wasm_bindgen]
impl Universe {
pub fn tick(&mut self) {
let mut next_blocks = self.blocks.clone();
let width_dec = self.width - 1;
let height_dec = self.height - 1;
for row in 0..self.height {
for column in 0..self.width {
let index = self.get_index(row, column);
let has_cell = self.has_cell(index);
let live_neighbor_cells_count = {
let mut counter = 0;
let left = if column > 0 { column - 1 } else { column };
let right = if column < width_dec { column + 1 } else { column };
let top = if row > 0 { row - 1 } else { row };
let bottom = if row < height_dec { row + 1 } else { row };
for r in top..=bottom {
for c in left..=right {
if row == r && column == c {
continue;
}
let index = self.get_index(r, c);
if self.has_cell(index) {
counter += 1;
}
}
}
counter
};
if has_cell {
if !(2..=3).contains(&live_neighbor_cells_count) {
// R1, R3
next_blocks[index] = Block::NoCell;
}
// R2 can be ignored
} else if live_neighbor_cells_count == 3 {
// R4
next_blocks[index] = Block::HasCell;
}
}
}
self.blocks = next_blocks;
}
}
不过当我们使用 cargo check 指令尝试编译程序项目时,却会发现 blocks 方法编译失败了。这是因为 Rust 的参考并不能直接被回传给 JavaScript 程序,我们必须要把 &[Block] 参考改成 *const Block 指针才行。如下:
pub fn blocks(&self) -> *const Block {
self.blocks.as_ptr()
}
修改之后,程序项目就能成功编译了!
建置项目
写完 Rust 程序后,就可以运行以下指令将它编译成 .wasm 文件,以及产生出相对应的胶水代码!
把 WebAssembly 套用在 HTML 网页
依照第一章介绍的方式,我们可以在 Cargo 程序项目目录中,添加一个 www 目录,并完成基本的 TypeScript+Webpack 程序项目。然后再继续进行下面的修改。
在 www 目录运行以下指令加入其他必要的套件:
import { Block, Universe } from "../../pkg/wasm_game_of_life.js";
// @ts-expect-error it can be load in Webpack
import { memory } from "../../pkg/wasm_game_of_life_bg.wasm";
const WIDTH = 32;
const HEIGHT = 32;
const BORDER_COLOR = "#888888";
const BLOCK_COLOR = "#CCCCCC";
const CELL_COLOR = "#000000";
export const init = () => {
const getWidth = () => {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth,
);
};
const getHeight = () => {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight,
);
};
const canvas = document.getElementById("game-of-life-canvas") as HTMLCanvasElement;
let size: number;
const screenWidth = getWidth();
const screenHeight = getHeight();
if (screenWidth < screenHeight) {
size = screenWidth / WIDTH;
} else {
size = screenHeight / HEIGHT;
}
const borderSize = size * 0.05;
const marginSize = size * 0.1;
const blockSize = size - (borderSize * 2) - (marginSize * 2);
const universe = new Universe(WIDTH, HEIGHT);
universe.default_cells();
canvas.height = size * HEIGHT;
canvas.width = size * WIDTH;
const ctx = canvas.getContext("2d");
if (ctx === null) {
return;
}
const drawCells = () => {
const blocksPtr = universe.blocks();
const blocks = new Uint8Array((memory as WebAssembly.Memory).buffer, blocksPtr, WIDTH * HEIGHT) as unknown as Block[];
ctx.beginPath();
ctx.strokeStyle = BORDER_COLOR;
ctx.lineWidth = borderSize;
for (let row = 0;row < HEIGHT;row++) {
for (let column = 0;column < WIDTH;column++) {
const index = universe.get_index(row, column);
ctx.fillStyle = blocks[index] === Block.NoCell ? BLOCK_COLOR : CELL_COLOR;
const x = (column * size) + borderSize + marginSize;
const y = (row * size) + borderSize + marginSize;
ctx.fillRect(x, y, blockSize, blockSize);
ctx.strokeRect(x, y, blockSize, blockSize);
}
}
};
const renderLoop = () => {
universe.tick();
drawCells();
requestAnimationFrame(renderLoop);
};
drawCells();
requestAnimationFrame(renderLoop);
};
注意这边我们除了引用胶水代码外,还直接引用了 .wasm 档(wasm_game_of_life_bg),这是为了要能够访问它暴露(export)的 memory 常数,也就是 WebAssembly 所使用到的内存对象(WebAssembly.Memory)实体。我们必须要有这个内存对象实体才能够在 JavaScript 中利用指针访问指定地址的数据,而访问的方式是透过 Uint8Array 对象。但为什么会是用 Uint8Array 对象呢?我们的 Block 应该要是个枚举,而不是 u8 不是吗?要怎么才能够知道一个枚举值该用多少个字节来表示?为什么可以确定这边的 Block 枚举值是一个字节呢?
事实上,Rust 编程语言的枚举,每个变体都可以对应一个 isize 整数值,如果这些 isize 整数值都在 i8 或 u8 范围内,那么这个枚举就会以 8 比特来保存,同样地,若这些 isize 整数值都在 i16 或 u16 范围内,那么这个枚举就会以 16 比特来保存,依此类推。
还有一个要注意的地方是,我们在绘制 Canvas 的前后均调用了 requestAnimationFrame 函数,这个是网页浏览器提供的 JS 函数,可以根据屏幕刷新频率来触发某个函数,就算重复调用也不必担心有堆栈溢出的问题,用于网页画面的绘制。
最后要注意的是,JavaScript 其实并不能直接以 import 关键字引入 .wasm 档,必须透过 WebAssembly 对象才行,但在 Webpack 中因为有内置的 WASM 加载器的帮助,才使得直接 import 变成可能。在之后的章节会以其它的方式来取代现在这个直接以 import 关键字引入 .wasm 档的作法,让程序写起来更漂亮一些。
body {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
}
canvas {
max-width: 100%;
max-height: 100%;
}
import "./index.scss";
import { init } from "./lib.js";
init();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Conway's Game of Life</title>
<link href="./css/bundle.min.css" rel="stylesheet">
</head>
<body>
<canvas id="game-of-life-canvas"></canvas>
<script src="./js/bundle.min.js"></script>
</body>
</html>
import autoprefixer from "autoprefixer";
import cssnano from "cssnano";
import HtmlWebpackPlugin from "html-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import TerserPlugin from "terser-webpack-plugin";
import { Configuration } from "webpack";
const config: Configuration = {
entry: "./src/index.ts",
output: {
clean: true,
filename: "./js/bundle.min.js",
webassemblyModuleFilename: "./wasm/game-of-life.wasm",
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.html",
filename: "./index.html",
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyCSS: true,
minifyJS: true,
sortAttributes: true,
useShortDoctype: true,
},
inject: false,
}),
new MiniCssExtractPlugin({ filename: "./css/bundle.min.css" }),
],
module: {
rules: [
{
test: /\.ts$/i,
use: [
{
loader: "babel-loader",
options: { presets: ["@babel/preset-env", "@babel/preset-typescript"] },
},
],
},
{
test: /\.js$/i,
use: [
{
loader: "babel-loader",
options: { presets: ["@babel/preset-env"] },
},
],
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
autoprefixer,
cssnano({ preset: ["default", { discardComments: { removeAll: true } }] }),
],
},
},
},
"sass-loader",
],
},
],
},
resolve: { extensionAlias: { ".js": [".ts", ".js"] } },
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: { format: { comments: false } },
}),
],
},
experiments: { asyncWebAssembly: true },
};
export default config;
然后就可以在 www 目录中运行 npm run build:webpack 指令来打包项目。接着再使用 VSCode 的 Live Server 打开 Webpack 输出的 index.html 来浏览结果,结果如下图:
总结
我们在这个章节中,成功用 Rust 程序实作了康威生命游戏,并且也将其编译成 WebAssembly 程序,在 HTML 网页 Canvas 上正确显示出游戏画面。不过现在这个游戏的功能实在是太少了,完全没有办法跟玩家交互嘛!先别着急,愈强大的程序开发起来愈复杂,因此我们在下一个章节必须要先学习 WebAssembly 程序的测试和调试方式才行。









