Attempt to clarify installation instructions a little
[vchess.git] / client / src / playCompMove.js
index f58f998..d83148f 100644 (file)
@@ -1,27 +1,27 @@
-// TODO: https://github.com/webpack-contrib/worker-loader
-// https://stackoverflow.com/questions/48713072/how-to-get-js-function-into-webworker-via-importscripts
-// For asynchronous computer move search
-onmessage = function(e)
-{
-       switch (e.data[0])
-       {
-               case "scripts":
-                       self.importScripts(
-                               '@/base_rules.js',
-                               '@/utils/array.js',
-                               '@/variants/' + e.data[1] + '.js');
-                       self.V = eval("VariantRules");
-                       break;
-               case "init":
-                       const fen = e.data[1];
-                       self.vr = new VariantRules(fen);
-                       break;
-               case "newmove":
-                       self.vr.play(e.data[1]);
-                       break;
-               case "askmove":
-                       const compMove = self.vr.getComputerMove();
-                       postMessage(compMove);
-                       break;
-       }
-}
+// Logic to play a computer move in a web worker
+onmessage = async function(e) {
+  switch (e.data[0]) {
+    case "scripts": {
+      await import("@/variants/" + e.data[1] + ".js")
+      .then((vModule) => { self.V = vModule[e.data[1] + "Rules"]; });
+      break;
+    }
+    case "init": {
+      const fen = e.data[1];
+      self.vr = new self.V(fen);
+      break;
+    }
+    case "newmove":
+      let move = e.data[1];
+      // Caution: could be a multi-move
+      if (!Array.isArray(move))
+        move = [move];
+      move.forEach(m => self.vr.play(m));
+      break;
+    case "askmove": {
+      const compMove = self.vr.getComputerMove();
+      postMessage(compMove);
+      break;
+    }
+  }
+};