// Initialisations
// https://stackoverflow.com/a/27747377/12660887
-function dec2hex (dec) { return dec.toString(16).padStart(2, "0") }
function generateId (len) {
- var arr = new Uint8Array((len || 40) / 2)
- window.crypto.getRandomValues(arr)
- return Array.from(arr, dec2hex).join('')
+ const dec2hex = (dec) => dec.toString(16).padStart(2, "0");
+ let arr = new Uint8Array(len / 2); //len/2 because 2 chars per hex value
+ window.crypto.getRandomValues(arr); //fill with random integers
+ return Array.from(arr, dec2hex).join('');
}
// Populate variants dropdown list
if (active) formField.classList.add("form-field--is-active");
else {
formField.classList.remove("form-field--is-active");
- inputName.value === "" ?
- formField.classList.remove("form-field--is-filled") :
- formField.classList.add("form-field--is-filled");
+ inputName.value == ''
+ ? formField.classList.remove("form-field--is-filled")
+ : formField.classList.add("form-field--is-filled");
}
};
+setActive(true);
inputName.onblur = () => setActive(false);
inputName.onfocus = () => setActive(true);
-inputName.focus();
/////////
// Utils
function setName() {
+ // 'onChange' event on name input text field [HTML]
localStorage.setItem("name", $.getElementById("myName").value);
}
// Turn a "tab" on, and "close" all others
function toggleVisible(element) {
- for (elt of document.querySelectorAll('main > div')) {
+ for (elt of document.querySelectorAll("main > div")) {
if (elt.id != element) elt.style.display = "none";
else elt.style.display = "block";
}
- if (element.id == "newGame") {
- // Workaround "superposed texts" effect
- inputName.focus();
- inputName.blur();
+ if (element == "boardContainer") {
+ // Avoid smartphone scrolling effects (TODO?)
+ document.querySelector("html").style.overflow = "hidden";
+ document.body.style.overflow = "hidden";
+ }
+ else {
+ document.querySelector("html").style.overflow = "visible";
+ document.body.style.overflow = "visible";
+ // Workaround "superposed texts" effect:
+ if (element == "newGame") setActive(false);
}
}
let seek_vname;
function seekGame() {
seek_vname = $.getElementById("selectVariant").value;
- send("seekgame", {vname: seek_vname, name: localStorage.getItem("name")});
- toggleVisible("pendingSeek");
+ if (send("seekgame",
+ {vname: seek_vname, name: localStorage.getItem("name")})
+ ) {
+ toggleVisible("pendingSeek");
+ }
}
function cancelSeek() {
- send("cancelseek", {vname: seek_vname});
- toggleVisible("newGame");
+ if (send("cancelseek", {vname: seek_vname})) toggleVisible("newGame");
}
function sendRematch() {
- send("rematch", { gid: gid });
- toggleVisible("pendingRematch");
+ if (send("rematch", {gid: gid})) toggleVisible("pendingRematch");
}
function cancelRematch() {
- send("norematch", { gid: gid });
- toggleVisible("newGame");
+ if (send("norematch", {gid: gid})) toggleVisible("newGame");
}
// Play with a friend (or not ^^)
$.getElementById("selectColor").selectedIndex = 0;
toggleVisible("newGameForm");
import(`/variants/${vname}/class.js`).then(module => {
- const Rules = module.default;
- prepareOptions(Rules);
+ window.V = module.default;
+ prepareOptions();
});
}
}
-function backToNormalSeek() { toggleVisible("newGame"); }
+function backToNormalSeek() {
+ toggleVisible("newGame");
+}
-function toggleStyle(e, word) {
+function toggleStyle(event, obj) {
+ const word = obj.innerHTML;
options[word] = !options[word];
- e.target.classList.toggle("highlight-word");
+ event.target.classList.toggle("highlight-word");
}
let options;
-function prepareOptions(Rules) {
+function prepareOptions() {
options = {};
- let optHtml = Rules.Options.select.map(select => { return `
+ let optHtml = V.Options.select.map(select => { return `
<div class="option-select">
<label for="var_${select.variable}">${select.label}</label>
<div class="select">
</div>
</div>`;
}).join("");
- optHtml += Rules.Options.check.map(check => {
+ optHtml += V.Options.check.map(check => {
return `
<div class="option-check">
<label class="checkbox">
</label>
</div>`;
}).join("");
- if (Rules.Options.styles.length >= 1) {
+ if (V.Options.styles.length >= 1) {
optHtml += '<div class="words">';
let i = 0;
- const stylesLength = Rules.Options.styles.length;
+ const stylesLength = V.Options.styles.length;
while (i < stylesLength) {
optHtml += '<div class="row">';
for (let j=i; j<i+4; j++) {
if (j == stylesLength) break;
- const style = Rules.Options.styles[j];
- optHtml +=
- `<span onClick="toggleStyle(event, '${style}')">${style}</span>`;
+ const style = V.Options.styles[j];
+ optHtml += `<span onClick="toggleStyle(event, this)">${style}</span>`;
}
optHtml += "</div>";
i += 4;
for (const select of $.querySelectorAll("#gameOptions select")) {
let value = select.value;
if (select.attributes["data-numeric"]) value = parseInt(value, 10);
- options[ select.id.split("_")[1] ] = value;
+ if (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 check of $.querySelectorAll("#gameOptions input"))
- options[ check.id.split("_")[1] ] = check.checked;
send("creategame", {
vname: vname,
- player: { sid: sid, name: localStorage.getItem("name"), color: color },
+ player: {sid: sid, name: localStorage.getItem("name"), color: color},
options: options
});
}
-const fillGameInfos = (gameInfos, oppIndex) => {
+function fillGameInfos(gameInfos, oppIndex) {
fetch(`/variants/${gameInfos.vname}/rules.html`)
.then(res => res.text())
.then(txt => {
htmlContent +=
'<span class="option">' +
(opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
- '</span>';
+ "</span>";
}
htmlContent += "</div>";
i += 4;
</div>`;
$.getElementById("gameInfos").innerHTML = htmlContent;
});
-};
+}
////////////////
// Communication
-let socket, gid, attempt = 0;
+let socket, gid, recoAttempt = 0;
const autoReconnectDelay = () => {
- return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(attempt, 6)];
+ return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(recoAttempt, 6)];
};
-function copyClipboard(msg) { navigator.clipboard.writeText(msg); }
+function send(code, data, opts) {
+ opts = opts || {};
+ const trySend = () => {
+ if (socket.readyState == 1) {
+ socket.send(JSON.stringify(Object.assign({code: code}, data)));
+ if (opts.success) opts.success();
+ return true;
+ }
+ return false;
+ };
+ const firstTry = trySend();
+ if (!firstTry) {
+ if (opts.retry) {
+ // Retry for a few seconds (sending move)
+ let sendAttempt = 1;
+ const retryLoop = setInterval(
+ () => {
+ if (trySend() || ++sendAttempt >= 3) clearInterval(retryLoop);
+ if (sendAttempt >= 3 && opts.error) opts.error();
+ },
+ 1000
+ );
+ }
+ else if (opt.error) opts.error();
+ }
+ return firstTry;
+}
+
+function copyClipboard(msg) {
+ navigator.clipboard.writeText(msg);
+}
function getWhatsApp(msg) {
return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
}
const tryResumeGame = () => {
- attempt = 0;
+ recoAttempt = 0;
// If a game is found, resume it:
if (localStorage.getItem("gid")) {
gid = localStorage.getItem("gid");
- send("getgame", { gid: gid });
+ send("getgame",
+ {gid: gid},
+ {
+ retry: true,
+ error: () => alert("Cannot load game: no connection")
+ });
}
else {
// If URL indicates "play with a friend", start game:
if (hashIdx >= 0) {
const urlParts = $.URL.split('#');
gid = urlParts[1];
- send("joingame", { gid: gid, name: localStorage.getItem("name") });
localStorage.setItem("gid", gid);
- history.replaceState(null, '', urlParts[0]);
+ history.replaceState(null, '', urlParts[0]); //hide game ID
+ send("joingame",
+ {gid: gid, name: localStorage.getItem("name")},
+ {
+ retry: true,
+ error: () => alert("Cannot load game: no connection")
+ });
}
}
};
switch (obj.code) {
// Start new game:
case "gamestart": {
- if (!$.hasFocus()) notifyMe("game");
+ if (document.hidden) notifyMe("game");
gid = obj.gid;
initializeGame(obj);
break;
<p>
<a href="${getWhatsApp(link)}">WhatsApp</a>
/
- <span onClick='copyClipboard("${link}")'>ToClipboard</span>
+ <span onClick="copyClipboard('${link}')">ToClipboard</span>
</p>
<p>${link}</p>
`;
break;
// Receive opponent's move:
case "newmove":
- if (!$.hasFocus()) notifyMe("move");
+ // Basic check: was it really opponent's turn?
+ if (vr.turn == playerColor) break;
+ if (document.hidden) notifyMe("move");
vr.playReceivedMove(obj.moves, () => {
if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
localStorage.removeItem("gid");
};
const handleError = (err) => {
- if (err.code === 'ECONNREFUSED') {
+ if (err.code === "ECONNREFUSED") {
removeAllListeners();
alert("Server refused connection. Please reload page later");
}
}, autoReconnectDelay());
};
-const removeAllListeners = () => {
+function removeAllListeners() {
socket.removeEventListener("open", tryResumeGame);
socket.removeEventListener("message", messageCenter);
socket.removeEventListener("error", handleError);
socket.removeEventListener("close", handleClose);
-};
+}
-const connectToWSS = () => {
+function connectToWSS() {
socket =
new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
socket.addEventListener("open", tryResumeGame);
socket.addEventListener("message", messageCenter);
socket.addEventListener("error", handleError);
socket.addEventListener("close", handleClose);
- attempt++;
-};
+ recoAttempt++;
+}
connectToWSS();
-const send = (code, data) => {
- socket.send(JSON.stringify(Object.assign({code: code}, data)));
-};
-
///////////
// Playing
new Notification("New " + code, { vibrate: [200, 100, 200] });
new Audio("/assets/new_" + code + ".mp3").play();
}
- if (Notification.permission === 'granted') doNotify();
- else if (Notification.permission !== 'denied') {
- Notification.requestPermission().then((permission) => {
- if (permission === 'granted') doNotify();
+ if (Notification.permission === "granted") doNotify();
+ else if (Notification.permission !== "denied") {
+ Notification.requestPermission().then(permission => {
+ if (permission === "granted") doNotify();
});
}
}
-let curMoves = [];
-const afterPlay = (move) => { //pack into one moves array, then send
+let curMoves = [],
+ lastFen;
+const afterPlay = (move) => {
+ const callbackAfterSend = () => {
+ 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({
appear: move.appear,
vanish: move.vanish,
});
if (vr.turn != playerColor) {
toggleTurnIndicator(false);
- send("newmove", { gid: gid, moves: curMoves, fen: vr.getFen() });
- curMoves = [];
- const result = vr.getCurrentScore(move);
- if (result != "*") {
- setTimeout( () => {
- toggleVisible("gameStopped");
- send("gameover", { gid: gid });
- }, 2000);
- }
- }
-};
-
-// Avoid loading twice the same stylesheet:
-const conditionalLoadCSS = (vname) => {
- const allIds = [].slice.call($.styleSheets).map(s => s.id);
- const newId = vname + "_css";
- if (!allIds.includes(newId)) {
- $.getElementsByTagName("head")[0].insertAdjacentHTML(
- "beforeend",
- `<link id="${newId}" rel="stylesheet"
- href="/variants/${vname}/style.css"/>`);
+ send("newmove",
+ {gid: gid, moves: curMoves, fen: vr.getFen()},
+ {
+ retry: true,
+ success: callbackAfterSend,
+ error: () => alert("Move not sent: reload page")
+ });
}
};
function initializeGame(obj) {
const options = obj.options || {};
import(`/variants/${obj.vname}/class.js`).then(module => {
- const Rules = module.default;
- conditionalLoadCSS(obj.vname);
+ window.V = module.default;
+ // 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)) {
+ $.getElementsByTagName("head")[0].insertAdjacentHTML(
+ "beforeend",
+ `<link id="${newId}" rel="stylesheet"
+ href="/variants/${obj.vname}/style.css"/>`);
+ }
playerColor = (sid == obj.players[0].sid ? "w" : "b");
// Init + remove potential extra DOM elements from a previous game:
document.getElementById("boardContainer").innerHTML = `
<div id="upLeftInfos"
onClick="toggleGameInfos()">
- <img src="/assets/icon_infos.svg"/>
+ <svg version="1.1"
+ viewBox="0.5 0.5 100 100">
+ <g>
+ <path d="M50.5,0.5c-27.614,0-50,22.386-50,50c0,27.614,22.386,50,50,50s50-22.386,50-50C100.5,22.886,78.114,0.5,50.5,0.5z M60.5,85.5h-20v-40h20V85.5z M50.5,35.5c-5.523,0-10-4.477-10-10s4.477-10,10-10c5.522,0,10,4.477,10,10S56.022,35.5,50.5,35.5z"/>
+ </g>
+ </svg>
</div>
<div id="upRightStop"
onClick="confirmStopGame()">
- <img src="/assets/icon_close.svg"/>
+ <svg version="1.1"
+ viewBox="0 0 533.333 533.333">
+ <g>
+ <path d="M528.468,428.468c-0.002-0.002-0.004-0.004-0.006-0.005L366.667,266.666l161.795-161.797 c0.002-0.002,0.004-0.003,0.006-0.005c1.741-1.742,3.001-3.778,3.809-5.946c2.211-5.925,0.95-12.855-3.814-17.62l-76.431-76.43 c-4.765-4.763-11.694-6.024-17.619-3.812c-2.167,0.807-4.203,2.066-5.946,3.807c0,0.002-0.002,0.003-0.005,0.005L266.667,166.666 L104.87,4.869c-0.002-0.002-0.003-0.003-0.005-0.005c-1.743-1.74-3.778-3-5.945-3.807C92.993-1.156,86.065,0.105,81.3,4.869 L4.869,81.3c-4.764,4.765-6.024,11.694-3.813,17.619c0.808,2.167,2.067,4.205,3.808,5.946c0.002,0.001,0.003,0.003,0.005,0.005 l161.797,161.796L4.869,428.464c-0.001,0.002-0.003,0.003-0.004,0.005c-1.741,1.742-3,3.778-3.809,5.945 c-2.212,5.924-0.951,12.854,3.813,17.619L81.3,528.464c4.766,4.765,11.694,6.025,17.62,3.813c2.167-0.809,4.203-2.068,5.946-3.809 c0.001-0.002,0.003-0.003,0.005-0.005l161.796-161.797l161.795,161.797c0.003,0.001,0.005,0.003,0.007,0.004 c1.743,1.741,3.778,3.001,5.944,3.81c5.927,2.212,12.856,0.951,17.619-3.813l76.43-76.432c4.766-4.765,6.026-11.696,3.815-17.62 C531.469,432.246,530.209,430.21,528.468,428.468z"/>
+ </g>
+ </svg>
</div>
<div class="resizeable" id="chessboard"></div>`;
- vr = new Rules({
+ vr = new V({
seed: obj.seed, //may be null if FEN already exists (running game)
fen: obj.fen,
element: "chessboard",
options: options
});
if (!obj.fen) {
- // Game creation
- if (playerColor == "w") send("setfen", {gid: obj.gid, fen: vr.getFen()});
+ // Game creation: both players set FEN, in case of one is offline
+ send("setfen", {gid: obj.gid, fen: vr.getFen()});
localStorage.setItem("gid", obj.gid);
}
const select = $.getElementById("selectVariant");
}
function confirmStopGame() {
- if (confirm("Stop game?")) {
- send("gameover", { gid: gid, relay: true });
+ if (confirm("Stop game?") && send("gameover", {gid: gid, relay: true})) {
localStorage.removeItem("gid");
toggleVisible("gameStopped");
}
function toggleGameInfos() {
if ($.getElementById("gameInfos").style.display == "none")
toggleVisible("gameInfos");
- else {
- toggleVisible("boardContainer");
- // Quickfix for the "vanished piece" bug (move played while on game infos)
- vr.setupPieces(); //TODO: understand better
- }
+ else toggleVisible("boardContainer");
}
$.body.addEventListener("keydown", (e) => {