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 score: "*", //'*' means 'unfinished'
14 mode: "idle", //human, computer or idle (when not playing)
15 oppid: "", //opponent ID in case of HH game
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))
32 const playingHuman
= (this.mode
== "human");
33 const playingComp
= (this.mode
== "computer");
39 if (this.mode
== "human")
40 return; //no newgame while playing
42 delete localStorage
["newgame"]; //cancel game seek
45 localStorage
["newgame"] = variant
;
46 this.newGame("human");
48 this.seek
= !this.seek
;
51 attrs: { "aria-label": 'New game VS human' },
55 "playing": playingHuman
,
58 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
63 if (this.mode
== "human")
64 return; //no newgame while playing
65 this.newGame("computer");
68 attrs: { "aria-label": 'New game VS computer' },
71 "playing": playingComp
,
74 [h('i', { 'class': { "material-icons": true } }, "computer")])
78 if (this.mode
== "human")
80 let connectedIndic
= h(
84 "connected": this.oppConnected
,
85 "disconnected": !this.oppConnected
,
89 elementArray
.push(connectedIndic
);
91 let choices
= h('div',
93 attrs: { "id": "choices" },
94 'class': { 'row': true },
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",
103 this.choices
.map( m
=> { //a "choice" is a move
106 'class': { 'board': true },
108 'width': (100/this.choices
.length
) + "%",
109 'padding-bottom': (100/this.choices
.length
) + "%",
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
=[]; } },
122 // Create board element (+ reserves if needed by variant or mode)
123 let gameDiv
= h('div',
125 'class': { 'game': true },
127 [_
.range(sizeX
).map(i
=> {
128 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
135 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
137 _
.range(sizeY
).map(j
=> {
138 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
140 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
148 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
151 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
157 if (hintSquares
[ci
][cj
])
167 src: "/images/mark.svg",
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
]);
182 'light-square': !highlight
&& (i
+j
)%2==0,
183 'dark-square': !highlight
&& (i
+j
)%2==1,
184 'highlight': highlight
,
188 id: this.getSquareId({x:ci
,y:cj
}),
200 on: { click: this.resign
},
201 attrs: { "aria-label": 'Resign' },
202 'class': { "tooltip":true },
204 [h('i', { 'class': { "material-icons": true } }, "flag")])
206 elementArray
.push(gameDiv
);
209 // let reserve = h('div',
210 // {'class':{'game':true}}, [
212 // { 'class': { 'row': true }},
215 // {'class':{'board':true}},
216 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
222 // elementArray.push(reserve);
224 let eogMessage
= "Unfinished";
228 eogMessage
= "White win";
231 eogMessage
= "Black win";
241 attrs: { "for": "modal-control" },
242 "class": { "modal-close": true },
247 "class": { "section": true },
248 domProps: { innerHTML: eogMessage
},
252 if (this.score
!= "*")
255 h('p', //'textarea', //TODO: selectable!
257 domProps: { innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
) },
258 //attrs: { "readonly": true },
266 attrs: { "id": "modal-control", type: "checkbox" },
267 "class": { "modal": true },
271 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
276 "class": { "card": true, "smallpad": true },
283 elementArray
= elementArray
.concat(modalEog
);
285 const modalNewgame
= [
288 attrs: { "id": "modal-control2", type: "checkbox" },
289 "class": { "modal": true },
293 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
298 "class": { "card": true, "smallpad": true },
303 attrs: { "id": "close-newgame", "for": "modal-control2" },
304 "class": { "modal-close": true },
309 "class": { "section": true },
310 domProps: { innerHTML: "New game" },
315 "class": { "section": true },
316 domProps: { innerHTML: "Waiting for opponent..." },
324 elementArray
= elementArray
.concat(modalNewgame
);
325 const actions
= h('div',
327 attrs: { "id": "actions" },
328 'class': { 'text-center': true },
332 elementArray
.push(actions
);
339 "col-md-offset-2":true,
341 "col-lg-offset-3":true,
343 // NOTE: click = mousedown + mouseup --> what about smartphone?!
345 mousedown: this.mousedown
,
346 mousemove: this.mousemove
,
347 mouseup: this.mouseup
,
348 touchdown: this.mousedown
,
349 touchmove: this.mousemove
,
350 touchup: this.mouseup
,
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
= () => {
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
}));
376 else if (localStorage
.getItem("newgame") === variant
)
378 // New game request has been cancelled on disconnect
380 this.newGame("human");
383 const socketMessageListener
= msg
=> {
384 const data
= JSON
.parse(msg
.data
);
387 case "newgame": //opponent found
388 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
390 case "newmove": //..he played!
391 this.play(data
.move, "animate");
393 case "pong": //sent when opponent stayed online after we disconnected
394 this.oppConnected
= true;
396 case "resign": //..you won!
397 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
399 // TODO: also use (dis)connect info to count online players
402 if (this.mode
== "human" && this.oppid
== data
.id
)
403 this.oppConnected
= (data
.code
== "connect");
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
);
414 this.conn
.onopen
= socketOpenListener
;
415 this.conn
.onmessage
= socketMessageListener
;
416 this.conn
.onclose
= socketCloseListener
;
419 endGame: function(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")
430 if (this.mode
== "human" && this.oppConnected
)
433 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
434 } catch (INVALID_STATE_ERR
) {
435 return; //resign failed for some reason...
438 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
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());
449 updateStorage: function() {
450 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
451 localStorage
.setItem("fen", this.vr
.getFen());
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"];
462 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
463 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
464 console
.log(fen
); //DEBUG
466 if (mode
=="human" && !oppId
)
468 // Send game request and wait..
469 this.clearStorage(); //in case of
471 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
472 } catch (INVALID_STATE_ERR
) {
473 return; //nothing achieved
475 let modalBox
= document
.getElementById("modal-control2");
476 modalBox
.checked
= true;
477 setTimeout(() => { modalBox
.checked
= false; }, 2000);
480 this.vr
= new VariantRules(fen
, moves
|| []);
482 this.fenStart
= continuation
483 ? localStorage
.getItem("fenStart")
484 : fen
.split(" ")[0]; //Only the position matters
490 // Playing sound fails on game continuation:
491 new Audio("/sounds/newgame.mp3").play();
492 document
.getElementById("modal-control2").checked
= false;
495 this.oppConnected
= true;
496 this.mycolor
= color
;
498 if (!!moves
&& moves
.length
> 0) //imply continuation
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");
506 delete localStorage
["newgame"];
507 this.setStorage(); //in case of interruptions
509 else //against computer
511 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
512 if (this.mycolor
== 'b')
513 setTimeout(this.playComputerMove
, 500);
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);
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
;
528 getSquareFromId: function(id
) {
529 let idParts
= id
.split('-');
530 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
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"))
537 // Next few lines to center the piece on mouse cursor
538 let rect
= e
.target
.parentNode
.getBoundingClientRect();
540 x: rect
.x
+ rect
.width
/2,
541 y: rect
.y
+ rect
.width
/2,
542 id: e
.target
.parentNode
.id
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
)
553 e
.target
.parentNode
.appendChild(this.selectedPiece
);
556 mousemove: function(e
) {
557 if (!this.selectedPiece
)
559 e
= e
|| window
.event
;
560 // If there is an active element, move it around
561 if (!!this.selectedPiece
)
563 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
564 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
567 mouseup: function(e
) {
568 if (!this.selectedPiece
)
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
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)
587 // Else: impossible move
588 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
589 delete this.selectedPiece
;
590 this.selectedPiece
= null;
592 findMatchingMoves: function(endSquare
) {
593 // Run through moves list and return the matching set (if promotions...)
595 this.possibleMoves
.forEach(function(m
) {
596 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
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
++)
613 let square
= squares
.item(i
);
614 if (square
.id
!= this.getSquareId(move.start
))
615 square
.style
.zIndex
= "-1";
617 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
618 movingPiece
.style
.transitionDuration
= "0.2s";
619 movingPiece
.style
.zIndex
= "3000";
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
627 play: function(move, programmatic
) {
628 if (!!programmatic
) //computer or human opponent
630 this.animateMove(move);
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
)
638 if (!this.oppConnected
)
639 return; //abort move if opponent is gone
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
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
);
653 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
654 setTimeout(this.playComputerMove
, 500);