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