007 Web Assembly康威遊戲新增互動

linghuyichong發表於2021-08-23

影片地址:www.bilibili.com/video/BV1eg411g7c...
相關原始碼:github.com/anonymousGiga/Rust-and-...

本節,我們將給康威遊戲新增互動。

我們首先在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();
    }
});

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

在wasm-game-of-life目錄下執行:

wasm-pack build

在www目錄下執行:

npm run start

在瀏覽器中輸入:127.0.0.1:8080

點選按鈕可以暫停和啟動,點選網格可以改變細胞狀態。

本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章