006 Web Assembly之调试方法

0 介绍

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

上一节我们对之前写的代码进行了测试,这一节我们来介绍调试方法。

在我们写更多的代码之前,我们希望有一些调试工具来让我们调试代码中的bug。具体的一些工具我们后续介绍。下面我们主要介绍三种调试方法。

1 打开panic 日志

我们的wasm-pack-template附带了一个可选的,默认情况下启用的依赖,该依赖属于console_error_panic_hook包,在wasm-game-of-life/src/utils中配置。我们需要做的就是在初始化函数或者公共代码路径中安装钩子。我们可以在Universe::new构造器中调用,如下:

pub fn new() -> Universe {
    utils::set_panic_hook();

    // ...
}

2 添加log到我们的游戏中

在Cargo.toml中添加如下代码:

[dependencies.web-sys]
version = "0.3"
features = [
  "console",
]

在src/lib.rs中添加:

extern crate web_sys;

// A macro to provide `println!(..)`-style syntax for `console.log` logging.
macro_rules! log {
    ( $( $t:tt )* ) => {
        web_sys::console::log_1(&format!( $( $t )* ).into());
    }
}

修改src/lib.rs中的tick函数如下:

//计算下一个滴答的状态
    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);

                //以下为添加的内容
                log!(
                    "cell[{}, {}] is initially {:?} and has {} live neighbors",
                    row,
                    col,
                    cell,
                    live_neighbors
                );


                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,
                };

                //以下为添加的内容
                log!("    it becomes {:?}", next_cell);

                next[idx] = next_cell;
            }
        }
        self.cells = next;
    }

3 使用debugger暂停每个tick

我们在js代码中添加一个js的debugger,如下:

//www/index.js中

function renderLoop() {
    debugger;

    ...
}

3.1 编译

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

wasm-pack build

在www目录下运行:

npm run start

按F12打开网页调试工具,可以进行调试。

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

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