1 // TODO: use indexedDB instead of localStorage: more flexible.
3 Vue
.component('my-game', {
6 vr: null, //object to check moves, store them, FEN..
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
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))
34 if (localStorage
.getItem("newgame") === variant
)
35 delete localStorage
["newgame"]; //cancel game seek
38 localStorage
["newgame"] = variant
;
39 this.newGame("human");
43 attrs: { "aria-label": 'New game VS human' },
44 'class': { "tooltip":true },
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
49 on: { click: () => this.newGame("computer") },
50 attrs: { "aria-label": 'New game VS computer' },
51 'class': { "tooltip":true },
53 [h('i', { 'class': { "material-icons": true } }, "computer")])
57 if (this.mode
== "human")
59 let connectedIndic
= h(
63 "connected": this.oppConnected
,
64 "disconnected": !this.oppConnected
,
68 elementArray
.push(connectedIndic
);
70 let choices
= h('div',
72 attrs: { "id": "choices" },
73 'class': { 'row': true },
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",
82 this.choices
.map( m
=> { //a "choice" is a move
85 'class': { 'board': true },
87 'width': (100/this.choices
.length
) + "%",
88 'padding-bottom': (100/this.choices
.length
) + "%",
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
=[]; } },
101 // Create board element (+ reserves if needed by variant or mode)
102 let gameDiv
= h('div',
104 'class': { 'game': true },
106 [_
.range(sizeX
).map(i
=> {
107 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
114 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
116 _
.range(sizeY
).map(j
=> {
117 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
119 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
127 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
130 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
136 if (hintSquares
[ci
][cj
])
146 src: "/images/mark.svg",
152 const lm
= this.vr
.lastMove
;
153 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}); //&& _.isMatch(lm.start, {x:ci,y:cj})
159 'light-square': !highlight
&& (i
+j
)%2==0,
160 'dark-square': !highlight
&& (i
+j
)%2==1,
161 'highlight': highlight
,
164 id: this.getSquareId({x:ci
,y:cj
}),
176 on: { click: this.resign
},
177 attrs: { "aria-label": 'Resign' },
178 'class': { "tooltip":true },
180 [h('i', { 'class': { "material-icons": true } }, "flag")])
182 elementArray
.push(gameDiv
);
185 // let reserve = h('div',
186 // {'class':{'game':true}}, [
188 // { 'class': { 'row': true }},
191 // {'class':{'board':true}},
192 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
198 // elementArray.push(reserve);
203 attrs: { "id": "modal-control", type: "checkbox" },
204 "class": { "modal": true },
208 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
213 "class": { "card": true, "smallpad": true },
218 attrs: { "for": "modal-control" },
219 "class": { "modal-close": true },
224 "class": { "section": true },
225 domProps: { innerHTML: "End of game" },
230 "class": { "section": true },
231 domProps: { innerHTML: this.endofgame
},
239 elementArray
= elementArray
.concat(modalEog
);
241 const modalNewgame
= [
244 attrs: { "id": "modal-control2", type: "checkbox" },
245 "class": { "modal": true },
249 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
254 "class": { "card": true, "smallpad": true },
259 attrs: { "id": "close-newgame", "for": "modal-control2" },
260 "class": { "modal-close": true },
265 "class": { "section": true },
266 domProps: { innerHTML: "New game" },
271 "class": { "section": true },
272 domProps: { innerHTML: "Waiting for opponent..." },
280 elementArray
= elementArray
.concat(modalNewgame
);
281 const actions
= h('div',
283 attrs: { "id": "actions" },
284 'class': { 'text-center': true },
288 elementArray
.push(actions
);
295 "col-md-offset-2":true,
297 "col-lg-offset-3":true,
299 // NOTE: click = mousedown + mouseup --> what about smartphone?!
301 mousedown: this.mousedown
,
302 mousemove: this.mousemove
,
303 mouseup: this.mouseup
,
304 touchdown: this.mousedown
,
305 touchmove: this.mousemove
,
306 touchup: this.mouseup
,
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
= () => {
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
}));
329 else if (localStorage
.getItem("newgame") === variant
)
331 // New game request has been cancelled on disconnect
332 this.newGame("human");
335 const socketMessageListener
= msg
=> {
336 const data
= JSON
.parse(msg
.data
);
339 case "newgame": //opponent found
340 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
342 case "newmove": //..he played!
343 this.play(data
.move, "animate");
345 case "pong": //sent when opponent stayed online after we disconnected
346 this.oppConnected
= true;
348 case "resign": //..you won!
349 this.endGame("Victory!");
351 // TODO: also use (dis)connect info to count online players
354 if (this.mode
== "human" && this.oppid
== data
.id
)
355 this.oppConnected
= (data
.code
== "connect");
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
);
366 this.conn
.onopen
= socketOpenListener
;
367 this.conn
.onmessage
= socketMessageListener
;
368 this.conn
.onclose
= socketCloseListener
;
371 endGame: function(message
) {
372 this.endofgame
= message
;
373 document
.getElementById("modal-control").checked
= true;
374 if (this.mode
== "human")
380 if (this.mode
== "human" && this.oppConnected
)
383 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
384 } catch (INVALID_STATE_ERR
) {
385 return; //resign failed for some reason...
388 this.endGame("Try again!");
390 updateStorage: function() {
391 if (!localStorage
.getItem("myid"))
393 localStorage
.setItem("myid", this.myid
);
394 localStorage
.setItem("variant", variant
);
395 localStorage
.setItem("mycolor", this.mycolor
);
396 localStorage
.setItem("oppid", this.oppid
);
398 localStorage
.setItem("fen", this.vr
.getFen());
400 clearStorage: function() {
401 delete localStorage
["variant"];
402 delete localStorage
["myid"];
403 delete localStorage
["mycolor"];
404 delete localStorage
["oppid"];
405 delete localStorage
["fen"];
407 newGame: function(mode
, fenInit
, color
, oppId
, continuation
) {
408 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
409 console
.log(fen
); //DEBUG
410 if (mode
=="human" && !oppId
)
412 // Send game request and wait..
413 this.clearStorage(); //in case of
415 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
416 } catch (INVALID_STATE_ERR
) {
417 return; //nothing achieved
419 document
.getElementById("modal-control2").checked
= true;
422 this.vr
= new VariantRules(fen
);
429 // Playing sound fails on game continuation:
430 new Audio("/sounds/newgame.mp3").play();
431 document
.getElementById("modal-control2").checked
= false;
434 this.oppConnected
= true;
435 this.mycolor
= color
;
436 delete localStorage
["newgame"]; //in case of
438 else //against computer
440 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
441 if (this.mycolor
== 'b')
442 setTimeout(this.playComputerMove
, 500);
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);
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
;
457 getSquareFromId: function(id
) {
458 let idParts
= id
.split('-');
459 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
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"))
466 // Next few lines to center the piece on mouse cursor
467 let rect
= e
.target
.parentNode
.getBoundingClientRect();
469 x: rect
.x
+ rect
.width
/2,
470 y: rect
.y
+ rect
.width
/2,
471 id: e
.target
.parentNode
.id
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
)
482 e
.target
.parentNode
.appendChild(this.selectedPiece
);
485 mousemove: function(e
) {
486 if (!this.selectedPiece
)
488 e
= e
|| window
.event
;
489 // If there is an active element, move it around
490 if (!!this.selectedPiece
)
492 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
493 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
496 mouseup: function(e
) {
497 if (!this.selectedPiece
)
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
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)
516 // Else: impossible move
517 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
518 delete this.selectedPiece
;
519 this.selectedPiece
= null;
521 findMatchingMoves: function(endSquare
) {
522 // Run through moves list and return the matching set (if promotions...)
524 this.possibleMoves
.forEach(function(m
) {
525 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
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
++)
542 let square
= squares
.item(i
);
543 if (square
.id
!= this.getSquareId(move.start
))
544 square
.style
.zIndex
= "-1";
546 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
547 movingPiece
.style
.transitionDuration
= "0.2s";
548 movingPiece
.style
.zIndex
= "3000";
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
556 play: function(move, programmatic
) {
557 if (!!programmatic
) //computer or human opponent
559 this.animateMove(move);
562 // Not programmatic, or animation is over
563 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
565 if (!this.oppConnected
)
566 return; //abort move if opponent is gone
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
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
);
580 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
581 setTimeout(this.playComputerMove
, 500);