1 let $ = document
; //shortcut
6 // https://stackoverflow.com/a/27747377/12660887
7 function generateId (len
) {
8 const dec2hex
= (dec
) => dec
.toString(16).padStart(2, "0");
9 let arr
= new Uint8Array(len
/ 2); //len/2 because 2 chars per hex value
10 window
.crypto
.getRandomValues(arr
); //fill with random integers
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
) => {
38 formField
.classList
.add("form-field--is-active");
40 formField
.classList
.remove("form-field--is-active");
42 ? formField
.classList
.remove("form-field--is-filled")
43 : formField
.classList
.add("form-field--is-filled");
47 inputName
.onblur
= () => setActive(false);
48 inputName
.onfocus
= () => setActive(true);
54 // 'onChange' event on name input text field [HTML]
55 localStorage
.setItem("name", $.getElementById("myName").value
);
58 // Turn a "tab" on, and "close" all others
59 function toggleVisible(element
) {
60 for (elt
of document
.querySelectorAll("main > div")) {
61 if (elt
.id
!= element
)
62 elt
.style
.display
= "none";
64 elt
.style
.display
= "block";
66 if (element
== "boardContainer") {
67 // Avoid smartphone scrolling effects (TODO?)
68 document
.querySelector("html").style
.overflow
= "hidden";
69 document
.body
.style
.overflow
= "hidden";
72 document
.querySelector("html").style
.overflow
= "visible";
73 document
.body
.style
.overflow
= "visible";
74 // Workaround "superposed texts" effect:
75 if (element
== "newGame")
82 seek_vname
= $.getElementById("selectVariant").value
;
84 {vname: seek_vname
, name: localStorage
.getItem("name")})
86 toggleVisible("pendingSeek");
89 function cancelSeek() {
90 if (send("cancelseek", {vname: seek_vname
}))
91 toggleVisible("newGame");
94 function sendRematch(random
) {
95 if (send("rematch", {gid: gid
, random: !!random
}))
96 toggleVisible("pendingRematch");
98 function cancelRematch() {
99 if (send("norematch", {gid: gid
}))
100 toggleVisible("newGame");
103 // Play with a friend (or not ^^)
104 function showNewGameForm() {
105 const vname
= $.getElementById("selectVariant").value
;
106 if (vname
== "_random")
107 alert("Select a variant first");
109 $.getElementById("gameLink").innerHTML
= "";
110 $.getElementById("selectColor").selectedIndex
= 0;
111 toggleVisible("newGameForm");
112 import(`/variants/${vname}/class.js`).then(module
=> {
113 window
.V
= module
.default;
114 for (const [k
, v
] of Object
.entries(V
.Aliases
))
120 function backToNormalSeek() {
121 toggleVisible("newGame");
124 function toggleStyle(event
, obj
) {
125 const word
= obj
.innerHTML
;
126 options
[word
] = !options
[word
];
127 event
.target
.classList
.toggle("highlight-word");
131 function prepareOptions() {
134 if (V
.Options
.select
) {
135 optHtml
+= V
.Options
.select
.map(select
=> { return `
136 <div class="option-select">
137 <label for="var_${select.variable}">${select.label}</label>
139 <select id="var_${select.variable}" data-numeric="1">` +
140 select
.options
.map(option
=> { return `
142 value="${option.value}"
143 ${option.value == select.defaut ? " selected" : ""}
149 <span class="focus"></span>
154 if (V
.Options
.check
) {
155 optHtml
+= V
.Options
.check
.map(check
=> { return `
156 <div class="option-check">
157 <label class="checkbox">
158 <input id="var_${check.variable}"
159 type="checkbox"${check.defaut ? " checked" : ""}/>
160 <span class="spacer"></span>
161 <span>${check.label}</span>
166 if (V
.Options
.input
) {
167 optHtml
+= V
.Options
.input
.map(input
=> { return `
168 <div class="option-input">
169 <label class="input">
170 <input id="var_${input.variable}"
172 content="${input.defaut}"/>
173 <span class="spacer"></span>
174 <span>${input.label}</span>
179 if (V
.Options
.styles
) {
180 optHtml
+= '<div class="words">';
182 const stylesLength
= V
.Options
.styles
.length
;
183 while (i
< stylesLength
) {
184 optHtml
+= '<div class="row">';
185 for (let j
=i
; j
<i
+4; j
++) {
186 if (j
== stylesLength
)
188 const style
= V
.Options
.styles
[j
];
189 optHtml
+= `<span onClick="toggleStyle(event, this)">${style}</span>`;
196 $.getElementById("gameOptions").innerHTML
= optHtml
;
199 function getGameLink() {
200 const vname
= $.getElementById("selectVariant").value
;
201 const color
= $.getElementById("selectColor").value
;
202 for (const select
of $.querySelectorAll("#gameOptions select")) {
203 let value
= select
.value
;
204 if (select
.attributes
["data-numeric"])
205 value
= parseInt(value
, 10);
207 options
[ select
.id
.split("_")[1] ] = value
;
209 for (const check
of $.querySelectorAll("#gameOptions input")) {
211 options
[ check
.id
.split("_")[1] ] = check
.checked
;
215 player: {sid: sid
, name: localStorage
.getItem("name"), color: color
},
220 function fillGameInfos(gameInfos
, oppIndex
) {
221 fetch(`/variants/${gameInfos.vname}/rules.html`)
222 .then(res
=> res
.text())
225 <div class="players-info">
227 <span class="bold">${gameInfos.vdisp}</span>
228 <span>vs. ${gameInfos.players[oppIndex].name}</span>
231 const options
= Object
.entries(gameInfos
.options
);
232 if (options
.length
> 0) {
233 htmlContent
+= '<div class="options-info">';
235 while (i
< options
.length
) {
236 htmlContent
+= '<div class="row">';
237 for (let j
=i
; j
<i
+4; j
++) {
238 if (j
== options
.length
)
240 const opt
= options
[j
];
244 '<span class="option">' +
245 (opt
[1] === true ? opt
[0] : `${opt[0]}:${opt[1]}`) + " " +
248 htmlContent
+= "</div>";
251 htmlContent
+= "</div>";
254 <div class="rules">${txt}</div>
255 <div class="btn-wrap">
256 <button onClick="toggleGameInfos()">Back to game</button>
258 $.getElementById("gameInfos").innerHTML
= htmlContent
;
265 let socket
, gid
, recoAttempt
= 0;
266 const autoReconnectDelay
= () => {
267 return [100, 200, 500, 1000, 3000, 10000, 30000][Math
.min(recoAttempt
, 6)];
270 function send(code
, data
, opts
) {
272 const trySend
= () => {
273 if (socket
.readyState
== 1) {
274 socket
.send(JSON
.stringify(Object
.assign({code: code
}, data
)));
281 const firstTry
= trySend();
284 // Retry for a few seconds (sending move)
286 const retryLoop
= setInterval(
288 if (trySend() || ++sendAttempt
>= 3)
289 clearInterval(retryLoop
);
290 if (sendAttempt
>= 3 && opts
.error
)
302 function copyClipboard(msg
) {
303 navigator
.clipboard
.writeText(msg
);
305 function getWhatsApp(msg
) {
306 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
309 const tryResumeGame
= () => {
311 // If a game is found, resume it:
312 if (localStorage
.getItem("gid")) {
313 gid
= localStorage
.getItem("gid");
318 error: () => alert("Cannot load game: no connection")
322 // If URL indicates "play with a friend", start game:
323 const hashIdx
= document
.URL
.indexOf('#');
325 const urlParts
= $.URL
.split('#');
327 localStorage
.setItem("gid", gid
);
328 history
.replaceState(null, '', urlParts
[0]); //hide game ID
330 {gid: gid
, name: localStorage
.getItem("name")},
333 error: () => alert("Cannot load game: no connection")
339 const messageCenter
= (msg
) => {
340 const obj
= JSON
.parse(msg
.data
);
350 // Game vs. friend just created on server: share link now
351 case "gamecreated": {
352 const link
= `${Params.http_server}/#${obj.gid}`;
353 $.getElementById("gameLink").innerHTML
= `
355 <a href="${getWhatsApp(link)}">WhatsApp</a>
357 <span onClick="copyClipboard('${link}')">ToClipboard</span>
363 // Game vs. friend joined after 1 minute (try again!)
365 alert("Game no longer available");
367 // Get infos of a running game (already launched)
371 // Tried to resume a game which is now gone:
373 localStorage
.removeItem("gid");
375 // Receive opponent's move:
377 // Basic check: was it really opponent's turn?
378 if (vr
.turn
== playerColor
)
382 vr
.playReceivedMove(obj
.moves
, () => {
383 if (vr
.getCurrentScore(obj
.moves
[obj
.moves
.length
-1]) != "*") {
384 localStorage
.removeItem("gid");
385 setTimeout( () => toggleVisible("gameStopped"), 2000 );
388 toggleTurnIndicator(true);
391 // Opponent stopped game (draw, abort, resign...)
393 toggleVisible("gameStopped");
394 localStorage
.removeItem("gid");
396 // Opponent cancelled rematch:
398 toggleVisible("newGame");
403 const handleError
= (err
) => {
404 if (err
.code
=== "ECONNREFUSED") {
405 removeAllListeners();
406 alert("Server refused connection. Please reload page later");
411 const handleClose
= () => {
413 removeAllListeners();
415 }, autoReconnectDelay());
418 function removeAllListeners() {
419 socket
.removeEventListener("open", tryResumeGame
);
420 socket
.removeEventListener("message", messageCenter
);
421 socket
.removeEventListener("error", handleError
);
422 socket
.removeEventListener("close", handleClose
);
425 function connectToWSS() {
427 new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
428 socket
.addEventListener("open", tryResumeGame
);
429 socket
.addEventListener("message", messageCenter
);
430 socket
.addEventListener("error", handleError
);
431 socket
.addEventListener("close", handleClose
);
439 function toggleTurnIndicator(myTurn
) {
441 $.getElementById("boardContainer").querySelector(".chessboard");
443 indicator
.style
.outline
= "thick solid green";
445 indicator
.style
.outline
= "thick solid lightgrey";
448 function notifyMe(code
) {
449 const doNotify
= () => {
450 // NOTE: empty body (TODO?)
451 new Notification("New " + code
, { vibrate: [200, 100, 200] });
452 new Audio("/assets/new_" + code
+ ".mp3").play();
454 if (Notification
.permission
=== "granted")
456 else if (Notification
.permission
!== "denied") {
457 Notification
.requestPermission().then(permission
=> {
458 if (permission
=== "granted")
466 const afterPlay
= (move) => {
467 const callbackAfterSend
= () => {
469 const result
= vr
.getCurrentScore(move);
472 toggleVisible("gameStopped");
473 send("gameover", {gid: gid
});
477 // Pack into one moves array, then send
479 if (vr
.turn
!= playerColor
) {
480 toggleTurnIndicator(false);
482 {gid: gid
, moves: curMoves
, fen: vr
.getFen()},
485 success: callbackAfterSend
,
486 error: () => alert("Move not sent: reload page")
492 function initializeGame(obj
) {
493 const options
= obj
.options
|| {};
494 import(`/variants/${obj.vname}/class.js`).then(module
=> {
495 window
.V
= module
.default;
496 for (const [k
, v
] of Object
.entries(V
.Aliases
))
498 // Load CSS. Avoid loading twice the same stylesheet:
499 const allIds
= [].slice
.call($.styleSheets
).map(s
=> s
.id
);
500 const newId
= obj
.vname
+ "_css";
501 if (!allIds
.includes(newId
)) {
502 $.getElementsByTagName("head")[0].insertAdjacentHTML(
504 `<link id="${newId}" rel="stylesheet"
505 href="/variants/${obj.vname}/style.css"/>`);
507 playerColor
= (sid
== obj
.players
[0].sid
? "w" : "b");
508 // Init + remove potential extra DOM elements from a previous game:
509 document
.getElementById("boardContainer").innerHTML
= `
510 <div id="upLeftInfos"
511 onClick="toggleGameInfos()">
513 viewBox="0.5 0.5 100 100">
515 <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"/>
519 <div id="upRightStop"
520 onClick="confirmStopGame()">
522 viewBox="0 0 533.333 533.333">
524 <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"/>
528 <div class="resizeable chessboard"></div>`;
530 seed: obj
.seed
, //may be null if FEN already exists (running game)
532 element: "boardContainer",
534 afterPlay: afterPlay
,
538 // Game creation: both players set FEN, in case of one is offline
539 send("setfen", {gid: obj
.gid
, fen: vr
.getFen()});
540 localStorage
.setItem("gid", obj
.gid
);
542 const select
= $.getElementById("selectVariant");
544 for (let i
=0; i
<select
.options
.length
; i
++) {
545 if (select
.options
[i
].value
== obj
.vname
) {
546 obj
.vdisp
= select
.options
[i
].text
;
550 fillGameInfos(obj
, playerColor
== "w" ? 1 : 0);
552 toggleVisible("gameInfos");
554 toggleVisible("boardContainer");
555 toggleTurnIndicator(vr
.turn
== playerColor
);
559 function confirmStopGame() {
560 if (confirm("Stop game?") && send("gameover", {gid: gid
, relay: true})) {
561 localStorage
.removeItem("gid");
562 toggleVisible("gameStopped");
566 function toggleGameInfos() {
567 if ($.getElementById("gameInfos").style
.display
== "none")
568 toggleVisible("gameInfos");
570 toggleVisible("boardContainer");
573 $.body
.addEventListener("keydown", (e
) => {
574 if (!localStorage
.getItem("gid"))
578 else if (e
.keyCode
== 32) {