Add falling pawn mode for Recycle + fix animation bug
[xogo.git] / app.js
CommitLineData
41534b92
BA
1let $ = document; //shortcut
2
3///////////////////
4// Initialisations
5
6// https://stackoverflow.com/a/27747377/12660887
41534b92 7function generateId (len) {
f46a68b8
BA
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('');
41534b92
BA
12}
13
14// Populate variants dropdown list
15let dropdown = $.getElementById("selectVariant");
16dropdown[0] = new Option("? ? ?", "_random", true, true);
17dropdown[0].title = "Random variant";
18for (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;
23}
24
25// Ensure that I have a socket ID and a name
26if (!localStorage.getItem("sid"))
27 localStorage.setItem("sid", generateId(8));
28if (!localStorage.getItem("name"))
29 localStorage.setItem("name", "@non" + generateId(4));
30const sid = localStorage.getItem("sid");
31$.getElementById("myName").value = localStorage.getItem("name");
32
86f3c2cd
BA
33// "Material" input field name
34let inputName = document.getElementById("myName");
35let formField = document.getElementById("ng-name");
36const setActive = (active) => {
37 if (active) formField.classList.add("form-field--is-active");
38 else {
39 formField.classList.remove("form-field--is-active");
f46a68b8
BA
40 inputName.value == ''
41 ? formField.classList.remove("form-field--is-filled")
42 : formField.classList.add("form-field--is-filled");
86f3c2cd
BA
43 }
44};
f46a68b8 45setActive(true);
86f3c2cd
BA
46inputName.onblur = () => setActive(false);
47inputName.onfocus = () => setActive(true);
86f3c2cd 48
41534b92
BA
49/////////
50// Utils
51
52function setName() {
f46a68b8 53 // 'onChange' event on name input text field [HTML]
41534b92
BA
54 localStorage.setItem("name", $.getElementById("myName").value);
55}
56
57// Turn a "tab" on, and "close" all others
58function toggleVisible(element) {
f46a68b8 59 for (elt of document.querySelectorAll("main > div")) {
41534b92
BA
60 if (elt.id != element) elt.style.display = "none";
61 else elt.style.display = "block";
62 }
a77150a1 63 if (element == "boardContainer") {
8022d544
BA
64 // Avoid smartphone scrolling effects (TODO?)
65 document.querySelector("html").style.overflow = "hidden";
66 document.body.style.overflow = "hidden";
67 }
68 else {
69 document.querySelector("html").style.overflow = "visible";
70 document.body.style.overflow = "visible";
f46a68b8
BA
71 // Workaround "superposed texts" effect:
72 if (element == "newGame") setActive(false);
86f3c2cd 73 }
41534b92
BA
74}
75
76let seek_vname;
77function seekGame() {
78 seek_vname = $.getElementById("selectVariant").value;
f46a68b8
BA
79 if (send("seekgame",
80 {vname: seek_vname, name: localStorage.getItem("name")})
81 ) {
82 toggleVisible("pendingSeek");
83 }
41534b92
BA
84}
85function cancelSeek() {
f46a68b8 86 if (send("cancelseek", {vname: seek_vname})) toggleVisible("newGame");
41534b92
BA
87}
88
89function sendRematch() {
f46a68b8 90 if (send("rematch", {gid: gid})) toggleVisible("pendingRematch");
41534b92
BA
91}
92function cancelRematch() {
f46a68b8 93 if (send("norematch", {gid: gid})) toggleVisible("newGame");
41534b92
BA
94}
95
96// Play with a friend (or not ^^)
97function showNewGameForm() {
98 const vname = $.getElementById("selectVariant").value;
99 if (vname == "_random") alert("Select a variant first");
100 else {
101 $.getElementById("gameLink").innerHTML = "";
102 $.getElementById("selectColor").selectedIndex = 0;
103 toggleVisible("newGameForm");
104 import(`/variants/${vname}/class.js`).then(module => {
cc2c7183
BA
105 window.V = module.default;
106 prepareOptions();
41534b92
BA
107 });
108 }
109}
f46a68b8
BA
110function backToNormalSeek() {
111 toggleVisible("newGame");
112}
41534b92 113
f46a68b8
BA
114function toggleStyle(event, obj) {
115 const word = obj.innerHTML;
41534b92 116 options[word] = !options[word];
f46a68b8 117 event.target.classList.toggle("highlight-word");
41534b92
BA
118}
119
120let options;
cc2c7183 121function prepareOptions() {
41534b92 122 options = {};
cc2c7183 123 let optHtml = V.Options.select.map(select => { return `
86f3c2cd
BA
124 <div class="option-select">
125 <label for="var_${select.variable}">${select.label}</label>
126 <div class="select">
127 <select id="var_${select.variable}" data-numeric="1">` +
128 select.options.map(option => { return `
129 <option
130 value="${option.value}"
131 ${option.value == select.defaut ? " selected" : ""}
132 >
133 ${option.label}
134 </option>`;
135 }).join("") + `
136 </select>
137 <span class="focus"></span>
138 </div>
139 </div>`;
140 }).join("");
cc2c7183 141 optHtml += V.Options.check.map(check => {
86f3c2cd
BA
142 return `
143 <div class="option-check">
144 <label class="checkbox">
145 <input id="var_${check.variable}"
146 type="checkbox"${check.defaut ? " checked" : ""}/>
147 <span class="spacer"></span>
148 <span>${check.label}</span>
149 </label>
150 </div>`;
151 }).join("");
cc2c7183 152 if (V.Options.styles.length >= 1) {
86f3c2cd
BA
153 optHtml += '<div class="words">';
154 let i = 0;
cc2c7183 155 const stylesLength = V.Options.styles.length;
86f3c2cd
BA
156 while (i < stylesLength) {
157 optHtml += '<div class="row">';
158 for (let j=i; j<i+4; j++) {
159 if (j == stylesLength) break;
cc2c7183 160 const style = V.Options.styles[j];
f46a68b8 161 optHtml += `<span onClick="toggleStyle(event, this)">${style}</span>`;
86f3c2cd
BA
162 }
163 optHtml += "</div>";
164 i += 4;
41534b92 165 }
86f3c2cd 166 optHtml += "</div>";
41534b92 167 }
41534b92
BA
168 $.getElementById("gameOptions").innerHTML = optHtml;
169}
170
171function getGameLink() {
172 const vname = $.getElementById("selectVariant").value;
173 const color = $.getElementById("selectColor").value;
86f3c2cd 174 for (const select of $.querySelectorAll("#gameOptions select")) {
41534b92
BA
175 let value = select.value;
176 if (select.attributes["data-numeric"]) value = parseInt(value, 10);
cc2c7183
BA
177 if (value) options[ select.id.split("_")[1] ] = value;
178 }
179 for (const check of $.querySelectorAll("#gameOptions input")) {
180 if (check.checked) options[ check.id.split("_")[1] ] = check.checked;
41534b92 181 }
41534b92
BA
182 send("creategame", {
183 vname: vname,
f46a68b8 184 player: {sid: sid, name: localStorage.getItem("name"), color: color},
41534b92
BA
185 options: options
186 });
187}
188
f46a68b8 189function fillGameInfos(gameInfos, oppIndex) {
41534b92
BA
190 fetch(`/variants/${gameInfos.vname}/rules.html`)
191 .then(res => res.text())
192 .then(txt => {
193 let htmlContent = `
86f3c2cd
BA
194 <div class="players-info">
195 <p>
196 <span class="bold">${gameInfos.vdisp}</span>
197 <span>vs. ${gameInfos.players[oppIndex].name}</span>
198 </p>
199 </div>`;
200 const options = Object.entries(gameInfos.options);
201 if (options.length > 0) {
202 htmlContent += '<div class="options-info">';
203 let i = 0;
204 while (i < options.length) {
205 htmlContent += '<div class="row">';
206 for (let j=i; j<i+4; j++) {
207 if (j == options.length) break;
208 const opt = options[j];
f8b43ef7 209 if (!opt[1]) continue;
86f3c2cd
BA
210 htmlContent +=
211 '<span class="option">' +
212 (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
f46a68b8 213 "</span>";
86f3c2cd
BA
214 }
215 htmlContent += "</div>";
216 i += 4;
217 }
218 htmlContent += "</div>";
219 }
41534b92 220 htmlContent += `
86f3c2cd
BA
221 <div class="rules">${txt}</div>
222 <div class="btn-wrap">
223 <button onClick="toggleGameInfos()">Back to game</button>
224 </div>`;
41534b92
BA
225 $.getElementById("gameInfos").innerHTML = htmlContent;
226 });
f46a68b8 227}
41534b92
BA
228
229////////////////
230// Communication
231
f46a68b8 232let socket, gid, recoAttempt = 0;
41534b92 233const autoReconnectDelay = () => {
f46a68b8 234 return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(recoAttempt, 6)];
41534b92
BA
235};
236
f46a68b8
BA
237function send(code, data, opts) {
238 opts = opts || {};
239 const trySend = () => {
240 if (socket.readyState == 1) {
241 socket.send(JSON.stringify(Object.assign({code: code}, data)));
242 if (opts.success) opts.success();
243 return true;
244 }
245 return false;
246 };
247 const firstTry = trySend();
248 if (!firstTry) {
249 if (opts.retry) {
250 // Retry for a few seconds (sending move)
251 let sendAttempt = 1;
252 const retryLoop = setInterval(
253 () => {
254 if (trySend() || ++sendAttempt >= 3) clearInterval(retryLoop);
255 if (sendAttempt >= 3 && opts.error) opts.error();
256 },
257 1000
258 );
259 }
260 else if (opt.error) opts.error();
261 }
262 return firstTry;
263}
264
265function copyClipboard(msg) {
266 navigator.clipboard.writeText(msg);
267}
41534b92
BA
268function getWhatsApp(msg) {
269 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
270}
271
272const tryResumeGame = () => {
f46a68b8 273 recoAttempt = 0;
41534b92
BA
274 // If a game is found, resume it:
275 if (localStorage.getItem("gid")) {
276 gid = localStorage.getItem("gid");
f46a68b8
BA
277 send("getgame",
278 {gid: gid},
279 {
280 retry: true,
281 error: () => alert("Cannot load game: no connection")
282 });
41534b92
BA
283 }
284 else {
285 // If URL indicates "play with a friend", start game:
286 const hashIdx = document.URL.indexOf('#');
287 if (hashIdx >= 0) {
288 const urlParts = $.URL.split('#');
289 gid = urlParts[1];
41534b92 290 localStorage.setItem("gid", gid);
f46a68b8
BA
291 history.replaceState(null, '', urlParts[0]); //hide game ID
292 send("joingame",
293 {gid: gid, name: localStorage.getItem("name")},
294 {
295 retry: true,
296 error: () => alert("Cannot load game: no connection")
297 });
41534b92
BA
298 }
299 }
300};
301
302const messageCenter = (msg) => {
303 const obj = JSON.parse(msg.data);
304 switch (obj.code) {
305 // Start new game:
306 case "gamestart": {
016306e3 307 if (document.hidden) notifyMe("game");
41534b92
BA
308 gid = obj.gid;
309 initializeGame(obj);
310 break;
311 }
312 // Game vs. friend just created on server: share link now
313 case "gamecreated": {
314 const link = `${Params.http_server}/#${obj.gid}`;
315 $.getElementById("gameLink").innerHTML = `
316 <p>
317 <a href="${getWhatsApp(link)}">WhatsApp</a>
318 /
f46a68b8 319 <span onClick="copyClipboard('${link}')">ToClipboard</span>
41534b92
BA
320 </p>
321 <p>${link}</p>
322 `;
323 break;
324 }
325 // Game vs. friend joined after 1 minute (try again!)
326 case "jointoolate":
327 alert("Game no longer available");
328 break;
329 // Get infos of a running game (already launched)
330 case "gameinfo":
331 initializeGame(obj);
332 break;
333 // Tried to resume a game which is now gone:
334 case "nogame":
335 localStorage.removeItem("gid");
336 break;
337 // Receive opponent's move:
338 case "newmove":
f46a68b8
BA
339 // Basic check: was it really opponent's turn?
340 if (vr.turn == playerColor) break;
016306e3 341 if (document.hidden) notifyMe("move");
41534b92
BA
342 vr.playReceivedMove(obj.moves, () => {
343 if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
344 localStorage.removeItem("gid");
345 setTimeout( () => toggleVisible("gameStopped"), 2000 );
346 }
347 else toggleTurnIndicator(true);
348 });
349 break;
350 // Opponent stopped game (draw, abort, resign...)
351 case "gameover":
352 toggleVisible("gameStopped");
353 localStorage.removeItem("gid");
354 break;
355 // Opponent cancelled rematch:
356 case "closerematch":
357 toggleVisible("newGame");
358 break;
359 }
360};
361
362const handleError = (err) => {
f46a68b8 363 if (err.code === "ECONNREFUSED") {
41534b92
BA
364 removeAllListeners();
365 alert("Server refused connection. Please reload page later");
366 }
367 socket.close();
368};
369
370const handleClose = () => {
371 setTimeout(() => {
372 removeAllListeners();
373 connectToWSS();
374 }, autoReconnectDelay());
375};
376
f46a68b8 377function removeAllListeners() {
41534b92
BA
378 socket.removeEventListener("open", tryResumeGame);
379 socket.removeEventListener("message", messageCenter);
380 socket.removeEventListener("error", handleError);
381 socket.removeEventListener("close", handleClose);
f46a68b8 382}
41534b92 383
f46a68b8 384function connectToWSS() {
41534b92
BA
385 socket =
386 new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
387 socket.addEventListener("open", tryResumeGame);
388 socket.addEventListener("message", messageCenter);
389 socket.addEventListener("error", handleError);
390 socket.addEventListener("close", handleClose);
f46a68b8
BA
391 recoAttempt++;
392}
41534b92
BA
393connectToWSS();
394
41534b92
BA
395///////////
396// Playing
397
398function toggleTurnIndicator(myTurn) {
399 let indicator = $.getElementById("chessboard");
400 if (myTurn) indicator.style.outline = "thick solid green";
401 else indicator.style.outline = "thick solid lightgrey";
402}
403
404function notifyMe(code) {
405 const doNotify = () => {
406 // NOTE: empty body (TODO?)
407 new Notification("New " + code, { vibrate: [200, 100, 200] });
408 new Audio("/assets/new_" + code + ".mp3").play();
409 }
f46a68b8
BA
410 if (Notification.permission === "granted") doNotify();
411 else if (Notification.permission !== "denied") {
016306e3 412 Notification.requestPermission().then(permission => {
f46a68b8 413 if (permission === "granted") doNotify();
41534b92
BA
414 });
415 }
416}
417
8a9f61ce 418let curMoves = [],
f46a68b8 419 lastFen;
8a9f61ce 420const afterPlay = (move) => {
f46a68b8
BA
421 const callbackAfterSend = () => {
422 curMoves = [];
423 const result = vr.getCurrentScore(move);
424 if (result != "*") {
425 setTimeout(() => {
426 toggleVisible("gameStopped");
427 send("gameover", {gid: gid});
428 }, 2000);
429 }
430 };
8a9f61ce 431 // Pack into one moves array, then send
f8b43ef7 432 curMoves.push(move);
21e8e712 433 if (vr.turn != playerColor) {
41534b92 434 toggleTurnIndicator(false);
f46a68b8
BA
435 send("newmove",
436 {gid: gid, moves: curMoves, fen: vr.getFen()},
437 {
438 retry: true,
439 success: callbackAfterSend,
440 error: () => alert("Move not sent: reload page")
441 });
41534b92
BA
442 }
443};
444
21e8e712 445let vr, playerColor;
41534b92
BA
446function initializeGame(obj) {
447 const options = obj.options || {};
448 import(`/variants/${obj.vname}/class.js`).then(module => {
cc2c7183 449 window.V = module.default;
f46a68b8
BA
450 // Load CSS. Avoid loading twice the same stylesheet:
451 const allIds = [].slice.call($.styleSheets).map(s => s.id);
452 const newId = obj.vname + "_css";
453 if (!allIds.includes(newId)) {
454 $.getElementsByTagName("head")[0].insertAdjacentHTML(
455 "beforeend",
456 `<link id="${newId}" rel="stylesheet"
457 href="/variants/${obj.vname}/style.css"/>`);
458 }
21e8e712 459 playerColor = (sid == obj.players[0].sid ? "w" : "b");
41534b92
BA
460 // Init + remove potential extra DOM elements from a previous game:
461 document.getElementById("boardContainer").innerHTML = `
462 <div id="upLeftInfos"
463 onClick="toggleGameInfos()">
cc2c7183
BA
464 <svg version="1.1"
465 viewBox="0.5 0.5 100 100">
466 <g>
467 <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"/>
468 </g>
469 </svg>
41534b92
BA
470 </div>
471 <div id="upRightStop"
472 onClick="confirmStopGame()">
cc2c7183
BA
473 <svg version="1.1"
474 viewBox="0 0 533.333 533.333">
475 <g>
476 <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"/>
477 </g>
478 </svg>
41534b92
BA
479 </div>
480 <div class="resizeable" id="chessboard"></div>`;
cc2c7183 481 vr = new V({
41534b92
BA
482 seed: obj.seed, //may be null if FEN already exists (running game)
483 fen: obj.fen,
484 element: "chessboard",
21e8e712 485 color: playerColor,
41534b92
BA
486 afterPlay: afterPlay,
487 options: options
488 });
489 if (!obj.fen) {
f46a68b8
BA
490 // Game creation: both players set FEN, in case of one is offline
491 send("setfen", {gid: obj.gid, fen: vr.getFen()});
41534b92
BA
492 localStorage.setItem("gid", obj.gid);
493 }
494 const select = $.getElementById("selectVariant");
495 obj.vdisp = "";
496 for (let i=0; i<select.options.length; i++) {
497 if (select.options[i].value == obj.vname) {
498 obj.vdisp = select.options[i].text;
499 break;
500 }
501 }
21e8e712 502 fillGameInfos(obj, playerColor == "w" ? 1 : 0);
41534b92
BA
503 if (obj.randvar) toggleVisible("gameInfos");
504 else toggleVisible("boardContainer");
21e8e712 505 toggleTurnIndicator(vr.turn == playerColor);
41534b92
BA
506 });
507}
508
509function confirmStopGame() {
f46a68b8 510 if (confirm("Stop game?") && send("gameover", {gid: gid, relay: true})) {
41534b92
BA
511 localStorage.removeItem("gid");
512 toggleVisible("gameStopped");
513 }
514}
515
516function toggleGameInfos() {
517 if ($.getElementById("gameInfos").style.display == "none")
518 toggleVisible("gameInfos");
f46a68b8 519 else toggleVisible("boardContainer");
41534b92
BA
520}
521
522$.body.addEventListener("keydown", (e) => {
523 if (!localStorage.getItem("gid")) return;
524 if (e.keyCode == 27) confirmStopGame();
525 else if (e.keyCode == 32) {
526 e.preventDefault();
527 toggleGameInfos();
528 }
529});