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