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 // Also precompute in-check squares
28 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
29 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
30 let elementArray
= [];
31 let square00
= document
.getElementById("sq-0-0");
32 let squareWidth
= !!square00
33 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
35 const playingHuman
= (this.mode
== "human");
36 const playingComp
= (this.mode
== "computer");
42 if (this.mode
== "human")
43 return; //no newgame while playing
45 delete localStorage
["newgame"]; //cancel game seek
48 localStorage
["newgame"] = variant
;
49 this.newGame("human");
51 this.seek
= !this.seek
;
54 attrs: { "aria-label": 'New game VS human' },
58 "playing": playingHuman
,
61 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
66 if (this.mode
== "human")
67 return; //no newgame while playing
68 this.newGame("computer");
71 attrs: { "aria-label": 'New game VS computer' },
74 "playing": playingComp
,
77 [h('i', { 'class': { "material-icons": true } }, "computer")])
81 if (this.mode
== "human")
83 let connectedIndic
= h(
87 "connected": this.oppConnected
,
88 "disconnected": !this.oppConnected
,
92 elementArray
.push(connectedIndic
);
94 let choices
= h('div',
96 attrs: { "id": "choices" },
97 'class': { 'row': true },
99 //"position": "relative",
100 "display": this.choices
.length
>0?"block":"none",
101 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
102 "width": (this.choices
.length
* squareWidth
) + "px",
103 "height": squareWidth
+ "px",
106 this.choices
.map( m
=> { //a "choice" is a move
109 'class': { 'board': true },
111 'width': (100/this.choices
.length
) + "%",
112 'padding-bottom': (100/this.choices
.length
) + "%",
117 attrs: { "src": '/images/pieces/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
118 'class': { 'choice-piece': true, 'board': true },
119 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
125 // Create board element (+ reserves if needed by variant or mode)
126 let gameDiv
= h('div',
128 'class': { 'game': true },
130 [_
.range(sizeX
).map(i
=> {
131 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
138 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
140 _
.range(sizeY
).map(j
=> {
141 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
143 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
151 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
154 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
160 if (hintSquares
[ci
][cj
])
170 src: "/images/mark.svg",
176 const lm
= this.vr
.lastMove
;
177 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
183 'light-square': !highlight
&& (i
+j
)%2==0,
184 'dark-square': !highlight
&& (i
+j
)%2==1,
185 'highlight': highlight
,
186 'incheck': incheckSq
[ci
][cj
],
189 id: this.getSquareId({x:ci
,y:cj
}),
201 on: { click: this.resign
},
202 attrs: { "aria-label": 'Resign' },
203 'class': { "tooltip":true },
205 [h('i', { 'class': { "material-icons": true } }, "flag")])
207 elementArray
.push(gameDiv
);
210 // let reserve = h('div',
211 // {'class':{'game':true}}, [
213 // { 'class': { 'row': true }},
216 // {'class':{'board':true}},
217 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
223 // elementArray.push(reserve);
225 let eogMessage
= "Unfinished";
229 eogMessage
= "White win";
232 eogMessage
= "Black win";
242 attrs: { "for": "modal-control" },
243 "class": { "modal-close": true },
248 "class": { "section": true },
249 domProps: { innerHTML: eogMessage
},
253 if (this.score
!= "*")
256 h('p', //'textarea', //TODO: selectable!
258 domProps: { innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
) },
259 //attrs: { "readonly": true },
267 attrs: { "id": "modal-control", type: "checkbox" },
268 "class": { "modal": true },
272 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
277 "class": { "card": true, "smallpad": true },
284 elementArray
= elementArray
.concat(modalEog
);
286 const modalNewgame
= [
289 attrs: { "id": "modal-control2", type: "checkbox" },
290 "class": { "modal": true },
294 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
299 "class": { "card": true, "smallpad": true },
304 attrs: { "id": "close-newgame", "for": "modal-control2" },
305 "class": { "modal-close": true },
310 "class": { "section": true },
311 domProps: { innerHTML: "New game" },
316 "class": { "section": true },
317 domProps: { innerHTML: "Waiting for opponent..." },
325 elementArray
= elementArray
.concat(modalNewgame
);
326 const actions
= h('div',
328 attrs: { "id": "actions" },
329 'class': { 'text-center': true },
333 elementArray
.push(actions
);
340 "col-md-offset-2":true,
342 "col-lg-offset-3":true,
344 // NOTE: click = mousedown + mouseup --> what about smartphone?!
346 mousedown: this.mousedown
,
347 mousemove: this.mousemove
,
348 mouseup: this.mouseup
,
349 touchdown: this.mousedown
,
350 touchmove: this.mousemove
,
351 touchup: this.mouseup
,
357 created: function() {
358 const url
= socketUrl
;
359 const continuation
= (localStorage
.getItem("variant") === variant
);
360 this.myid
= continuation
361 ? localStorage
.getItem("myid")
362 // random enough (TODO: function)
363 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
364 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
365 const socketOpenListener
= () => {
368 // TODO: check FEN integrity with opponent
369 const fen
= localStorage
.getItem("fen");
370 const mycolor
= localStorage
.getItem("mycolor");
371 const oppid
= localStorage
.getItem("oppid");
372 const moves
= JSON
.parse(localStorage
.getItem("moves"));
373 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
374 // Send ping to server, which answers pong if opponent is connected
375 this.conn
.send(JSON
.stringify({code:"ping", oppid:this.oppId
}));
377 else if (localStorage
.getItem("newgame") === variant
)
379 // New game request has been cancelled on disconnect
381 this.newGame("human", "reconnect");
384 const socketMessageListener
= msg
=> {
385 const data
= JSON
.parse(msg
.data
);
388 case "newgame": //opponent found
389 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
391 case "newmove": //..he played!
392 this.play(data
.move, "animate");
394 case "pong": //sent when opponent stayed online after we disconnected
395 this.oppConnected
= true;
397 case "resign": //..you won!
398 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
400 // TODO: also use (dis)connect info to count online players
403 if (this.mode
== "human" && this.oppid
== data
.id
)
404 this.oppConnected
= (data
.code
== "connect");
408 const socketCloseListener
= () => {
409 console
.log("Lost connection -- reconnect");
410 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
411 this.conn
.addEventListener('open', socketOpenListener
);
412 this.conn
.addEventListener('message', socketMessageListener
);
413 this.conn
.addEventListener('close', socketCloseListener
);
415 this.conn
.onopen
= socketOpenListener
;
416 this.conn
.onmessage
= socketMessageListener
;
417 this.conn
.onclose
= socketCloseListener
;
420 endGame: function(score
) {
422 let modalBox
= document
.getElementById("modal-control");
423 modalBox
.checked
= true;
424 //setTimeout(() => { modalBox.checked = false; }, 2000); //disabled, to show PGN
425 if (this.mode
== "human")
431 if (this.mode
== "human" && this.oppConnected
)
434 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
435 } catch (INVALID_STATE_ERR
) {
436 return; //resign failed for some reason...
439 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
441 setStorage: function() {
442 localStorage
.setItem("myid", this.myid
);
443 localStorage
.setItem("variant", variant
);
444 localStorage
.setItem("mycolor", this.mycolor
);
445 localStorage
.setItem("oppid", this.oppid
);
446 localStorage
.setItem("fenStart", this.fenStart
);
447 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
448 localStorage
.setItem("fen", this.vr
.getFen());
450 updateStorage: function() {
451 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
452 localStorage
.setItem("fen", this.vr
.getFen());
454 clearStorage: function() {
455 delete localStorage
["variant"];
456 delete localStorage
["myid"];
457 delete localStorage
["mycolor"];
458 delete localStorage
["oppid"];
459 delete localStorage
["fenStart"];
460 delete localStorage
["fen"];
461 delete localStorage
["moves"];
463 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
464 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
465 console
.log(fen
); //DEBUG
467 if (mode
=="human" && !oppId
)
469 const storageVariant
= localStorage
.getItem("variant");
470 if (!!storageVariant
&& storageVariant
!== variant
)
472 // TODO: find a better way to ensure this. Newgame system is currently a mess.
473 alert("Finish your " + storageVariant
+ " game first!");
476 // Send game request and wait..
477 this.clearStorage(); //in case of
479 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
480 } catch (INVALID_STATE_ERR
) {
481 return; //nothing achieved
483 if (!fenInit
|| fenInit
!="reconnect") //TODO: bad HACK...
485 let modalBox
= document
.getElementById("modal-control2");
486 modalBox
.checked
= true;
487 setTimeout(() => { modalBox
.checked
= false; }, 2000);
491 this.vr
= new VariantRules(fen
, moves
|| []);
493 this.incheck
= []; //in case of
494 this.fenStart
= continuation
495 ? localStorage
.getItem("fenStart")
496 : fen
.split(" ")[0]; //Only the position matters
502 // Playing sound fails on game continuation:
503 new Audio("/sounds/newgame.mp3").play();
504 document
.getElementById("modal-control2").checked
= false;
507 this.oppConnected
= true;
508 this.mycolor
= color
;
510 if (!!moves
&& moves
.length
> 0) //imply continuation
512 const oppCol
= this.vr
.turn
;
513 const lastMove
= moves
[moves
.length
-1];
514 this.vr
.undo(lastMove
, "ingame");
515 this.incheck
= this.vr
.getCheckSquares(lastMove
, oppCol
);
516 this.vr
.play(lastMove
, "ingame");
518 delete localStorage
["newgame"];
519 this.setStorage(); //in case of interruptions
521 else //against computer
523 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
524 if (this.mycolor
== 'b')
525 setTimeout(this.playComputerMove
, 500);
528 playComputerMove: function() {
529 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
530 const compMove
= this.vr
.getComputerMove(compColor
);
531 // HACK: avoid selecting elements before they appear on page:
532 setTimeout(() => this.play(compMove
, "animate"), 500);
534 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
535 getSquareId: function(o
) {
536 // NOTE: a separator is required to allow any size of board
537 return "sq-" + o
.x
+ "-" + o
.y
;
540 getSquareFromId: function(id
) {
541 let idParts
= id
.split('-');
542 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
544 mousedown: function(e
) {
545 e
= e
|| window
.event
;
546 e
.preventDefault(); //disable native drag & drop
547 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
549 // Next few lines to center the piece on mouse cursor
550 let rect
= e
.target
.parentNode
.getBoundingClientRect();
552 x: rect
.x
+ rect
.width
/2,
553 y: rect
.y
+ rect
.width
/2,
554 id: e
.target
.parentNode
.id
556 this.selectedPiece
= e
.target
.cloneNode();
557 this.selectedPiece
.style
.position
= "absolute";
558 this.selectedPiece
.style
.top
= 0;
559 this.selectedPiece
.style
.display
= "inline-block";
560 this.selectedPiece
.style
.zIndex
= 3000;
561 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
562 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
563 ? this.vr
.getPossibleMovesFrom(startSquare
)
565 e
.target
.parentNode
.appendChild(this.selectedPiece
);
568 mousemove: function(e
) {
569 if (!this.selectedPiece
)
571 e
= e
|| window
.event
;
572 // If there is an active element, move it around
573 if (!!this.selectedPiece
)
575 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
576 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
579 mouseup: function(e
) {
580 if (!this.selectedPiece
)
582 e
= e
|| window
.event
;
583 // Read drop target (or parentElement, parentNode... if type == "img")
584 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
585 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
586 this.selectedPiece
.style
.zIndex
= 3000;
587 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
588 landing
= landing
.parentNode
;
589 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
591 // OK: process move attempt
592 let endSquare
= this.getSquareFromId(landing
.id
);
593 let moves
= this.findMatchingMoves(endSquare
);
594 this.possibleMoves
= [];
595 if (moves
.length
> 1)
596 this.choices
= moves
;
597 else if (moves
.length
==1)
599 // Else: impossible move
600 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
601 delete this.selectedPiece
;
602 this.selectedPiece
= null;
604 findMatchingMoves: function(endSquare
) {
605 // Run through moves list and return the matching set (if promotions...)
607 this.possibleMoves
.forEach(function(m
) {
608 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
613 animateMove: function(move) {
614 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
615 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
616 let rectStart
= startSquare
.getBoundingClientRect();
617 let rectEnd
= endSquare
.getBoundingClientRect();
618 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
619 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
620 // HACK for animation (otherwise with positive translate, image slides "under background"...)
621 // Possible improvement: just alter squares on the piece's way...
622 squares
= document
.getElementsByClassName("board");
623 for (let i
=0; i
<squares
.length
; i
++)
625 let square
= squares
.item(i
);
626 if (square
.id
!= this.getSquareId(move.start
))
627 square
.style
.zIndex
= "-1";
629 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
630 movingPiece
.style
.transitionDuration
= "0.2s";
631 movingPiece
.style
.zIndex
= "3000";
633 for (let i
=0; i
<squares
.length
; i
++)
634 squares
.item(i
).style
.zIndex
= "auto";
635 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
639 play: function(move, programmatic
) {
640 if (!!programmatic
) //computer or human opponent
642 this.animateMove(move);
645 const oppCol
= this.vr
.getOppCol(this.vr
.turn
);
646 this.incheck
= this.vr
.getCheckSquares(move, oppCol
); //is opponent in check?
647 // Not programmatic, or animation is over
648 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
650 if (!this.oppConnected
)
651 return; //abort move if opponent is gone
653 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
654 } catch(INVALID_STATE_ERR
) {
655 return; //abort also if sending failed
658 new Audio("/sounds/chessmove1.mp3").play();
659 this.vr
.play(move, "ingame");
660 if (this.mode
== "human")
661 this.updateStorage(); //after our moves and opponent moves
662 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
665 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
666 setTimeout(this.playComputerMove
, 500);