007 Web Assembly康威游戏添加交互

0 介绍

视频地址:www.bilibili.com/video/BV1eg411g7c...
相关源码:github.com/anonymousGiga/Rust-and-...

本节,我们将给康威游戏添加交互。

1 暂停和恢复游戏

我们首先在wasm-game-of-life/www/index.html中添加button在标签上面添加如下:

<button id="play-pause"></button>

我们将wasm-game-of-life/www/index.js修改为如下:

//import { Universe } from "wasm-game-of-life";
import { Universe, Cell } from "wasm-game-of-life";
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";

const CELL_SIZE = 5; // px
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";

const universe = Universe.new();
const width = universe.width();
const height = universe.height();

const canvas = document.getElementById("game-of-life-canvas");
canvas.height = (CELL_SIZE + 1) * height + 1;
canvas.width = (CELL_SIZE + 1) * width + 1;

const ctx = canvas.getContext('2d');

let animationId = null;

function renderLoop() {
  //debugger;
  drawGrid();
  drawCells();
  universe.tick();
  //window.requestAnimationFrame(renderLoop);
  animationId = requestAnimationFrame(renderLoop);
}

function isPaused() {
    return animationId === null;
}

const playPauseButton = document.getElementById("play-pause");

function play() {
    playPauseButton.textContent = "⏸ ";
    renderLoop();
}

function pause() {
    playPauseButton.textContent = "▶";
    cancelAnimationFrame(animationId);
    andmationId = null;
}


function drawGrid() {
  ctx.beginPath();
  ctx.strokeStyle = GRID_COLOR;

  // Vertical lines.
  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);
  }

  // Horizontal lines.
  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();
}

function getIndex(row, column) {
  return row * width + column;
}

function 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 = getIndex(row, 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();
}

//window.requestAnimationFrame(renderLoop);

playPauseButton.addEventListener("click", function() {
    if (isPaused())    {
        play();
    } else {
        pause();
    }
});

2 切换细胞状态

在wasm-game-of-life/src/lib.rs中添加如下代码:

impl Cell {
    fn toggle(&mut self) {
        *self = match *self {
            Cell::Dead => Cell::Alive,
            Cell::Alive => Cell::Dead,
        };
    }
}

。。。

#[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();
    }
}

然后,我们在index.js中添加如下代码:

canvas.addEventListener("click", function()  {
  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();
});

3 编译测试

在wasm-game-of-life目录下运行:

wasm-pack build

在www目录下运行:

npm run start

在浏览器中输入:127.0.0.1:8080

点击按钮可以暂停和启动,点击网格可以改变细胞状态。

本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
119
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商