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