save state
[westcastle.git] / js / index.js
CommitLineData
7a00c409
BA
1new Vue({
2 el: "#mahjong",
3 data: {
4 players: [], //array of objects, filled later
5 display: "players",
6 },
7 components: {
8 'my-players': {
48bee368 9 props: ['players','initPlayers'],
7a00c409
BA
10 template: `
11 <div id="players">
1369a09d 12 <div class="left">
7a00c409
BA
13 <p>Présents</p>
14 <table class="list">
15 <tr v-for="p in sortedPlayers" v-if="p.available" @click="toggleAvailability(p.index)">
16 <td>{{ p.prenom }}</td>
17 <td>{{ p.nom }}</td>
18 </tr>
19 </table>
20 </div>
1369a09d 21 <div id="inactive" class="right">
7a00c409
BA
22 <p>Absents</p>
23 <table class="list">
fd4a69e4 24 <tr v-for="p in sortedPlayers" v-if="!p.available && p.nom!=''" @click="toggleAvailability(p.index)">
7a00c409
BA
25 <td>{{ p.prenom }}</td>
26 <td>{{ p.nom }}</td>
27 </tr>
28 </table>
29 </div>
48bee368
BA
30 <div class="clear">
31 <input class="hide" id="upload" type="file" @change="upload"/>
32 <button class="btn block cancel" @click="uploadTrigger()" title="Charge la liste des joueurs, en principe en début de tournoi">
33 (Ré)initialiser
34 </button>
35 </div>
7a00c409
BA
36 </div>
37 `,
38 computed: {
39 sortedPlayers: function() {
40 return this.players
41 .map( (p,i) => { return Object.assign({}, p, {index: i}); })
42 .sort( (a,b) => {
43 return a.nom.localeCompare(b.nom);
44 });
45 },
46 },
47 methods: {
48 toggleAvailability: function(i) {
49 this.players[i].available = 1 - this.players[i].available;
48bee368
BA
50 },
51 uploadTrigger: function() {
52 document.getElementById("upload").click();
53 },
54 upload: function(e) {
55 let file = (e.target.files || e.dataTransfer.files)[0];
56 var reader = new FileReader();
57 reader.onloadend = ev => {
58 this.initPlayers(ev.currentTarget.result);
59 };
60 reader.readAsText(file);
7a00c409
BA
61 },
62 },
63 },
7a00c409 64 'my-pairings': {
48bee368 65 props: ['players','commitScores'],
7a00c409
BA
66 data: function() {
67 return {
68 unpaired: [],
69 tables: [], //array of arrays of players indices
1d2d7593 70 sessions: [], //"mini-points" for each table
7a00c409 71 currentIndex: -1, //table index for scoring
1369a09d 72 scored: [], //boolean for each table index
7a00c409
BA
73 };
74 },
75 template: `
76 <div id="pairings">
77 <div v-show="currentIndex < 0">
48bee368 78 <div class="button-container-horizontal">
496ab82e 79 <button class="btn cancel" :class="{hide: tables.length==0}" @click="cancelRound()" title="Annule la ronde courante : tous les scores en cours seront perdus, et un nouveau tirage effectué. ATTENTION : action irréversible">
48bee368
BA
80 Valider
81 </button>
496ab82e 82 <button id="doPairings" class="btn" :class="{cancel: tables.length>0}" :disabled="scored.some( s => { return !s; })" @click="doPairings()" title="Répartit les joueurs actifs aléatoirement sur les tables">
48bee368
BA
83 Nouvelle ronde
84 </button>
85 </div>
1369a09d 86 <div class="pairing" v-for="(table,index) in tables" :class="{scored: scored[index]}"
7a00c409
BA
87 @click="showScoreForm(table,index)">
88 <p>Table {{ index+1 }}</p>
89 <table>
90 <tr v-for="(i,j) in table">
fd4a69e4 91 <td :class="{toto: players[i].prenom=='Toto'}">{{ players[i].prenom }} {{ players[i].nom }}</td>
1d2d7593 92 <td class="score"><span v-show="sessions[index].length > 0">{{ sessions[index][j] }}</span></td>
7a00c409 93 </tr>
7a00c409
BA
94 </table>
95 </div>
96 <div v-if="unpaired.length>0" class="pairing unpaired">
97 <p>Exempts</p>
98 <div v-for="i in unpaired">
99 {{ players[i].prenom }} {{ players[i].nom }}
100 </div>
101 </div>
102 </div>
103 <div id="scoreInput" v-if="currentIndex >= 0">
104 <table>
105 <tr v-for="(index,i) in tables[currentIndex]">
fd4a69e4
BA
106 <td :class="{toto: players[tables[currentIndex][i]].prenom=='Toto'}">
107 {{ players[tables[currentIndex][i]].prenom }} {{ players[tables[currentIndex][i]].nom }}
108 </td>
48bee368 109 <td><input type="text" v-model="sessions[currentIndex][i]" :disabled="scored[currentIndex]"/></td>
7a00c409
BA
110 </tr>
111 </table>
1369a09d 112 <div class="button-container-horizontal">
496ab82e 113 <button :class="{hide:scored[currentIndex]}" class="btn validate" @click="setScore()" title="Enregistre le score dans la base">
48bee368
BA
114 Enregistrer
115 </button>
496ab82e 116 <button :class="{hide:!scored[currentIndex]}" class="btn cancel" @click="resetScore()" title="Annule le score précédemment enregistré">
48bee368
BA
117 Annuler
118 </button>
119 <button class="btn" @click="closeScoreForm()">Fermer</button>
7a00c409
BA
120 </div>
121 </div>
122 </div>
123 `,
124 methods: {
942ca610 125 // TODO: télécharger la ronde courante
3480360c 126 // TODO: mémoriser les appariements passés pour éviter que les mêmes joueurs se rencontrent plusieurs fois
496ab82e
BA
127 // --> dans la base: tableau rounds, rounds[0] : {tables[0,1,...], chacune contenant 4 indices de joueurs; + sessions[0,1,...]}
128 // --> devrait séparer les components en plusieurs fichiers...
129 // cas à 5 joueurs : le joueur exempt doit tourner (c'est fait automatiquement en fait)
130 cancelRound: function() {
942ca610
BA
131 this.scored.forEach( (s,i) => {
132 if (s)
133 {
134 // Cancel this table
135 this.currentIndex = i; //TODO: clumsy. funcions should take "index" as argument
136 this.resetScore();
137 }
138 });
139 this.currentIndex = -1;
140 this.doPairings();
496ab82e 141 },
7a00c409 142 doPairings: function() {
942ca610
BA
143 let rounds = JSON.parse(localStorage.getItem("rounds"));
144
145 if (this.scored.some( s => { return s; }))
146 {
147 this.commitScores(); //TODO: temporary: shouldn't be here... (incremental commit)
148 if (rounds === null)
149 rounds = [];
150 rounds.push(this.tables);
151 }
152
153 // 1) Compute the "meeting" matrix: who played who and how many times
154 let meetMat = _.range(this.players.length).map( i => {
155 _.range(this.players.length).map( j => {
156 return 0;
157 });
158 });
159 rounds.forEach( r => { //for each round
160 r.forEach( t => { //for each table within round
161 for (let i=0; i<4; i++) //TODO: these loops are ugly
162 {
163 for (let j=0; j<4; j++)
164 {
165 if (j!=i)
166 meetMat[i][j]++;
167 }
168 }
169 });
170 });
171
172 // 2) Pre-compute tables repartition (in numbers): depends on active players count % 4
173 let activePlayers = this.players
174 .map( (p,i) => { return Object.Assign({}, p, {index:i}); })
175 .filter( p => { return p.available; });
176 let repartition = _.times(Math.floor(activePlayers.length/4), _.constant(4));
177 switch (activePlayers.length % 4)
178 {
179 case 1:
180 // Need 2 more
181 if (repartition.length-1 >= 2)
182 {
183 repartition[0]--;
184 repartition[1]--;
185 repartition[repartition.length-1] += 2;
186 }
187 break;
188 case 2:
189 // Need 1 more
190 if (repartition.length-1 >= 1)
191 {
192 repartition[0]--;
193 repartition[repartition.length-1]++;
194 }
195 break;
196 }
197
198 // 3) Sort people by total games played (increasing) - naturally solve the potential unpaired case
199 let totalGames = _.range(this.players.length).map( i => { return 0; });
200 rounds.forEach( r => {
201 r.forEach(t => {
202 t.forEach( p => {
203 totalGames[p]++;
204 })
205 })
206 });
207 let sortedPlayers = activePlayers
208 .map( (p,i) => { return Object.Assign({}, p, {games:totalGames[p.index]}); })
209 .sort( (a,b) => { return a.games - b.games; });
210
211 // 4) Affect people on tables, following total games sorted order (with random sampling on ex-aequos)
212 // --> et surtout en minimisant la somme des rencontres précédentes (ci-dessus : cas particulier rare à peu de joueurs)
213//TODO
7a00c409
BA
214 // Simple case first: 4 by 4
215 let tables = [];
216 let currentTable = [];
ade10194 217 let ordering = _.shuffle(_.range(this.players.length));
7a00c409
BA
218 for (let i=0; i<ordering.length; i++)
219 {
220 if ( ! this.players[ordering[i]].available )
221 continue;
222 if (currentTable.length >= 4)
223 {
224 tables.push(currentTable);
225 currentTable = [];
226 }
227 currentTable.push(ordering[i]);
228 }
229 // Analyse remainder
230 this.unpaired = [];
231 if (currentTable.length != 0)
232 {
233 if (currentTable.length < 3)
234 {
235 let missingPlayers = 3 - currentTable.length;
236 // Pick players from 'missingPlayers' random different tables, if possible
237 if (tables.length >= missingPlayers)
238 {
239 let tblNums = _.sample(_.range(tables.length), missingPlayers);
240 tblNums.forEach( num => {
241 currentTable.push(tables[num].pop());
242 });
243 }
244 }
245 if (currentTable.length >= 3)
246 tables.push(currentTable);
247 else
248 this.unpaired = currentTable;
249 }
fd4a69e4
BA
250 // Ensure that all tables have 4 players
251 tables.forEach( t => {
252 if (t.length < 4)
253 t.push(0); //index of "Toto", ghost player
254 });
7a00c409 255 this.tables = tables;
1d2d7593 256 this.sessions = tables.map( t => { return []; }); //empty sessions
1369a09d
BA
257 this.scored = tables.map( t => { return false; }); //nothing scored yet
258 this.currentIndex = -1; //required if reset while scoring
7a00c409
BA
259 },
260 showScoreForm: function(table,index) {
1369a09d
BA
261 if (this.sessions[index].length == 0)
262 this.sessions[index] = _.times(table.length, _.constant(0));
7a00c409
BA
263 this.currentIndex = index;
264 },
48bee368
BA
265 closeScoreForm: function() {
266 if (!this.scored[this.currentIndex])
267 this.sessions[this.currentIndex] = [];
268 this.currentIndex = -1;
269 },
270 getPdts: function() {
1d2d7593 271 let sortedSessions = this.sessions[this.currentIndex]
ce0473b4
BA
272 .map( (s,i) => { return {value:parseInt(s), index:i}; })
273 .sort( (a,b) => { return b.value - a.value; });
48bee368 274 const ref_pdts = [4, 2, 1, 0];
1369a09d
BA
275 // NOTE: take care of ex-aequos (spread points subtotal)
276 let curSum = 0, curCount = 0, start = 0;
48bee368 277 let sortedPdts = [];
1369a09d 278 for (let i=0; i<4; i++)
7a00c409 279 {
48bee368 280 curSum += ref_pdts[i];
1369a09d
BA
281 curCount++;
282 if (i==3 || sortedSessions[i].value > sortedSessions[i+1].value)
283 {
284 let pdt = curSum / curCount;
285 for (let j=start; j<=i; j++)
48bee368 286 sortedPdts.push(pdt);
1369a09d
BA
287 curSum = 0;
288 curCount = 0;
289 start = i+1;
290 }
48bee368
BA
291 }
292 // Re-order pdts to match table order
293 let pdts = [0, 0, 0, 0];
294 for (let i=0; i<4; i++)
295 pdts[sortedSessions[i].index] = sortedPdts[i];
296 return pdts;
297 },
298 setScore: function() {
299 let pdts = this.getPdts();
300 for (let i=0; i<4; i++)
301 {
302 this.players[this.tables[this.currentIndex][i]].pdt += pdts[i];
1d2d7593 303 this.players[this.tables[this.currentIndex][i]].session += parseInt(this.sessions[this.currentIndex][i]);
7a00c409 304 }
48bee368 305 Vue.set(this.scored, this.currentIndex, true);
7a00c409 306 this.currentIndex = -1;
7a00c409 307 },
48bee368
BA
308 resetScore: function() {
309 let pdts = this.getPdts();
310 for (let i=0; i<4; i++)
311 {
312 this.players[this.tables[this.currentIndex][i]].pdt -= pdts[i];
313 this.players[this.tables[this.currentIndex][i]].session -= parseInt(this.sessions[this.currentIndex][i]);
314 }
315 Vue.set(this.scored, this.currentIndex, false);
6d7bb9ad 316 },
7a00c409
BA
317 },
318 },
2caa3889
BA
319 'my-timer': {
320 data: function() {
321 return {
322 time: 0, //remaining time, in seconds
323 running: false,
496ab82e
BA
324 initialTime: 90, //1h30, in minutes
325 setter: false,
326 setterTime: 0, //to input new initial time
2caa3889
BA
327 };
328 },
329 template: `
8d4d2300 330 <div id="timer" :style="{lineHeight: divHeight + 'px', fontSize: 0.66*divHeight + 'px', width: divWidth + 'px', height: divHeight + 'px'}">
496ab82e 331 <div v-show="!setter" @click.left="pauseResume()" @click.right.prevent="reset()" :class="{timeout:time==0}">
2caa3889
BA
332 {{ formattedTime }}
333 </div>
496ab82e 334 <input type="text" autofocus id="setter" @keyup.enter="setTime()" @keyup.esc="setter=false" v-show="setter" v-model="setterTime"></input>
2caa3889
BA
335 <img class="close-cross" src="img/cross.svg" @click="$emit('clockover')"/>
336 </div>
337 `,
338 computed: {
339 formattedTime: function() {
340 let seconds = this.time % 60;
341 let minutes = Math.floor(this.time / 60);
342 return this.padToZero(minutes) + ":" + this.padToZero(seconds);
343 },
8d4d2300 344 divHeight: function() {
6d7bb9ad
BA
345 return screen.height;
346 },
8d4d2300
BA
347 divWidth: function() {
348 return screen.width;
349 },
2caa3889
BA
350 },
351 methods: {
496ab82e
BA
352 setTime: function() {
353 this.initialTime = this.setterTime;
354 this.setter = false;
355 this.reset();
356 },
2caa3889
BA
357 padToZero: function(a) {
358 if (a < 10)
359 return "0" + a;
360 return a;
361 },
362 pauseResume: function() {
363 this.running = !this.running;
364 if (this.running)
365 this.start();
366 },
367 reset: function(e) {
368 this.running = false;
496ab82e 369 this.time = this.initialTime * 60;
2caa3889
BA
370 },
371 start: function() {
372 if (!this.running)
373 return;
374 if (this.time == 0)
375 {
376 new Audio("sounds/gong.mp3").play();
377 this.running = false;
378 return;
379 }
3480360c
BA
380 if (this.time == this.initialTime)
381 new Audio("sounds/gong.mp3").play(); //gong at the beginning
2caa3889
BA
382 setTimeout(() => {
383 if (this.running)
384 this.time--;
385 this.start();
386 }, 1000);
387 },
388 },
389 created: function() {
496ab82e 390 this.setterTime = this.initialTime;
2caa3889
BA
391 this.reset();
392 },
496ab82e
BA
393 mounted: function() {
394 let timer = document.getElementById("timer");
395 let keyDict = {
396 32: () => { this.setter = true; }, //Space
397 27: () => { this.setter = false; }, //Esc
398 };
399 document.addEventListener("keyup", e => {
400 if (timer.style.display !== "none")
401 {
402 let func = keyDict[e.keyCode];
403 if (!!func)
404 {
405 e.preventDefault();
406 func();
407 }
408 }
409 });
410 },
2caa3889 411 },
48b3a536 412 'my-ranking': {
48bee368 413 props: ['players','sortByScore','commitScores'],
48b3a536
BA
414 template: `
415 <div id="ranking">
416 <table class="ranking">
417 <tr class="title">
418 <th>Rang</th>
419 <th>Joueur</th>
420 <th>Points</th>
421 <th>Mini-pts</th>
422 </tr>
423 <tr v-for="p in sortedPlayers">
424 <td>{{ p.rank }}</td>
425 <td>{{ p.prenom }} {{ p.nom }}</td>
426 <td>{{ p.pdt }}</td>
427 <td>{{ p.session }}</td>
428 </tr>
429 </table>
430 <div class="button-container-vertical" style="width:200px">
48bee368
BA
431 <a id="download" href="#"></a>
432 <button class="btn" @click="download()" title="Télécharge le classement courant au format CSV">Télécharger</button>
433 <button class="btn cancel" @click="resetPlayers()" title="Réinitialise les scores à zéro. ATTENTION: action irréversible">
434 Réinitialiser
435 </button>
48b3a536
BA
436 </div>
437 </div>
438 `,
439 computed: {
440 sortedPlayers: function() {
441 let res = this.rankPeople();
442 // Add rank information (taking care of ex-aequos)
443 let rank = 1;
444 for (let i=0; i<res.length; i++)
445 {
446 if (i==0 || this.sortByScore(res[i],res[i-1]) == 0)
447 res[i].rank = rank;
448 else //strictly lower scoring
449 res[i].rank = ++rank;
450 }
451 return res;
452 },
453 },
454 methods: {
455 rankPeople: function() {
456 return this.players
457 .slice(1) //discard Toto
48b3a536
BA
458 .sort(this.sortByScore);
459 },
460 resetPlayers: function() {
48bee368
BA
461 if (confirm('Êtes-vous sûr ?'))
462 {
463 this.players
464 .slice(1) //discard Toto
465 .forEach( p => {
466 p.pdt = 0;
467 p.session = 0;
468 p.available = 1;
469 });
470 this.commitScores();
471 document.getElementById("doPairings").click();
472 }
473 },
474 download: function() {
475 // Prepare file content
476 let content = "prénom,nom,pdt,session\n";
48b3a536
BA
477 this.players
478 .slice(1) //discard Toto
48bee368 479 .sort(this.sortByScore)
48b3a536 480 .forEach( p => {
48bee368 481 content += p.prenom + "," + p.nom + "," + p.pdt + "," + p.session + "\n";
48b3a536 482 });
48bee368
BA
483 // Prepare and trigger download link
484 let downloadAnchor = document.getElementById("download");
485 downloadAnchor.setAttribute("download", "classement.csv");
486 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
487 downloadAnchor.click();
48b3a536
BA
488 },
489 },
490 },
7a00c409
BA
491 },
492 created: function() {
48bee368
BA
493 let players = JSON.parse(localStorage.getItem("players"));
494 if (players !== null)
495 {
496 this.addToto(players);
497 this.players = players;
498 }
7a00c409 499 },
ade10194 500 methods: {
48bee368
BA
501 addToto: function(array) {
502 array.unshift({ //add ghost 4th player for 3-players tables
503 prenom: "Toto",
504 nom: "",
505 pdt: 0,
506 session: 0,
507 available: 0,
508 });
509 },
1369a09d 510 // Used both in ranking and pairings:
ade10194
BA
511 sortByScore: function(a,b) {
512 return b.pdt - a.pdt + (Math.atan(b.session - a.session) / (Math.PI/2)) / 2;
513 },
48bee368
BA
514 commitScores: function() {
515 localStorage.setItem(
516 "players",
517 JSON.stringify(this.players.slice(1)) //discard Toto
518 );
519 },
520 // Used in players, reinit players array
521 initPlayers: function(csv) {
522 const allLines = csv
523 .split(/\r\n|\n|\r/) //line breaks
524 .splice(1); //discard header
525 let players = allLines
526 .filter( line => { return line.length > 0; }) //remove empty lines
527 .map( line => {
528 let parts = line.split(",");
d940eb68
BA
529 let p = { prenom: parts[0], nom: parts[1] };
530 p.pdt = parts.length > 2 ? parseFloat(parts[2]) : 0;
531 p.session = parts.length > 3 ? parseInt(parts[3]) : 0;
532 p.available = parts.length > 4 ? parts[4] : 1;
533 return p;
48bee368
BA
534 });
535 this.addToto(players);
536 this.players = players;
55043689 537 this.commitScores(); //save players in memory
1369a09d 538 },
ade10194 539 },
7a00c409 540});