f5db3378e208dae1a50922452945dbbb5ec2531b
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
21 let [sizeX
,sizeY
] = VariantRules
.size
;
22 // Precompute hints squares to facilitate rendering
23 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
24 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
25 let elementArray
= [];
26 let square00
= document
.getElementById("sq-0-0");
27 let squareWidth
= !!square00
28 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
30 const playingHuman
= (this.mode
== "human");
31 const playingComp
= (this.mode
== "computer");
38 delete localStorage
["newgame"]; //cancel game seek
41 localStorage
["newgame"] = variant
;
42 this.newGame("human");
44 this.seek
= !this.seek
;
47 attrs: { "aria-label": 'New game VS human' },
51 "playing": playingHuman
,
54 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
57 on: { click: () => this.newGame("computer") },
58 attrs: { "aria-label": 'New game VS computer' },
61 "playing": playingComp
,
64 [h('i', { 'class': { "material-icons": true } }, "computer")])
68 if (this.mode
== "human")
70 let connectedIndic
= h(
74 "connected": this.oppConnected
,
75 "disconnected": !this.oppConnected
,
79 elementArray
.push(connectedIndic
);
81 let choices
= h('div',
83 attrs: { "id": "choices" },
84 'class': { 'row': true },
86 //"position": "relative",
87 "display": this.choices
.length
>0?"block":"none",
88 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
89 "width": (this.choices
.length
* squareWidth
) + "px",
90 "height": squareWidth
+ "px",
93 this.choices
.map( m
=> { //a "choice" is a move
96 'class': { 'board': true },
98 'width': (100/this.choices
.length
) + "%",
99 'padding-bottom': (100/this.choices
.length
) + "%",
104 attrs: { "src": '/images/pieces/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
105 'class': { 'choice-piece': true, 'board': true },
106 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
112 // Create board element (+ reserves if needed by variant or mode)
113 let gameDiv
= h('div',
115 'class': { 'game': true },
117 [_
.range(sizeX
).map(i
=> {
118 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
125 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
127 _
.range(sizeY
).map(j
=> {
128 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
130 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
138 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
141 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
147 if (hintSquares
[ci
][cj
])
157 src: "/images/mark.svg",
163 const lm
= this.vr
.lastMove
;
164 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}); //&& _.isMatch(lm.start, {x:ci,y:cj})
170 'light-square': !highlight
&& (i
+j
)%2==0,
171 'dark-square': !highlight
&& (i
+j
)%2==1,
172 'highlight': highlight
,
175 id: this.getSquareId({x:ci
,y:cj
}),
187 on: { click: this.resign
},
188 attrs: { "aria-label": 'Resign' },
189 'class': { "tooltip":true },
191 [h('i', { 'class': { "material-icons": true } }, "flag")])
193 elementArray
.push(gameDiv
);
196 // let reserve = h('div',
197 // {'class':{'game':true}}, [
199 // { 'class': { 'row': true }},
202 // {'class':{'board':true}},
203 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
209 // elementArray.push(reserve);
214 attrs: { "id": "modal-control", type: "checkbox" },
215 "class": { "modal": true },
219 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
224 "class": { "card": true, "smallpad": true },
229 attrs: { "for": "modal-control" },
230 "class": { "modal-close": true },
235 "class": { "section": true },
236 domProps: { innerHTML: "End of game" },
241 "class": { "section": true },
242 domProps: { innerHTML: this.endofgame
},
250 elementArray
= elementArray
.concat(modalEog
);
252 const modalNewgame
= [
255 attrs: { "id": "modal-control2", type: "checkbox" },
256 "class": { "modal": true },
260 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
265 "class": { "card": true, "smallpad": true },
270 attrs: { "id": "close-newgame", "for": "modal-control2" },
271 "class": { "modal-close": true },
276 "class": { "section": true },
277 domProps: { innerHTML: "New game" },
282 "class": { "section": true },
283 domProps: { innerHTML: "Waiting for opponent..." },
291 elementArray
= elementArray
.concat(modalNewgame
);
292 const actions
= h('div',
294 attrs: { "id": "actions" },
295 'class': { 'text-center': true },
299 elementArray
.push(actions
);
306 "col-md-offset-2":true,
308 "col-lg-offset-3":true,
310 // NOTE: click = mousedown + mouseup --> what about smartphone?!
312 mousedown: this.mousedown
,
313 mousemove: this.mousemove
,
314 mouseup: this.mouseup
,
315 touchdown: this.mousedown
,
316 touchmove: this.mousemove
,
317 touchup: this.mouseup
,
323 created: function() {
324 const url
= socketUrl
;
325 const continuation
= (localStorage
.getItem("variant") === variant
);
326 this.myid
= continuation
327 ? localStorage
.getItem("myid")
328 // random enough (TODO: function)
329 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
330 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
331 const socketOpenListener
= () => {
334 // TODO: check FEN integrity with opponent
335 this.newGame("human", localStorage
.getItem("fen"),
336 localStorage
.getItem("mycolor"), localStorage
.getItem("oppid"), true);
337 // Send ping to server, which answers pong if opponent is connected
338 this.conn
.send(JSON
.stringify({code:"ping", oppid:this.oppId
}));
340 else if (localStorage
.getItem("newgame") === variant
)
342 // New game request has been cancelled on disconnect
344 this.newGame("human");
347 const socketMessageListener
= msg
=> {
348 const data
= JSON
.parse(msg
.data
);
351 case "newgame": //opponent found
352 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
354 case "newmove": //..he played!
355 this.play(data
.move, "animate");
357 case "pong": //sent when opponent stayed online after we disconnected
358 this.oppConnected
= true;
360 case "resign": //..you won!
361 this.endGame("Victory!");
363 // TODO: also use (dis)connect info to count online players
366 if (this.mode
== "human" && this.oppid
== data
.id
)
367 this.oppConnected
= (data
.code
== "connect");
371 const socketCloseListener
= () => {
372 console
.log("Lost connection -- reconnect");
373 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
374 this.conn
.addEventListener('open', socketOpenListener
);
375 this.conn
.addEventListener('message', socketMessageListener
);
376 this.conn
.addEventListener('close', socketCloseListener
);
378 this.conn
.onopen
= socketOpenListener
;
379 this.conn
.onmessage
= socketMessageListener
;
380 this.conn
.onclose
= socketCloseListener
;
383 endGame: function(message
) {
384 this.endofgame
= message
;
385 let modalBox
= document
.getElementById("modal-control");
386 modalBox
.checked
= true;
387 setTimeout(() => { modalBox
.checked
= false; }, 2000);
388 if (this.mode
== "human")
394 if (this.mode
== "human" && this.oppConnected
)
397 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
398 } catch (INVALID_STATE_ERR
) {
399 return; //resign failed for some reason...
402 this.endGame("Try again!");
404 updateStorage: function() {
405 if (!localStorage
.getItem("myid"))
407 localStorage
.setItem("myid", this.myid
);
408 localStorage
.setItem("variant", variant
);
409 localStorage
.setItem("mycolor", this.mycolor
);
410 localStorage
.setItem("oppid", this.oppid
);
412 localStorage
.setItem("fen", this.vr
.getFen());
414 clearStorage: function() {
415 delete localStorage
["variant"];
416 delete localStorage
["myid"];
417 delete localStorage
["mycolor"];
418 delete localStorage
["oppid"];
419 delete localStorage
["fen"];
421 newGame: function(mode
, fenInit
, color
, oppId
, continuation
) {
422 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
423 console
.log(fen
); //DEBUG
424 if (mode
=="human" && !oppId
)
426 // Send game request and wait..
427 this.clearStorage(); //in case of
429 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
430 } catch (INVALID_STATE_ERR
) {
431 return; //nothing achieved
433 let modalBox
= document
.getElementById("modal-control2");
434 modalBox
.checked
= true;
435 setTimeout(() => { modalBox
.checked
= false; }, 2000);
438 this.vr
= new VariantRules(fen
);
445 // Playing sound fails on game continuation:
446 new Audio("/sounds/newgame.mp3").play();
447 document
.getElementById("modal-control2").checked
= false;
450 this.oppConnected
= true;
451 this.mycolor
= color
;
453 delete localStorage
["newgame"];
455 else //against computer
457 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
458 if (this.mycolor
== 'b')
459 setTimeout(this.playComputerMove
, 500);
462 playComputerMove: function() {
463 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
464 const compMove
= this.vr
.getComputerMove(compColor
);
465 // HACK: avoid selecting elements before they appear on page:
466 setTimeout(() => this.play(compMove
, "animate"), 500);
468 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
469 getSquareId: function(o
) {
470 // NOTE: a separator is required to allow any size of board
471 return "sq-" + o
.x
+ "-" + o
.y
;
474 getSquareFromId: function(id
) {
475 let idParts
= id
.split('-');
476 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
478 mousedown: function(e
) {
479 e
= e
|| window
.event
;
480 e
.preventDefault(); //disable native drag & drop
481 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
483 // Next few lines to center the piece on mouse cursor
484 let rect
= e
.target
.parentNode
.getBoundingClientRect();
486 x: rect
.x
+ rect
.width
/2,
487 y: rect
.y
+ rect
.width
/2,
488 id: e
.target
.parentNode
.id
490 this.selectedPiece
= e
.target
.cloneNode();
491 this.selectedPiece
.style
.position
= "absolute";
492 this.selectedPiece
.style
.top
= 0;
493 this.selectedPiece
.style
.display
= "inline-block";
494 this.selectedPiece
.style
.zIndex
= 3000;
495 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
496 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
497 ? this.vr
.getPossibleMovesFrom(startSquare
)
499 e
.target
.parentNode
.appendChild(this.selectedPiece
);
502 mousemove: function(e
) {
503 if (!this.selectedPiece
)
505 e
= e
|| window
.event
;
506 // If there is an active element, move it around
507 if (!!this.selectedPiece
)
509 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
510 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
513 mouseup: function(e
) {
514 if (!this.selectedPiece
)
516 e
= e
|| window
.event
;
517 // Read drop target (or parentElement, parentNode... if type == "img")
518 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
519 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
520 this.selectedPiece
.style
.zIndex
= 3000;
521 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
522 landing
= landing
.parentNode
;
523 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
525 // OK: process move attempt
526 let endSquare
= this.getSquareFromId(landing
.id
);
527 let moves
= this.findMatchingMoves(endSquare
);
528 this.possibleMoves
= [];
529 if (moves
.length
> 1)
530 this.choices
= moves
;
531 else if (moves
.length
==1)
533 // Else: impossible move
534 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
535 delete this.selectedPiece
;
536 this.selectedPiece
= null;
538 findMatchingMoves: function(endSquare
) {
539 // Run through moves list and return the matching set (if promotions...)
541 this.possibleMoves
.forEach(function(m
) {
542 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
547 animateMove: function(move) {
548 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
549 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
550 let rectStart
= startSquare
.getBoundingClientRect();
551 let rectEnd
= endSquare
.getBoundingClientRect();
552 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
553 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
554 // HACK for animation (otherwise with positive translate, image slides "under background"...)
555 // Possible improvement: just alter squares on the piece's way...
556 squares
= document
.getElementsByClassName("board");
557 for (let i
=0; i
<squares
.length
; i
++)
559 let square
= squares
.item(i
);
560 if (square
.id
!= this.getSquareId(move.start
))
561 square
.style
.zIndex
= "-1";
563 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
564 movingPiece
.style
.transitionDuration
= "0.2s";
565 movingPiece
.style
.zIndex
= "3000";
567 for (let i
=0; i
<squares
.length
; i
++)
568 squares
.item(i
).style
.zIndex
= "auto";
569 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
573 play: function(move, programmatic
) {
574 if (!!programmatic
) //computer or human opponent
576 this.animateMove(move);
579 // Not programmatic, or animation is over
580 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
582 if (!this.oppConnected
)
583 return; //abort move if opponent is gone
585 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
586 } catch(INVALID_STATE_ERR
) {
587 return; //abort also if sending failed
590 new Audio("/sounds/chessmove1.mp3").play();
591 this.vr
.play(move, "ingame");
592 if (this.mode
== "human")
593 this.updateStorage(); //after our moves and opponent moves
594 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
597 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
598 setTimeout(this.playComputerMove
, 500);