1 let $ = document
; //shortcut
6 // https://stackoverflow.com/a/27747377/12660887
7 function dec2hex (dec
) { return dec
.toString(16).padStart(2, "0") }
8 function generateId (len
) {
9 var arr
= new Uint8Array((len
|| 40) / 2)
10 window
.crypto
.getRandomValues(arr
)
11 return Array
.from(arr
, dec2hex
).join('')
14 // Populate variants dropdown list
15 let dropdown
= $.getElementById("selectVariant");
16 dropdown
[0] = new Option("? ? ?", "_random", true, true);
17 dropdown
[0].title
= "Random variant";
18 for (let i
= 0; i
< variants
.length
; i
++) {
19 let newOption
= new Option(
20 variants
[i
].disp
|| variants
[i
].name
, variants
[i
].name
, false, false);
21 newOption
.title
= variants
[i
].desc
;
22 dropdown
[dropdown
.length
] = newOption
;
25 // Ensure that I have a socket ID and a name
26 if (!localStorage
.getItem("sid"))
27 localStorage
.setItem("sid", generateId(8));
28 if (!localStorage
.getItem("name"))
29 localStorage
.setItem("name", "@non" + generateId(4));
30 const sid
= localStorage
.getItem("sid");
31 $.getElementById("myName").value
= localStorage
.getItem("name");
33 // "Material" input field name
34 let inputName
= document
.getElementById("myName");
35 let formField
= document
.getElementById("ng-name");
36 const setActive
= (active
) => {
37 if (active
) formField
.classList
.add("form-field--is-active");
39 formField
.classList
.remove("form-field--is-active");
40 inputName
.value
=== "" ?
41 formField
.classList
.remove("form-field--is-filled") :
42 formField
.classList
.add("form-field--is-filled");
45 inputName
.onblur
= () => setActive(false);
46 inputName
.onfocus
= () => setActive(true);
53 localStorage
.setItem("name", $.getElementById("myName").value
);
56 // Turn a "tab" on, and "close" all others
57 function toggleVisible(element
) {
58 for (elt
of document
.querySelectorAll('main > div')) {
59 if (elt
.id
!= element
) elt
.style
.display
= "none";
60 else elt
.style
.display
= "block";
62 if (element
.id
== "newGame") {
63 // Workaround "superposed texts" effect
71 seek_vname
= $.getElementById("selectVariant").value
;
72 send("seekgame", {vname: seek_vname
, name: localStorage
.getItem("name")});
73 toggleVisible("pendingSeek");
75 function cancelSeek() {
76 send("cancelseek", {vname: seek_vname
});
77 toggleVisible("newGame");
80 function sendRematch() {
81 send("rematch", { gid: gid
});
82 toggleVisible("pendingRematch");
84 function cancelRematch() {
85 send("norematch", { gid: gid
});
86 toggleVisible("newGame");
89 // Play with a friend (or not ^^)
90 function showNewGameForm() {
91 const vname
= $.getElementById("selectVariant").value
;
92 if (vname
== "_random") alert("Select a variant first");
94 $.getElementById("gameLink").innerHTML
= "";
95 $.getElementById("selectColor").selectedIndex
= 0;
96 toggleVisible("newGameForm");
97 import(`/variants/${vname}/class.js`).then(module
=> {
98 window
.V
= module
.default;
103 function backToNormalSeek() { toggleVisible("newGame"); }
105 function toggleStyle(e
, word
) {
106 options
[word
] = !options
[word
];
107 e
.target
.classList
.toggle("highlight-word");
111 function prepareOptions() {
113 let optHtml
= V
.Options
.select
.map(select
=> { return `
114 <div class="option-select">
115 <label for="var_${select.variable}">${select.label}</label>
117 <select id="var_${select.variable}" data-numeric="1">` +
118 select
.options
.map(option
=> { return `
120 value="${option.value}"
121 ${option.value == select.defaut ? " selected" : ""}
127 <span class="focus"></span>
131 optHtml
+= V
.Options
.check
.map(check
=> {
133 <div class="option-check">
134 <label class="checkbox">
135 <input id="var_${check.variable}"
136 type="checkbox"${check.defaut ? " checked" : ""}/>
137 <span class="spacer"></span>
138 <span>${check.label}</span>
142 if (V
.Options
.styles
.length
>= 1) {
143 optHtml
+= '<div class="words">';
145 const stylesLength
= V
.Options
.styles
.length
;
146 while (i
< stylesLength
) {
147 optHtml
+= '<div class="row">';
148 for (let j
=i
; j
<i
+4; j
++) {
149 if (j
== stylesLength
) break;
150 const style
= V
.Options
.styles
[j
];
152 `<span onClick="toggleStyle(event, '${style}')">${style}</span>`;
159 $.getElementById("gameOptions").innerHTML
= optHtml
;
162 function getGameLink() {
163 const vname
= $.getElementById("selectVariant").value
;
164 const color
= $.getElementById("selectColor").value
;
165 for (const select
of $.querySelectorAll("#gameOptions select")) {
166 let value
= select
.value
;
167 if (select
.attributes
["data-numeric"]) value
= parseInt(value
, 10);
168 if (value
) options
[ select
.id
.split("_")[1] ] = value
;
170 for (const check
of $.querySelectorAll("#gameOptions input")) {
171 if (check
.checked
) options
[ check
.id
.split("_")[1] ] = check
.checked
;
175 player: { sid: sid
, name: localStorage
.getItem("name"), color: color
},
180 const fillGameInfos
= (gameInfos
, oppIndex
) => {
181 fetch(`/variants/${gameInfos.vname}/rules.html`)
182 .then(res
=> res
.text())
185 <div class="players-info">
187 <span class="bold">${gameInfos.vdisp}</span>
188 <span>vs. ${gameInfos.players[oppIndex].name}</span>
191 const options
= Object
.entries(gameInfos
.options
);
192 if (options
.length
> 0) {
193 htmlContent
+= '<div class="options-info">';
195 while (i
< options
.length
) {
196 htmlContent
+= '<div class="row">';
197 for (let j
=i
; j
<i
+4; j
++) {
198 if (j
== options
.length
) break;
199 const opt
= options
[j
];
201 '<span class="option">' +
202 (opt
[1] === true ? opt
[0] : `${opt[0]}:${opt[1]}`) + " " +
205 htmlContent
+= "</div>";
208 htmlContent
+= "</div>";
211 <div class="rules">${txt}</div>
212 <div class="btn-wrap">
213 <button onClick="toggleGameInfos()">Back to game</button>
215 $.getElementById("gameInfos").innerHTML
= htmlContent
;
222 let socket
, gid
, attempt
= 0;
223 const autoReconnectDelay
= () => {
224 return [100, 200, 500, 1000, 3000, 10000, 30000][Math
.min(attempt
, 6)];
227 function copyClipboard(msg
) { navigator
.clipboard
.writeText(msg
); }
228 function getWhatsApp(msg
) {
229 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
232 const tryResumeGame
= () => {
234 // If a game is found, resume it:
235 if (localStorage
.getItem("gid")) {
236 gid
= localStorage
.getItem("gid");
237 send("getgame", { gid: gid
});
240 // If URL indicates "play with a friend", start game:
241 const hashIdx
= document
.URL
.indexOf('#');
243 const urlParts
= $.URL
.split('#');
245 send("joingame", { gid: gid
, name: localStorage
.getItem("name") });
246 localStorage
.setItem("gid", gid
);
247 history
.replaceState(null, '', urlParts
[0]);
252 const messageCenter
= (msg
) => {
253 const obj
= JSON
.parse(msg
.data
);
257 if (document
.hidden
) notifyMe("game");
262 // Game vs. friend just created on server: share link now
263 case "gamecreated": {
264 const link
= `${Params.http_server}/#${obj.gid}`;
265 $.getElementById("gameLink").innerHTML
= `
267 <a href="${getWhatsApp(link)}">WhatsApp</a>
269 <span onClick='copyClipboard("${link}")'>ToClipboard</span>
275 // Game vs. friend joined after 1 minute (try again!)
277 alert("Game no longer available");
279 // Get infos of a running game (already launched)
283 // Tried to resume a game which is now gone:
285 localStorage
.removeItem("gid");
287 // Receive opponent's move:
289 if (document
.hidden
) notifyMe("move");
290 vr
.playReceivedMove(obj
.moves
, () => {
291 if (vr
.getCurrentScore(obj
.moves
[obj
.moves
.length
-1]) != "*") {
292 localStorage
.removeItem("gid");
293 setTimeout( () => toggleVisible("gameStopped"), 2000 );
295 else toggleTurnIndicator(true);
298 // Opponent stopped game (draw, abort, resign...)
300 toggleVisible("gameStopped");
301 localStorage
.removeItem("gid");
303 // Opponent cancelled rematch:
305 toggleVisible("newGame");
310 const handleError
= (err
) => {
311 if (err
.code
=== 'ECONNREFUSED') {
312 removeAllListeners();
313 alert("Server refused connection. Please reload page later");
318 const handleClose
= () => {
320 removeAllListeners();
322 }, autoReconnectDelay());
325 const removeAllListeners
= () => {
326 socket
.removeEventListener("open", tryResumeGame
);
327 socket
.removeEventListener("message", messageCenter
);
328 socket
.removeEventListener("error", handleError
);
329 socket
.removeEventListener("close", handleClose
);
332 const connectToWSS
= () => {
334 new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
335 socket
.addEventListener("open", tryResumeGame
);
336 socket
.addEventListener("message", messageCenter
);
337 socket
.addEventListener("error", handleError
);
338 socket
.addEventListener("close", handleClose
);
343 const send
= (code
, data
) => {
344 socket
.send(JSON
.stringify(Object
.assign({code: code
}, data
)));
350 function toggleTurnIndicator(myTurn
) {
351 let indicator
= $.getElementById("chessboard");
352 if (myTurn
) indicator
.style
.outline
= "thick solid green";
353 else indicator
.style
.outline
= "thick solid lightgrey";
356 function notifyMe(code
) {
357 const doNotify
= () => {
358 // NOTE: empty body (TODO?)
359 new Notification("New " + code
, { vibrate: [200, 100, 200] });
360 new Audio("/assets/new_" + code
+ ".mp3").play();
362 if (Notification
.permission
=== 'granted') doNotify();
363 else if (Notification
.permission
!== 'denied') {
364 Notification
.requestPermission().then(permission
=> {
365 if (permission
=== 'granted') doNotify();
371 const afterPlay
= (move) => { //pack into one moves array, then send
378 if (vr
.turn
!= playerColor
) {
379 toggleTurnIndicator(false);
380 send("newmove", { gid: gid
, moves: curMoves
, fen: vr
.getFen() });
382 const result
= vr
.getCurrentScore(move);
385 toggleVisible("gameStopped");
386 send("gameover", { gid: gid
});
392 // Avoid loading twice the same stylesheet:
393 const conditionalLoadCSS
= (vname
) => {
394 const allIds
= [].slice
.call($.styleSheets
).map(s
=> s
.id
);
395 const newId
= vname
+ "_css";
396 if (!allIds
.includes(newId
)) {
397 $.getElementsByTagName("head")[0].insertAdjacentHTML(
399 `<link id="${newId}" rel="stylesheet"
400 href="/variants/${vname}/style.css"/>`);
405 function initializeGame(obj
) {
406 const options
= obj
.options
|| {};
407 import(`/variants/${obj.vname}/class.js`).then(module
=> {
408 window
.V
= module
.default;
409 conditionalLoadCSS(obj
.vname
);
410 playerColor
= (sid
== obj
.players
[0].sid
? "w" : "b");
411 // Init + remove potential extra DOM elements from a previous game:
412 document
.getElementById("boardContainer").innerHTML
= `
413 <div id="upLeftInfos"
414 onClick="toggleGameInfos()">
416 viewBox="0.5 0.5 100 100">
418 <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"/>
422 <div id="upRightStop"
423 onClick="confirmStopGame()">
425 viewBox="0 0 533.333 533.333">
427 <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"/>
431 <div class="resizeable" id="chessboard"></div>`;
433 seed: obj
.seed
, //may be null if FEN already exists (running game)
435 element: "chessboard",
437 afterPlay: afterPlay
,
442 if (playerColor
== "w") send("setfen", {gid: obj
.gid
, fen: vr
.getFen()});
443 localStorage
.setItem("gid", obj
.gid
);
445 const select
= $.getElementById("selectVariant");
447 for (let i
=0; i
<select
.options
.length
; i
++) {
448 if (select
.options
[i
].value
== obj
.vname
) {
449 obj
.vdisp
= select
.options
[i
].text
;
453 fillGameInfos(obj
, playerColor
== "w" ? 1 : 0);
454 if (obj
.randvar
) toggleVisible("gameInfos");
455 else toggleVisible("boardContainer");
456 toggleTurnIndicator(vr
.turn
== playerColor
);
460 function confirmStopGame() {
461 if (confirm("Stop game?")) {
462 send("gameover", { gid: gid
, relay: true });
463 localStorage
.removeItem("gid");
464 toggleVisible("gameStopped");
468 function toggleGameInfos() {
469 if ($.getElementById("gameInfos").style
.display
== "none")
470 toggleVisible("gameInfos");
472 toggleVisible("boardContainer");
473 // Quickfix for the "vanished piece" bug (move played while on game infos)
474 vr
.setupPieces(); //TODO: understand better
478 $.body
.addEventListener("keydown", (e
) => {
479 if (!localStorage
.getItem("gid")) return;
480 if (e
.keyCode
== 27) confirmStopGame();
481 else if (e
.keyCode
== 32) {