0016-wasm-康威生命游戏
游戏 生命 Wasm
2023-09-27 14:23:45 时间
环境
- Time 2022-05-16
- Rust 1.60.0
- Node 12.22.5
- wasm-pack 0.10.2
前言
说明
参考:https://rustwasm.github.io/docs/book/game-of-life/implementing.html
目标
在上一节的基础上进行,前面已经实现了康威游戏,只不过是直接将字符串渲染到页面上的,接下来使用 canvas
渲染。
index.html
将之前的 pre
标签修改为 canvas
标签。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>康威生命游戏</title>
<style>
body {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<canvas id="game"></canvas>
<script src="./bootstrap.js"></script>
</body>
</html>
暴露细胞列表地址
#[wasm_bindgen]
impl Universe {
...
pub fn cells(&self) -> *const Cell {
self.cells.as_ptr()
}
...
}
index.js
之后就是 index.js 之中的内容。
导入
import { Universe, Cell } from "game";
import { memory } from "game/game_bg";
常量定义
const CELL_SIZE = 10;
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";
const WIDTH = 64;
const HEIGHT = 64;
获取画布
const canvas = document.getElementById("game");
canvas.height = (CELL_SIZE + 1) * HEIGHT + 1;
canvas.width = (CELL_SIZE + 1) * WIDTH + 1;
const ctx = canvas.getContext('2d');
循环渲染
const universe = Universe.new(WIDTH, HEIGHT);
const renderLoop = () => {
universe.tick();
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
};
画栅格
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();
};
画细胞
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();
};
入口
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
启动前端
npm run start
效果展示
总结
使用 canvas
来渲染康威生命游戏的效果。
附录
相关文章
- FPS 游戏自瞄原理
- 游戏工程管理
- 游戏开发:Unity中Lua造成的堆内存泄露问题
- 【BZOJ3875】[Ahoi2014&Jsoi2014]骑士游戏 SPFA优化DP
- 有奖征集活动系列——《iOS游戏编程之旅》已结束
- 工作十年对游戏看法的转变历程
- C#开发Unity游戏教程之使用脚本变量
- 《C++游戏编程入门(第4版)》——2.7 使用do循环
- 《Unity 5.x游戏开发实战》一2.2 Unity中的C#脚本
- 《Android游戏开发详解》——第3章,第3.1节构造方法
- 《Android游戏开发详解》一2.3 编写第一个程序
- 游戏的发展~游戏本质与思考摘录
- 如何使用Python环境下的2D经典游戏仿真器(openai推出的)retro库运行游戏"刺猬索尼克" (SonicTheHedgehog-Genesis)
- 华为游戏登录验签失败can not find publicKey of the cp
- MATLAB | 比生命游戏更自由的生命游戏
- 做一个略调皮的个人主页--游戏篇
- (cocos2d-js游戏)測试你的反应速度----------基本逻辑(上)