save state
[westcastle.git] / js / index.js
1 new Vue({
2 el: "#mahjong",
3 data: {
4 players: [], //array of objects, filled later
5 display: "players",
6 },
7 components: {
8 'my-players': {
9 props: ['players','initPlayers'],
10 template: `
11 <div id="players">
12 <div class="left">
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>
21 <div id="inactive" class="right">
22 <p>Absents</p>
23 <table class="list">
24 <tr v-for="p in sortedPlayers" v-if="!p.available && p.nom!=''" @click="toggleAvailability(p.index)">
25 <td>{{ p.prenom }}</td>
26 <td>{{ p.nom }}</td>
27 </tr>
28 </table>
29 </div>
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>
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;
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);
61 },
62 },
63 },
64 'my-pairings': {
65 props: ['players','commitScores'],
66 data: function() {
67 return {
68 unpaired: [],
69 tables: [], //array of arrays of players indices
70 sessions: [], //"mini-points" for each table
71 currentIndex: -1, //table index for scoring
72 scored: [], //boolean for each table index
73 };
74 },
75 template: `
76 <div id="pairings">
77 <div v-show="currentIndex < 0">
78 <div class="button-container-horizontal">
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">
80 Valider
81 </button>
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">
83 Nouvelle ronde
84 </button>
85 </div>
86 <div class="pairing" v-for="(table,index) in tables" :class="{scored: scored[index]}"
87 @click="showScoreForm(table,index)">
88 <p>Table {{ index+1 }}</p>
89 <table>
90 <tr v-for="(i,j) in table">
91 <td :class="{toto: players[i].prenom=='Toto'}">{{ players[i].prenom }} {{ players[i].nom }}</td>
92 <td class="score"><span v-show="sessions[index].length > 0">{{ sessions[index][j] }}</span></td>
93 </tr>
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]">
106 <td :class="{toto: players[tables[currentIndex][i]].prenom=='Toto'}">
107 {{ players[tables[currentIndex][i]].prenom }} {{ players[tables[currentIndex][i]].nom }}
108 </td>
109 <td><input type="text" v-model="sessions[currentIndex][i]" :disabled="scored[currentIndex]"/></td>
110 </tr>
111 </table>
112 <div class="button-container-horizontal">
113 <button :class="{hide:scored[currentIndex]}" class="btn validate" @click="setScore()" title="Enregistre le score dans la base">
114 Enregistrer
115 </button>
116 <button :class="{hide:!scored[currentIndex]}" class="btn cancel" @click="resetScore()" title="Annule le score précédemment enregistré">
117 Annuler
118 </button>
119 <button class="btn" @click="closeScoreForm()">Fermer</button>
120 </div>
121 </div>
122 </div>
123 `,
124 methods: {
125 // TODO: télécharger la ronde courante
126 // TODO: mémoriser les appariements passés pour éviter que les mêmes joueurs se rencontrent plusieurs fois
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() {
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();
141 },
142 doPairings: function() {
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
214 // Simple case first: 4 by 4
215 let tables = [];
216 let currentTable = [];
217 let ordering = _.shuffle(_.range(this.players.length));
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 }
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 });
255 this.tables = tables;
256 this.sessions = tables.map( t => { return []; }); //empty sessions
257 this.scored = tables.map( t => { return false; }); //nothing scored yet
258 this.currentIndex = -1; //required if reset while scoring
259 },
260 showScoreForm: function(table,index) {
261 if (this.sessions[index].length == 0)
262 this.sessions[index] = _.times(table.length, _.constant(0));
263 this.currentIndex = index;
264 },
265 closeScoreForm: function() {
266 if (!this.scored[this.currentIndex])
267 this.sessions[this.currentIndex] = [];
268 this.currentIndex = -1;
269 },
270 getPdts: function() {
271 let sortedSessions = this.sessions[this.currentIndex]
272 .map( (s,i) => { return {value:parseInt(s), index:i}; })
273 .sort( (a,b) => { return b.value - a.value; });
274 const ref_pdts = [4, 2, 1, 0];
275 // NOTE: take care of ex-aequos (spread points subtotal)
276 let curSum = 0, curCount = 0, start = 0;
277 let sortedPdts = [];
278 for (let i=0; i<4; i++)
279 {
280 curSum += ref_pdts[i];
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++)
286 sortedPdts.push(pdt);
287 curSum = 0;
288 curCount = 0;
289 start = i+1;
290 }
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];
303 this.players[this.tables[this.currentIndex][i]].session += parseInt(this.sessions[this.currentIndex][i]);
304 }
305 Vue.set(this.scored, this.currentIndex, true);
306 this.currentIndex = -1;
307 },
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);
316 },
317 },
318 },
319 'my-timer': {
320 data: function() {
321 return {
322 time: 0, //remaining time, in seconds
323 running: false,
324 initialTime: 90, //1h30, in minutes
325 setter: false,
326 setterTime: 0, //to input new initial time
327 };
328 },
329 template: `
330 <div id="timer" :style="{lineHeight: divHeight + 'px', fontSize: 0.66*divHeight + 'px', width: divWidth + 'px', height: divHeight + 'px'}">
331 <div v-show="!setter" @click.left="pauseResume()" @click.right.prevent="reset()" :class="{timeout:time==0}">
332 {{ formattedTime }}
333 </div>
334 <input type="text" autofocus id="setter" @keyup.enter="setTime()" @keyup.esc="setter=false" v-show="setter" v-model="setterTime"></input>
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 },
344 divHeight: function() {
345 return screen.height;
346 },
347 divWidth: function() {
348 return screen.width;
349 },
350 },
351 methods: {
352 setTime: function() {
353 this.initialTime = this.setterTime;
354 this.setter = false;
355 this.reset();
356 },
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;
369 this.time = this.initialTime * 60;
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 }
380 if (this.time == this.initialTime)
381 new Audio("sounds/gong.mp3").play(); //gong at the beginning
382 setTimeout(() => {
383 if (this.running)
384 this.time--;
385 this.start();
386 }, 1000);
387 },
388 },
389 created: function() {
390 this.setterTime = this.initialTime;
391 this.reset();
392 },
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 },
411 },
412 'my-ranking': {
413 props: ['players','sortByScore','commitScores'],
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">
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>
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
458 .sort(this.sortByScore);
459 },
460 resetPlayers: function() {
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";
477 this.players
478 .slice(1) //discard Toto
479 .sort(this.sortByScore)
480 .forEach( p => {
481 content += p.prenom + "," + p.nom + "," + p.pdt + "," + p.session + "\n";
482 });
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();
488 },
489 },
490 },
491 },
492 created: function() {
493 let players = JSON.parse(localStorage.getItem("players"));
494 if (players !== null)
495 {
496 this.addToto(players);
497 this.players = players;
498 }
499 },
500 methods: {
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 },
510 // Used both in ranking and pairings:
511 sortByScore: function(a,b) {
512 return b.pdt - a.pdt + (Math.atan(b.session - a.session) / (Math.PI/2)) / 2;
513 },
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(",");
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;
534 });
535 this.addToto(players);
536 this.players = players;
537 this.commitScores(); //save players in memory
538 },
539 },
540 });