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