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