30ed7e0b910606fa64755b7ff64b7e5ef13e2fab
1 // TODO: use indexedDB instead of localStorage? (more flexible: allow several games)
2 Vue
.component('my-game', {
5 vr: null, //object to check moves, store them, FEN..
7 possibleMoves: [], //filled after each valid click/dragstart
8 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket messages
12 score: "*", //'*' means 'unfinished'
13 mode: "idle", //human, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
22 let [sizeX
,sizeY
] = VariantRules
.size
;
23 // Precompute hints squares to facilitate rendering
24 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
25 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
26 // Also precompute in-check squares
27 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
28 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
29 let elementArray
= [];
30 let square00
= document
.getElementById("sq-0-0");
31 let squareWidth
= !!square00
32 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
34 const playingHuman
= (this.mode
== "human");
35 const playingComp
= (this.mode
== "computer");
39 on: { click: this.clickGameSeek
},
40 attrs: { "aria-label": 'New game VS human' },
43 "bottom": true, //display below
45 "playing": playingHuman
,
48 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
51 on: { click: this.clickComputerGame
},
52 attrs: { "aria-label": 'New game VS computer' },
56 "playing": playingComp
,
59 [h('i', { 'class': { "material-icons": true } }, "computer")])
63 if (this.mode
== "human")
65 let connectedIndic
= h(
69 "connected": this.oppConnected
,
70 "disconnected": !this.oppConnected
,
74 elementArray
.push(connectedIndic
);
76 let choices
= h('div',
78 attrs: { "id": "choices" },
79 'class': { 'row': true },
81 //"position": "relative",
82 "display": this.choices
.length
>0?"block":"none",
83 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
84 "width": (this.choices
.length
* squareWidth
) + "px",
85 "height": squareWidth
+ "px",
88 this.choices
.map( m
=> { //a "choice" is a move
91 'class': { 'board': true },
93 'width': (100/this.choices
.length
) + "%",
94 'padding-bottom': (100/this.choices
.length
) + "%",
99 attrs: { "src": '/images/pieces/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
100 'class': { 'choice-piece': true, 'board': true },
101 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
107 // Create board element (+ reserves if needed by variant or mode)
108 let gameDiv
= h('div',
110 'class': { 'game': true },
112 [_
.range(sizeX
).map(i
=> {
113 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
120 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
122 _
.range(sizeY
).map(j
=> {
123 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
125 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
133 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
136 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
142 if (hintSquares
[ci
][cj
])
152 src: "/images/mark.svg",
158 const lm
= this.vr
.lastMove
;
159 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
165 'light-square': !highlight
&& (i
+j
)%2==0,
166 'dark-square': !highlight
&& (i
+j
)%2==1,
167 'highlight': highlight
,
168 'incheck': incheckSq
[ci
][cj
],
171 id: this.getSquareId({x:ci
,y:cj
}),
183 on: { click: this.resign
},
184 attrs: { "aria-label": 'Resign' },
190 [h('i', { 'class': { "material-icons": true } }, "flag")])
192 elementArray
.push(gameDiv
);
195 // let reserve = h('div',
196 // {'class':{'game':true}}, [
198 // { 'class': { 'row': true }},
201 // {'class':{'board':true}},
202 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
208 // elementArray.push(reserve);
210 const eogMessage
= this.getEndgameMessage(this.score
);
214 attrs: { "id": "modal-eog", type: "checkbox" },
215 "class": { "modal": true },
219 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
224 "class": { "card": true, "smallpad": true },
229 attrs: { "for": "modal-eog" },
230 "class": { "modal-close": true },
235 "class": { "section": true },
236 domProps: { innerHTML: eogMessage
},
244 elementArray
= elementArray
.concat(modalEog
);
246 const modalNewgame
= [
249 attrs: { "id": "modal-newgame", type: "checkbox" },
250 "class": { "modal": true },
254 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
259 "class": { "card": true, "smallpad": true },
264 attrs: { "id": "close-newgame", "for": "modal-newgame" },
265 "class": { "modal-close": true },
270 "class": { "section": true },
271 domProps: { innerHTML: "New game" },
276 "class": { "section": true },
277 domProps: { innerHTML: "Waiting for opponent..." },
285 elementArray
= elementArray
.concat(modalNewgame
);
286 const actions
= h('div',
288 attrs: { "id": "actions" },
289 'class': { 'text-center': true },
293 elementArray
.push(actions
);
294 if (this.score
!= "*")
303 innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
)
317 "col-md-offset-2":true,
319 "col-lg-offset-3":true,
321 // NOTE: click = mousedown + mouseup --> what about smartphone?!
323 mousedown: this.mousedown
,
324 mousemove: this.mousemove
,
325 mouseup: this.mouseup
,
326 touchdown: this.mousedown
,
327 touchmove: this.mousemove
,
328 touchup: this.mouseup
,
334 created: function() {
335 const url
= socketUrl
;
336 const continuation
= (localStorage
.getItem("variant") === variant
);
337 this.myid
= continuation
338 ? localStorage
.getItem("myid")
339 // random enough (TODO: function)
340 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
341 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
342 const socketOpenListener
= () => {
345 const fen
= localStorage
.getItem("fen");
346 const mycolor
= localStorage
.getItem("mycolor");
347 const oppid
= localStorage
.getItem("oppid");
348 const moves
= JSON
.parse(localStorage
.getItem("moves"));
349 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
350 // Send ping to server (answer pong if opponent is connected)
351 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
353 else if (localStorage
.getItem("newgame") === variant
)
355 // New game request has been cancelled on disconnect
357 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
360 const socketMessageListener
= msg
=> {
361 const data
= JSON
.parse(msg
.data
);
362 console
.log("Receive message: " + data
.code
);
365 case "newgame": //opponent found
366 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
368 case "newmove": //..he played!
369 this.play(data
.move, "animate");
371 case "pong": //received if we sent a ping (game still alive on our side)
372 this.oppConnected
= true;
373 const L
= this.vr
.moves
.length
;
374 // Send our "last state" informations to opponent
375 this.conn
.send(JSON
.stringify({
378 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
382 case "lastate": //got opponent infos about last move (we might have resigned)
383 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
386 this.conn
.send(JSON
.stringify({
393 else if (data
.movesCount
< 0)
396 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
398 else if (data
.movesCount
< this.vr
.moves
.length
)
400 // We must tell last move to opponent
401 const L
= this.vr
.moves
.length
;
402 this.conn
.send(JSON
.stringify({
405 lastMove:this.vr
.moves
[L
-1],
409 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
410 this.play(data
.lastMove
, "animate");
412 case "resign": //..you won!
413 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
415 // TODO: also use (dis)connect info to count online players?
418 if (this.mode
== "human" && this.oppid
== data
.id
)
419 this.oppConnected
= (data
.code
== "connect");
423 const socketCloseListener
= () => {
424 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
425 this.conn
.addEventListener('open', socketOpenListener
);
426 this.conn
.addEventListener('message', socketMessageListener
);
427 this.conn
.addEventListener('close', socketCloseListener
);
429 this.conn
.onopen
= socketOpenListener
;
430 this.conn
.onmessage
= socketMessageListener
;
431 this.conn
.onclose
= socketCloseListener
;
434 endGame: function(score
) {
436 let modalBox
= document
.getElementById("modal-eog");
437 modalBox
.checked
= true;
438 setTimeout(() => { modalBox
.checked
= false; }, 2000);
439 if (this.mode
== "human")
444 getEndgameMessage: function(score
) {
445 let eogMessage
= "Unfinished";
449 eogMessage
= "White win";
452 eogMessage
= "Black win";
461 if (this.mode
== "human" && this.oppConnected
)
464 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
465 } catch (INVALID_STATE_ERR
) {
466 return; //socket is not ready (and not yet reconnected)
469 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
471 setStorage: function() {
472 localStorage
.setItem("myid", this.myid
);
473 localStorage
.setItem("variant", variant
);
474 localStorage
.setItem("mycolor", this.mycolor
);
475 localStorage
.setItem("oppid", this.oppid
);
476 localStorage
.setItem("fenStart", this.fenStart
);
477 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
478 localStorage
.setItem("fen", this.vr
.getFen());
480 updateStorage: function() {
481 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
482 localStorage
.setItem("fen", this.vr
.getFen());
484 clearStorage: function() {
485 delete localStorage
["variant"];
486 delete localStorage
["myid"];
487 delete localStorage
["mycolor"];
488 delete localStorage
["oppid"];
489 delete localStorage
["fenStart"];
490 delete localStorage
["fen"];
491 delete localStorage
["moves"];
493 clickGameSeek: function() {
494 if (this.mode
== "human")
495 return; //no newgame while playing
498 delete localStorage
["newgame"]; //cancel game seek
502 this.newGame("human");
504 clickComputerGame: function() {
505 if (this.mode
== "human")
506 return; //no newgame while playing
507 this.newGame("computer");
509 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
510 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
511 console
.log(fen
); //DEBUG
513 if (mode
=="human" && !oppId
)
515 const storageVariant
= localStorage
.getItem("variant");
516 if (!!storageVariant
&& storageVariant
!== variant
)
518 alert("Finish your " + storageVariant
+ " game first!");
521 // Send game request and wait..
522 localStorage
["newgame"] = variant
;
524 this.clearStorage(); //in case of
526 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
527 } catch (INVALID_STATE_ERR
) {
528 return; //nothing achieved
530 if (continuation
!== "reconnect") //TODO: bad HACK...
532 let modalBox
= document
.getElementById("modal-newgame");
533 modalBox
.checked
= true;
534 setTimeout(() => { modalBox
.checked
= false; }, 2000);
538 this.vr
= new VariantRules(fen
, moves
|| []);
540 this.incheck
= []; //in case of
541 this.fenStart
= continuation
542 ? localStorage
.getItem("fenStart")
543 : fen
.split(" ")[0]; //Only the position matters
549 // Not playing sound on game continuation:
550 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
551 document
.getElementById("modal-newgame").checked
= false;
554 this.oppConnected
= true;
555 this.mycolor
= color
;
557 if (!!moves
&& moves
.length
> 0) //imply continuation
559 const oppCol
= this.vr
.turn
;
560 const lastMove
= moves
[moves
.length
-1];
561 this.vr
.undo(lastMove
);
562 this.incheck
= this.vr
.getCheckSquares(lastMove
, oppCol
);
563 this.vr
.play(lastMove
, "ingame");
565 delete localStorage
["newgame"];
566 this.setStorage(); //in case of interruptions
568 else //against computer
570 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
571 if (this.mycolor
== 'b')
572 setTimeout(this.playComputerMove
, 500);
575 playComputerMove: function() {
576 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
577 const compMove
= this.vr
.getComputerMove(compColor
);
578 // HACK: avoid selecting elements before they appear on page:
579 setTimeout(() => this.play(compMove
, "animate"), 500);
581 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
582 getSquareId: function(o
) {
583 // NOTE: a separator is required to allow any size of board
584 return "sq-" + o
.x
+ "-" + o
.y
;
587 getSquareFromId: function(id
) {
588 let idParts
= id
.split('-');
589 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
591 mousedown: function(e
) {
592 e
= e
|| window
.event
;
593 e
.preventDefault(); //disable native drag & drop
594 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
596 // Next few lines to center the piece on mouse cursor
597 let rect
= e
.target
.parentNode
.getBoundingClientRect();
599 x: rect
.x
+ rect
.width
/2,
600 y: rect
.y
+ rect
.width
/2,
601 id: e
.target
.parentNode
.id
603 this.selectedPiece
= e
.target
.cloneNode();
604 this.selectedPiece
.style
.position
= "absolute";
605 this.selectedPiece
.style
.top
= 0;
606 this.selectedPiece
.style
.display
= "inline-block";
607 this.selectedPiece
.style
.zIndex
= 3000;
608 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
609 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
610 ? this.vr
.getPossibleMovesFrom(startSquare
)
612 e
.target
.parentNode
.appendChild(this.selectedPiece
);
615 mousemove: function(e
) {
616 if (!this.selectedPiece
)
618 e
= e
|| window
.event
;
619 // If there is an active element, move it around
620 if (!!this.selectedPiece
)
622 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
623 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
626 mouseup: function(e
) {
627 if (!this.selectedPiece
)
629 e
= e
|| window
.event
;
630 // Read drop target (or parentElement, parentNode... if type == "img")
631 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
632 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
633 this.selectedPiece
.style
.zIndex
= 3000;
634 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
635 landing
= landing
.parentNode
;
636 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
638 // OK: process move attempt
639 let endSquare
= this.getSquareFromId(landing
.id
);
640 let moves
= this.findMatchingMoves(endSquare
);
641 this.possibleMoves
= [];
642 if (moves
.length
> 1)
643 this.choices
= moves
;
644 else if (moves
.length
==1)
646 // Else: impossible move
647 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
648 delete this.selectedPiece
;
649 this.selectedPiece
= null;
651 findMatchingMoves: function(endSquare
) {
652 // Run through moves list and return the matching set (if promotions...)
654 this.possibleMoves
.forEach(function(m
) {
655 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
660 animateMove: function(move) {
661 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
662 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
663 let rectStart
= startSquare
.getBoundingClientRect();
664 let rectEnd
= endSquare
.getBoundingClientRect();
665 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
666 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
667 // HACK for animation (otherwise with positive translate, image slides "under background"...)
668 // Possible improvement: just alter squares on the piece's way...
669 squares
= document
.getElementsByClassName("board");
670 for (let i
=0; i
<squares
.length
; i
++)
672 let square
= squares
.item(i
);
673 if (square
.id
!= this.getSquareId(move.start
))
674 square
.style
.zIndex
= "-1";
676 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
677 movingPiece
.style
.transitionDuration
= "0.2s";
678 movingPiece
.style
.zIndex
= "3000";
680 for (let i
=0; i
<squares
.length
; i
++)
681 squares
.item(i
).style
.zIndex
= "auto";
682 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
686 play: function(move, programmatic
) {
687 if (!!programmatic
) //computer or human opponent
689 this.animateMove(move);
692 const oppCol
= this.vr
.getOppCol(this.vr
.turn
);
693 this.incheck
= this.vr
.getCheckSquares(move, oppCol
); //is opponent in check?
694 // Not programmatic, or animation is over
695 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
696 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
697 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
698 this.vr
.play(move, "ingame");
699 if (this.mode
== "human")
700 this.updateStorage(); //after our moves and opponent moves
701 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
704 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
705 setTimeout(this.playComputerMove
, 500);