First draft of game balancing solution after reconnect
[vchess.git] / public / javascripts / components / game.js
1 // TODO: use indexedDB instead of localStorage? (more flexible: allow several games)
2
3 Vue.component('my-game', {
4 data: function() {
5 return {
6 vr: null, //object to check moves, store them, FEN..
7 mycolor: "w",
8 possibleMoves: [], //filled after each valid click/dragstart
9 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
10 start: {}, //pixels coordinates + id of starting square (click or drag)
11 selectedPiece: null, //moving piece (or clicked piece)
12 conn: null, //socket messages
13 score: "*", //'*' means 'unfinished'
14 mode: "idle", //human, computer or idle (when not playing)
15 oppid: "", //opponent ID in case of HH game
16 oppConnected: false,
17 seek: false,
18 fenStart: "",
19 incheck: [],
20 };
21 },
22 render(h) {
23 let [sizeX,sizeY] = VariantRules.size;
24 // Precompute hints squares to facilitate rendering
25 let hintSquares = doubleArray(sizeX, sizeY, false);
26 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
27 // Also precompute in-check squares
28 let incheckSq = doubleArray(sizeX, sizeY, false);
29 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
30 let elementArray = [];
31 let square00 = document.getElementById("sq-0-0");
32 let squareWidth = !!square00
33 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
34 : 0;
35 const playingHuman = (this.mode == "human");
36 const playingComp = (this.mode == "computer");
37 let actionArray = [
38 h('button',
39 {
40 on: {
41 click: () => {
42 if (this.mode == "human")
43 return; //no newgame while playing
44 if (this.seek)
45 delete localStorage["newgame"]; //cancel game seek
46 else
47 {
48 localStorage["newgame"] = variant;
49 this.newGame("human");
50 }
51 this.seek = !this.seek;
52 }
53 },
54 attrs: { "aria-label": 'New game VS human' },
55 'class': {
56 "tooltip": true,
57 "seek": this.seek,
58 "playing": playingHuman,
59 },
60 },
61 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
62 h('button',
63 {
64 on: {
65 click: () => {
66 if (this.mode == "human")
67 return; //no newgame while playing
68 this.newGame("computer");
69 }
70 },
71 attrs: { "aria-label": 'New game VS computer' },
72 'class': {
73 "tooltip":true,
74 "playing": playingComp,
75 },
76 },
77 [h('i', { 'class': { "material-icons": true } }, "computer")])
78 ];
79 if (!!this.vr)
80 {
81 if (this.mode == "human")
82 {
83 let connectedIndic = h(
84 'div',
85 {
86 "class": {
87 "connected": this.oppConnected,
88 "disconnected": !this.oppConnected,
89 },
90 }
91 );
92 elementArray.push(connectedIndic);
93 }
94 let choices = h('div',
95 {
96 attrs: { "id": "choices" },
97 'class': { 'row': true },
98 style: {
99 //"position": "relative",
100 "display": this.choices.length>0?"block":"none",
101 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
102 "width": (this.choices.length * squareWidth) + "px",
103 "height": squareWidth + "px",
104 },
105 },
106 this.choices.map( m => { //a "choice" is a move
107 return h('div',
108 {
109 'class': { 'board': true },
110 style: {
111 'width': (100/this.choices.length) + "%",
112 'padding-bottom': (100/this.choices.length) + "%",
113 },
114 },
115 [h('img',
116 {
117 attrs: { "src": '/images/pieces/' + VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
118 'class': { 'choice-piece': true, 'board': true },
119 on: { "click": e => { this.play(m); this.choices=[]; } },
120 })
121 ]
122 );
123 })
124 );
125 // Create board element (+ reserves if needed by variant or mode)
126 let gameDiv = h('div',
127 {
128 'class': { 'game': true },
129 },
130 [_.range(sizeX).map(i => {
131 let ci = this.mycolor=='w' ? i : sizeX-i-1;
132 return h(
133 'div',
134 {
135 'class': {
136 'row': true,
137 },
138 style: { 'opacity': this.choices.length>0?"0.5":"1" },
139 },
140 _.range(sizeY).map(j => {
141 let cj = this.mycolor=='w' ? j : sizeY-j-1;
142 let elems = [];
143 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
144 {
145 elems.push(
146 h(
147 'img',
148 {
149 'class': {
150 'piece': true,
151 'ghost': !!this.selectedPiece && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
152 },
153 attrs: {
154 src: "/images/pieces/" + VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
155 },
156 }
157 )
158 );
159 }
160 if (hintSquares[ci][cj])
161 {
162 elems.push(
163 h(
164 'img',
165 {
166 'class': {
167 'mark-square': true,
168 },
169 attrs: {
170 src: "/images/mark.svg",
171 },
172 }
173 )
174 );
175 }
176 const lm = this.vr.lastMove;
177 const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
178 return h(
179 'div',
180 {
181 'class': {
182 'board': true,
183 'light-square': !highlight && (i+j)%2==0,
184 'dark-square': !highlight && (i+j)%2==1,
185 'highlight': highlight,
186 'incheck': incheckSq[ci][cj],
187 },
188 attrs: {
189 id: this.getSquareId({x:ci,y:cj}),
190 },
191 },
192 elems
193 );
194 })
195 );
196 }), choices]
197 );
198 actionArray.push(
199 h('button',
200 {
201 on: { click: this.resign },
202 attrs: { "aria-label": 'Resign' },
203 'class': { "tooltip":true },
204 },
205 [h('i', { 'class': { "material-icons": true } }, "flag")])
206 );
207 elementArray.push(gameDiv);
208 // if (!!vr.reserve)
209 // {
210 // let reserve = h('div',
211 // {'class':{'game':true}}, [
212 // h('div',
213 // { 'class': { 'row': true }},
214 // [
215 // h('div',
216 // {'class':{'board':true}},
217 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
218 // )
219 // ]
220 // )
221 // ],
222 // );
223 // elementArray.push(reserve);
224 // }
225 let eogMessage = "Unfinished";
226 switch (this.score)
227 {
228 case "1-0":
229 eogMessage = "White win";
230 break;
231 case "0-1":
232 eogMessage = "Black win";
233 break;
234 case "1/2":
235 eogMessage = "Draw";
236 break;
237 }
238 let elemsOfEog =
239 [
240 h('label',
241 {
242 attrs: { "for": "modal-control" },
243 "class": { "modal-close": true },
244 }
245 ),
246 h('h3',
247 {
248 "class": { "section": true },
249 domProps: { innerHTML: eogMessage },
250 }
251 )
252 ];
253 if (this.score != "*")
254 {
255 elemsOfEog.push(
256 h('p', //'textarea', //TODO: selectable!
257 {
258 domProps: { innerHTML: this.vr.getPGN(this.mycolor, this.score, this.fenStart) },
259 //attrs: { "readonly": true },
260 }
261 )
262 );
263 }
264 const modalEog = [
265 h('input',
266 {
267 attrs: { "id": "modal-control", type: "checkbox" },
268 "class": { "modal": true },
269 }),
270 h('div',
271 {
272 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
273 },
274 [
275 h('div',
276 {
277 "class": { "card": true, "smallpad": true },
278 },
279 elemsOfEog
280 )
281 ]
282 )
283 ];
284 elementArray = elementArray.concat(modalEog);
285 }
286 const modalNewgame = [
287 h('input',
288 {
289 attrs: { "id": "modal-control2", type: "checkbox" },
290 "class": { "modal": true },
291 }),
292 h('div',
293 {
294 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
295 },
296 [
297 h('div',
298 {
299 "class": { "card": true, "smallpad": true },
300 },
301 [
302 h('label',
303 {
304 attrs: { "id": "close-newgame", "for": "modal-control2" },
305 "class": { "modal-close": true },
306 }
307 ),
308 h('h3',
309 {
310 "class": { "section": true },
311 domProps: { innerHTML: "New game" },
312 }
313 ),
314 h('p',
315 {
316 "class": { "section": true },
317 domProps: { innerHTML: "Waiting for opponent..." },
318 }
319 )
320 ]
321 )
322 ]
323 )
324 ];
325 elementArray = elementArray.concat(modalNewgame);
326 const actions = h('div',
327 {
328 attrs: { "id": "actions" },
329 'class': { 'text-center': true },
330 },
331 actionArray
332 );
333 elementArray.push(actions);
334 return h(
335 'div',
336 {
337 'class': {
338 "col-sm-12":true,
339 "col-md-8":true,
340 "col-md-offset-2":true,
341 "col-lg-6":true,
342 "col-lg-offset-3":true,
343 },
344 // NOTE: click = mousedown + mouseup --> what about smartphone?!
345 on: {
346 mousedown: this.mousedown,
347 mousemove: this.mousemove,
348 mouseup: this.mouseup,
349 touchdown: this.mousedown,
350 touchmove: this.mousemove,
351 touchup: this.mouseup,
352 },
353 },
354 elementArray
355 );
356 },
357 created: function() {
358 const url = socketUrl;
359 const continuation = (localStorage.getItem("variant") === variant);
360 this.myid = continuation
361 ? localStorage.getItem("myid")
362 // random enough (TODO: function)
363 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
364 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
365 const socketOpenListener = () => {
366 if (continuation)
367 {
368 const fen = localStorage.getItem("fen");
369 const mycolor = localStorage.getItem("mycolor");
370 const oppid = localStorage.getItem("oppid");
371 const moves = JSON.parse(localStorage.getItem("moves"));
372 this.newGame("human", fen, mycolor, oppid, moves, true);
373 // Send ping to server (answer pong if opponent is connected)
374 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppId}));
375 }
376 else if (localStorage.getItem("newgame") === variant)
377 {
378 // New game request has been cancelled on disconnect
379 this.seek = true;
380 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
381 }
382 };
383 const socketMessageListener = msg => {
384 const data = JSON.parse(msg.data);
385 switch (data.code)
386 {
387 case "newgame": //opponent found
388 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
389 break;
390 case "newmove": //..he played!
391 this.play(data.move, "animate");
392 break;
393 case "pong": //received if opponent sent a ping
394 this.oppConnected = true;
395 const L = this.vr.moves.length;
396 // Send our "last state" informations to opponent (we are still playing)
397 this.conn.send(JSON.stringify({
398 code:"lastate",
399 oppid:this.oppId,
400 lastMove:L>0?this.vr.moves[L-1]:undefined,
401 movesCount:L,
402 }));
403 break;
404 case "lastate": //got opponent infos about last move (we might have resigned)
405 if (this.mode!="human" || this.oppid!=data.oppid)
406 {
407 // OK, we resigned
408 this.conn.send(JSON.stringify({
409 code:"lastate",
410 oppid:this.oppId,
411 lastMove:undefined,
412 movesCount:-1,
413 }));
414 }
415 else if (data.movesCount < 0)
416 {
417 // OK, he resigned
418 this.endGame(this.mycolor=="w"?"1-0":"0-1");
419 }
420 else if (data.movesCount < this.vr.moves.length)
421 {
422 // We must tell last move to opponent
423 const L = this.vr.moves.length;
424 this.conn.send(JSON.stringify({
425 code:"lastate",
426 oppid:this.oppId,
427 lastMove:this.vr.moves[L-1],
428 movesCount:L,
429 }));
430 }
431 else if (data.movesCount > this.vr.moves.length) //just got last move from him
432 this.play(data.lastMove, "animate");
433 case "resign": //..you won!
434 this.endGame(this.mycolor=="w"?"1-0":"0-1");
435 break;
436 // TODO: also use (dis)connect info to count online players
437 case "connect":
438 case "disconnect":
439 if (this.mode == "human" && this.oppid == data.id)
440 this.oppConnected = (data.code == "connect");
441 break;
442 }
443 };
444 const socketCloseListener = () => {
445 console.log("Lost connection -- reconnect");
446 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
447 this.conn.addEventListener('open', socketOpenListener);
448 this.conn.addEventListener('message', socketMessageListener);
449 this.conn.addEventListener('close', socketCloseListener);
450 };
451 this.conn.onopen = socketOpenListener;
452 this.conn.onmessage = socketMessageListener;
453 this.conn.onclose = socketCloseListener;
454 },
455 methods: {
456 endGame: function(score) {
457 this.score = score;
458 let modalBox = document.getElementById("modal-control");
459 modalBox.checked = true;
460 //setTimeout(() => { modalBox.checked = false; }, 2000); //disabled, to show PGN
461 if (this.mode == "human")
462 this.clearStorage();
463 this.mode = "idle";
464 this.oppid = "";
465 },
466 resign: function() {
467 if (this.mode == "human" && this.oppConnected)
468 {
469 try {
470 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
471 } catch (INVALID_STATE_ERR) {
472 return; //socket is not ready (and not yet reconnected)
473 }
474 }
475 this.endGame(this.mycolor=="w"?"0-1":"1-0");
476 },
477 setStorage: function() {
478 localStorage.setItem("myid", this.myid);
479 localStorage.setItem("variant", variant);
480 localStorage.setItem("mycolor", this.mycolor);
481 localStorage.setItem("oppid", this.oppid);
482 localStorage.setItem("fenStart", this.fenStart);
483 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
484 localStorage.setItem("fen", this.vr.getFen());
485 },
486 updateStorage: function() {
487 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
488 localStorage.setItem("fen", this.vr.getFen());
489 },
490 clearStorage: function() {
491 delete localStorage["variant"];
492 delete localStorage["myid"];
493 delete localStorage["mycolor"];
494 delete localStorage["oppid"];
495 delete localStorage["fenStart"];
496 delete localStorage["fen"];
497 delete localStorage["moves"];
498 },
499 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
500 const fen = fenInit || VariantRules.GenRandInitFen();
501 console.log(fen); //DEBUG
502 this.score = "*";
503 if (mode=="human" && !oppId)
504 {
505 const storageVariant = localStorage.getItem("variant");
506 if (!!storageVariant && storageVariant !== variant)
507 {
508 // TODO: find a better way to ensure this. Newgame system is currently a mess.
509 alert("Finish your " + storageVariant + " game first!");
510 return;
511 }
512 // Send game request and wait..
513 this.clearStorage(); //in case of
514 try {
515 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
516 } catch (INVALID_STATE_ERR) {
517 return; //nothing achieved
518 }
519 if (continuation == "reconnect") //TODO: bad HACK...
520 {
521 let modalBox = document.getElementById("modal-control2");
522 modalBox.checked = true;
523 setTimeout(() => { modalBox.checked = false; }, 2000);
524 }
525 return;
526 }
527 this.vr = new VariantRules(fen, moves || []);
528 this.mode = mode;
529 this.incheck = []; //in case of
530 this.fenStart = continuation
531 ? localStorage.getItem("fenStart")
532 : fen.split(" ")[0]; //Only the position matters
533 if (mode=="human")
534 {
535 // Opponent found!
536 if (!continuation)
537 {
538 // Playing sound fails on game continuation:
539 new Audio("/sounds/newgame.mp3").play();
540 document.getElementById("modal-control2").checked = false;
541 }
542 this.oppid = oppId;
543 this.oppConnected = true;
544 this.mycolor = color;
545 this.seek = false;
546 if (!!moves && moves.length > 0) //imply continuation
547 {
548 const oppCol = this.vr.turn;
549 const lastMove = moves[moves.length-1];
550 this.vr.undo(lastMove, "ingame");
551 this.incheck = this.vr.getCheckSquares(lastMove, oppCol);
552 this.vr.play(lastMove, "ingame");
553 }
554 delete localStorage["newgame"];
555 this.setStorage(); //in case of interruptions
556 }
557 else //against computer
558 {
559 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
560 if (this.mycolor == 'b')
561 setTimeout(this.playComputerMove, 500);
562 }
563 },
564 playComputerMove: function() {
565 const compColor = this.mycolor=='w' ? 'b' : 'w';
566 const compMove = this.vr.getComputerMove(compColor);
567 // HACK: avoid selecting elements before they appear on page:
568 setTimeout(() => this.play(compMove, "animate"), 500);
569 },
570 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
571 getSquareId: function(o) {
572 // NOTE: a separator is required to allow any size of board
573 return "sq-" + o.x + "-" + o.y;
574 },
575 // Inverse function
576 getSquareFromId: function(id) {
577 let idParts = id.split('-');
578 return [parseInt(idParts[1]), parseInt(idParts[2])];
579 },
580 mousedown: function(e) {
581 e = e || window.event;
582 e.preventDefault(); //disable native drag & drop
583 if (!this.selectedPiece && e.target.classList.contains("piece"))
584 {
585 // Next few lines to center the piece on mouse cursor
586 let rect = e.target.parentNode.getBoundingClientRect();
587 this.start = {
588 x: rect.x + rect.width/2,
589 y: rect.y + rect.width/2,
590 id: e.target.parentNode.id
591 };
592 this.selectedPiece = e.target.cloneNode();
593 this.selectedPiece.style.position = "absolute";
594 this.selectedPiece.style.top = 0;
595 this.selectedPiece.style.display = "inline-block";
596 this.selectedPiece.style.zIndex = 3000;
597 let startSquare = this.getSquareFromId(e.target.parentNode.id);
598 this.possibleMoves = this.vr.canIplay(this.mycolor,startSquare)
599 ? this.vr.getPossibleMovesFrom(startSquare)
600 : [];
601 e.target.parentNode.appendChild(this.selectedPiece);
602 }
603 },
604 mousemove: function(e) {
605 if (!this.selectedPiece)
606 return;
607 e = e || window.event;
608 // If there is an active element, move it around
609 if (!!this.selectedPiece)
610 {
611 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
612 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
613 }
614 },
615 mouseup: function(e) {
616 if (!this.selectedPiece)
617 return;
618 e = e || window.event;
619 // Read drop target (or parentElement, parentNode... if type == "img")
620 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
621 let landing = document.elementFromPoint(e.clientX, e.clientY);
622 this.selectedPiece.style.zIndex = 3000;
623 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
624 landing = landing.parentNode;
625 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
626 return;
627 // OK: process move attempt
628 let endSquare = this.getSquareFromId(landing.id);
629 let moves = this.findMatchingMoves(endSquare);
630 this.possibleMoves = [];
631 if (moves.length > 1)
632 this.choices = moves;
633 else if (moves.length==1)
634 this.play(moves[0]);
635 // Else: impossible move
636 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
637 delete this.selectedPiece;
638 this.selectedPiece = null;
639 },
640 findMatchingMoves: function(endSquare) {
641 // Run through moves list and return the matching set (if promotions...)
642 let moves = [];
643 this.possibleMoves.forEach(function(m) {
644 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
645 moves.push(m);
646 });
647 return moves;
648 },
649 animateMove: function(move) {
650 let startSquare = document.getElementById(this.getSquareId(move.start));
651 let endSquare = document.getElementById(this.getSquareId(move.end));
652 let rectStart = startSquare.getBoundingClientRect();
653 let rectEnd = endSquare.getBoundingClientRect();
654 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
655 let movingPiece = document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
656 // HACK for animation (otherwise with positive translate, image slides "under background"...)
657 // Possible improvement: just alter squares on the piece's way...
658 squares = document.getElementsByClassName("board");
659 for (let i=0; i<squares.length; i++)
660 {
661 let square = squares.item(i);
662 if (square.id != this.getSquareId(move.start))
663 square.style.zIndex = "-1";
664 }
665 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
666 movingPiece.style.transitionDuration = "0.2s";
667 movingPiece.style.zIndex = "3000";
668 setTimeout( () => {
669 for (let i=0; i<squares.length; i++)
670 squares.item(i).style.zIndex = "auto";
671 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
672 this.play(move);
673 }, 200);
674 },
675 play: function(move, programmatic) {
676 if (!!programmatic) //computer or human opponent
677 {
678 this.animateMove(move);
679 return;
680 }
681 const oppCol = this.vr.getOppCol(this.vr.turn);
682 this.incheck = this.vr.getCheckSquares(move, oppCol); //is opponent in check?
683 // Not programmatic, or animation is over
684 if (this.mode == "human" && this.vr.turn == this.mycolor)
685 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
686 new Audio("/sounds/chessmove1.mp3").play();
687 this.vr.play(move, "ingame");
688 if (this.mode == "human")
689 this.updateStorage(); //after our moves and opponent moves
690 const eog = this.vr.checkGameOver(this.vr.turn);
691 if (eog != "*")
692 this.endGame(eog);
693 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
694 setTimeout(this.playComputerMove, 500);
695 },
696 },
697 })