New variant idea
[xogo.git] / app.js
diff --git a/app.js b/app.js
index 6036d49..c5d5c7f 100644 (file)
--- a/app.js
+++ b/app.js
@@ -130,11 +130,13 @@ function toggleStyle(event, obj) {
 let options;
 function prepareOptions() {
   options = {};
-  let optHtml = V.Options.select.map(select => { return `
+  let optHtml = "";
+  if (V.Options.select) {
+    optHtml += V.Options.select.map(select => { return `
       <div class="option-select">
         <label for="var_${select.variable}">${select.label}</label>
         <div class="select">
-          <select id="var_${select.variable}" data-numeric="1">` +
+          <select id="var_${select.variable}">` +
           select.options.map(option => { return `
             <option
               value="${option.value}"
@@ -147,19 +149,25 @@ function prepareOptions() {
           <span class="focus"></span>
         </div>
       </div>`;
-  }).join("");
-  optHtml += V.Options.check.map(check => {
-    return `
-      <div class="option-check">
-        <label class="checkbox">
-          <input id="var_${check.variable}"
-                 type="checkbox"${check.defaut ? " checked" : ""}/>
+    }).join("");
+  }
+  if (V.Options.input) {
+    optHtml += V.Options.input.map(input => { return `
+      <div class="option-input">
+        <label class="input">
+          <input id="var_${input.variable}"
+                 type="${input.type}"
+                 ${input.type == "checkbox" && input.defaut
+                   ? "checked"
+                   : 'value="' + input.defaut + '"'}
+          />
           <span class="spacer"></span>
-          <span>${check.label}</span>
+          <span>${input.label}</span>
         </label>
       </div>`;
-  }).join("");
-  if (V.Options.styles.length >= 1) {
+    }).join("");
+  }
+  if (V.Options.styles) {
     optHtml += '<div class="words">';
     let i = 0;
     const stylesLength = V.Options.styles.length;
@@ -183,15 +191,17 @@ function getGameLink() {
   const vname = $.getElementById("selectVariant").value;
   const color = $.getElementById("selectColor").value;
   for (const select of $.querySelectorAll("#gameOptions select")) {
-    let value = select.value;
-    if (select.attributes["data-numeric"])
-      value = parseInt(value, 10);
-    if (value)
-      options[ select.id.split("_")[1] ] = value;
+    let value = parseInt(select.value, 10);
+    if (isNaN(value)) //not an integer
+      value = select.value;
+    options[ select.id.split("_")[1] ] = value;
   }
-  for (const check of $.querySelectorAll("#gameOptions input")) {
-    if (check.checked)
-      options[ check.id.split("_")[1] ] = check.checked;
+  for (const input of $.querySelectorAll("#gameOptions input")) {
+    const variable = input.id.split("_")[1];
+    if (input.type == "number")
+      options[variable] = parseInt(input.value, 10); //TODO: real numbers?
+    else if (input.type == "checkbox")
+      options[variable] = input.checked;
   }
   send("creategame", {
     vname: vname,
@@ -221,7 +231,7 @@ function fillGameInfos(gameInfos, oppIndex) {
           if (j == options.length)
             break;
           const opt = options[j];
-          if (!opt[1])
+          if (!opt[1]) //includes 0 and false (lighter display)
             continue;
           htmlContent +=
             '<span class="option">' +
@@ -363,7 +373,7 @@ const messageCenter = (msg) => {
       if (document.hidden)
         notifyMe("move");
       vr.playReceivedMove(obj.moves, () => {
-        if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
+        if (vr.getCurrentScore(obj.moves) != "*") {
           localStorage.removeItem("gid");
           setTimeout( () => toggleVisible("gameStopped"), 2000 );
         }
@@ -380,6 +390,10 @@ const messageCenter = (msg) => {
     case "closerematch":
       toggleVisible("newGame");
       break;
+    case "filechange":
+      // TODO?: could be more subtle
+      setTimeout(() => location.reload(), 100);
+      break;
   }
 };
 
@@ -446,46 +460,54 @@ function notifyMe(code) {
 
 let curMoves = [],
     lastFen;
-const afterPlay = (move) => {
-  const callbackAfterSend = () => {
+const afterPlay = (move_s, newTurn, ops) => {
+  if (ops.send) {
+    // Pack into one moves array, then send (if turn changed)
+    if (Array.isArray(move_s))
+      // Array of simple moves (e.g. Chakart)
+      Array.prototype.push.apply(curMoves, move_s);
+    else
+      // Usual case
+      curMoves.push(move_s);
+    if (newTurn != playerColor) {
+      send("newmove",
+           {gid: gid, moves: curMoves, fen: vr.getFen()},
+           {
+             retry: true,
+             error: () => alert("Move not sent: reload page")
+           }
+      );
+    }
+  }
+  if (ops.res && newTurn != playerColor) {
+    toggleTurnIndicator(false); //now all moves are sent and animated
+    const result = vr.getCurrentScore(curMoves);
     curMoves = [];
-    const result = vr.getCurrentScore(move);
     if (result != "*") {
       setTimeout(() => {
         toggleVisible("gameStopped");
         send("gameover", {gid: gid});
       }, 2000);
     }
-  };
-  // Pack into one moves array, then send
-  curMoves.push(move);
-  if (vr.turn != playerColor) {
-    toggleTurnIndicator(false);
-    send("newmove",
-         {gid: gid, moves: curMoves, fen: vr.getFen()},
-         {
-           retry: true,
-           success: callbackAfterSend,
-           error: () => alert("Move not sent: reload page")
-         });
   }
 };
 
-let vr, playerColor;
+let vr = null, playerColor, lastVname = undefined;
 function initializeGame(obj) {
   const options = obj.options || {};
   import(`/variants/${obj.vname}/class.js`).then(module => {
     window.V = module.default;
     for (const [k, v] of Object.entries(V.Aliases))
       window[k] = v;
-    // Load CSS. Avoid loading twice the same stylesheet:
-    const allIds = [].slice.call($.styleSheets).map(s => s.id);
-    const newId = obj.vname + "_css";
-    if (!allIds.includes(newId)) {
+    if (lastVname != obj.vname) {
+      // Load CSS + unload potential previous one.
+      if (lastVname)
+        document.getElementById(lastVname + "_css").remove();
       $.getElementsByTagName("head")[0].insertAdjacentHTML(
         "beforeend",
-        `<link id="${newId}" rel="stylesheet"
+        `<link id="${obj.vname + '_css'}" rel="stylesheet"
                href="/variants/${obj.vname}/style.css"/>`);
+      lastVname = obj.vname;
     }
     playerColor = (sid == obj.players[0].sid ? "w" : "b");
     // Init + remove potential extra DOM elements from a previous game:
@@ -508,7 +530,10 @@ function initializeGame(obj) {
           </g>
         </svg>
       </div>
-      <div class="resizeable chessboard"></div>`;
+      <div class="chessboard"></div>`;
+    if (vr)
+      // Avoid interferences:
+      vr.removeListeners();
     vr = new V({
       seed: obj.seed, //may be null if FEN already exists (running game)
       fen: obj.fen,
@@ -517,8 +542,9 @@ function initializeGame(obj) {
       afterPlay: afterPlay,
       options: options
     });
-    if (!obj.fen) {
-      // Game creation: both players set FEN, in case of one is offline
+    const gameCreation = !obj.fen;
+    if (gameCreation) {
+      // Both players set FEN, in case of one is offline
       send("setfen", {gid: obj.gid, fen: vr.getFen()});
       localStorage.setItem("gid", obj.gid);
     }
@@ -530,8 +556,9 @@ function initializeGame(obj) {
         break;
       }
     }
-    fillGameInfos(obj, playerColor == "w" ? 1 : 0);
-    if (obj.randvar)
+    const playerIndex = (playerColor == "w" ? 0 : 1);
+    fillGameInfos(obj, 1 - playerIndex);
+    if (obj.players[playerIndex].randvar && gameCreation)
       toggleVisible("gameInfos");
     else
       toggleVisible("boardContainer");