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