Skip to content

Commit

Permalink
web: Use web workers to run chess bot
Browse files Browse the repository at this point in the history
Running it on the main thread would freeze the browser.
  • Loading branch information
francorbacho committed Apr 29, 2024
1 parent 08f43ce commit 23c2b15
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 8 additions & 1 deletion web/js/chessboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ class Chessboard {
white: "human",
black: "computer",
};

this.worker = new Worker("js/worker.js", { type: "module" });

this.worker.onmessage = (ev) => { this.feedMove(ev.data); };
this.worker.onerror = (ev) => {
console.error("WORKER FAILED", ev);
};
}

constructHTML() {
Expand Down Expand Up @@ -263,7 +270,7 @@ class Chessboard {
return;
}

wasm.flimsybirdRun().then(move => this.feedMove(move)).catch(() => { });
this.worker.postMessage({ inputData: wasm.boardToFen() });
}
}

Expand Down
11 changes: 11 additions & 0 deletions web/js/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import init, * as wasm from '../pkg/chess_wasm.js';

self.onmessage = async (event) => {
await init();

const { inputData } = event.data;
wasm.loadBoardFromFen(inputData);

const result = await wasm.flimsybirdRun().catch(() => { /* TODO: Handle this? */ });
self.postMessage(result);
};

0 comments on commit 23c2b15

Please sign in to comment.