1 // Game logic on a variant page: 3 modes, analyze, computer or human
2 // TODO: envoyer juste "light move", sans FEN ni notation ...etc
3 // TODO: if I'm an observer and player(s) disconnect/reconnect, how to find me ?
4 // onClick :: ask full game to remote player, and register as an observer in game
5 // (use gameId to communicate)
6 // on landing on game :: if gameId not found locally, check remotely
7 // ==> il manque un param dans game : "remoteId"
8 Vue
.component('my-game', {
9 // gameId: to find the game in storage (assumption: it exists)
10 // fen: to start from a FEN without identifiers (analyze mode)
11 // subMode: "auto" (game comp vs comp) or "corr" (correspondance game),
12 // or "examine" (after human game: TODO)
13 props: ["conn","gameRef","fen","mode","subMode",
14 "allowChat","allowMovelist","settings"],
17 // Web worker to play computer moves without freezing interface:
18 compWorker: new Worker('/javascripts/playCompMove.js'),
19 timeStart: undefined, //time when computer starts thinking
20 vr: null, //VariantRules object, describing the game state + rules
23 lockCompThink: false, //used to avoid some ghost moves
24 myname: user
.name
, //may be anonymous (thus no name)
25 opponents: {}, //filled later (potentially 2 or 3 opponents)
26 drawOfferSent: false, //did I just ask for draw?
27 people: {}, //observers
28 score: "*", //'*' means 'unfinished'
29 // userColor: given by gameId, or fen in problems mode (if no game Id)...
32 moves: [], //TODO: initialize if gameId is defined...
33 cursor: -1, //index of the move just played
39 // (Security) No effect if a computer move is in progress:
40 if (this.mode
== "computer" && this.lockCompThink
)
41 return this.$emit("computer-think");
42 this.newGameFromFen();
49 showChat: function() {
50 return this.allowChat
&& this.mode
=='human' && this.score
!= '*';
52 showMoves: function() {
54 return this.allowMovelist
&& window
.innerWidth
>= 768;
57 return variant
.name
!= "Dark" || this.score
!= "*";
60 // Modal end of game, and then sub-components
62 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
63 <input id="modal-eog" type="checkbox" class="modal"/>
64 <div role="dialog" aria-labelledby="eogMessage">
65 <div class="card smallpad small-modal text-center">
66 <label for="modal-eog" class="modal-close">
68 <h3 id="eogMessage" class="section">
73 <my-chat v-if="showChat" :conn="conn" :myname="myname"
74 :opponents="opponents" :people="people">
76 <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode"
77 :orientation="orientation" :user-color="mycolor" :settings="settings"
80 <div class="button-group">
81 <button @click="() => play()">Play</button>
82 <button @click="() => undo()">Undo</button>
83 <button @click="flip">Flip</button>
84 <button @click="gotoBegin">GotoBegin</button>
85 <button @click="gotoEnd">GotoEnd</button>
87 <div v-if="mode=='human'" class="button-group">
88 <button @click="offerDraw">Draw</button>
89 <button @click="abortGame">Abort</button>
90 <button @click="resign">Resign</button>
92 <div v-if="mode=='human' && subMode=='corr'">
93 <textarea v-show="score=='*' && vr.turn==mycolor" v-model="corrMsg">
95 <div v-show="cursor>=0">
96 {{ moves[cursor].message }}
99 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
100 <p id="fen-string" class="text-center">
104 <div id="pgn-div" class="section-content">
105 <a id="download" href="#">
107 <div class="button-group">
108 <button id="downloadBtn" @click="download">
109 {{ translate("Download PGN") }}
111 <button>Import game</button>
114 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
118 created: function() {
123 this.vr
= new V(this.fen
);
124 this.fenStart
= this.fen
;
126 // TODO: if I'm one of the players in game, then:
127 // Send ping to server (answer pong if opponent is connected)
128 if (true && !!this.conn
&& !!this.gameRef
)
130 this.conn
.onopen
= () => {
131 this.conn
.send(JSON
.stringify({
132 code:"ping",oppid:this.oppid
,gameId:this.gameRef
.id
}));
135 // TODO: also handle "draw accepted" (use opponents array?)
136 // --> must give this info also when sending lastState...
137 // and, if all players agree then OK draw (end game ...etc)
138 const socketMessageListener
= msg
=> {
139 const data
= JSON
.parse(msg
.data
);
143 case "newmove": //..he played!
144 this.play(data
.move, variant
.name
!="Dark" ? "animate" : null);
146 case "pong": //received if we sent a ping (game still alive on our side)
147 if (this.gameRef
.id
!= data
.gameId
)
148 break; //games IDs don't match: definitely over...
149 this.oppConnected
= true;
150 // Send our "last state" informations to opponent(s)
151 L
= this.vr
.moves
.length
;
152 Object
.keys(this.opponents
).forEach(oid
=> {
153 this.conn
.send(JSON
.stringify({
156 gameId: this.gameRef
.id
,
157 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
162 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves (not just one)
163 case "lastate": //got opponent infos about last move
164 L
= this.vr
.moves
.length
;
165 if (this.gameRef
.id
!= data
.gameId
)
166 break; //games IDs don't match: nothing we can do...
167 // OK, opponent still in game (which might be over)
168 if (this.score
!= "*")
170 // We finished the game (any result possible)
171 this.conn
.send(JSON
.stringify({
174 gameId: this.gameRef
.id
,
178 else if (!!data
.score
) //opponent finished the game
179 this.endGame(data
.score
);
180 else if (data
.movesCount
< L
)
182 // We must tell last move to opponent
183 this.conn
.send(JSON
.stringify({
185 oppid: this.opponent
.id
,
186 gameId: this.gameRef
.id
,
187 lastMove: this.vr
.moves
[L
-1],
191 else if (data
.movesCount
> L
) //just got last move from him
192 this.play(data
.lastMove
, "animate");
194 case "resign": //..you won!
195 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
197 // TODO: also use (dis)connect info to count online players?
200 if (this.mode
=="human")
202 const online
= (data
.code
== "connect");
203 // If this is an opponent ?
204 if (!!this.opponents
[data
.id
])
205 this.opponents
[data
.id
].online
= online
;
210 delete this.people
[data
.id
];
212 this.people
[data
.id
] = data
.name
;
218 const socketCloseListener
= () => {
219 this.conn
.addEventListener('message', socketMessageListener
);
220 this.conn
.addEventListener('close', socketCloseListener
);
224 this.conn
.onmessage
= socketMessageListener
;
225 this.conn
.onclose
= socketCloseListener
;
227 // Computer moves web worker logic: (TODO: also for observers in HH games ?)
228 this.compWorker
.postMessage(["scripts",variant
.name
]);
229 this.compWorker
.onmessage
= e
=> {
230 this.lockCompThink
= true; //to avoid some ghost moves
231 let compMove
= e
.data
;
232 if (!Array
.isArray(compMove
))
233 compMove
= [compMove
]; //to deal with MarseilleRules
234 // Small delay for the bot to appear "more human"
235 const delay
= Math
.max(500-(Date
.now()-this.timeStart
), 0);
237 const animate
= variant
.name
!= "Dark";
238 this.play(compMove
[0], animate
);
239 if (compMove
.length
== 2)
240 setTimeout( () => { this.play(compMove
[1], animate
); }, 750);
241 else //250 == length of animation (TODO: should be a constant somewhere)
242 setTimeout( () => this.lockCompThink
= false, 250);
246 // dans variant.js (plutôt room.js) conn gère aussi les challenges
247 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
249 offerDraw: function() {
250 if (!confirm("Offer draw?"))
252 // Stay in "draw offer sent" state until next move is played
253 this.drawOfferSent
= true;
254 if (this.subMode
== "corr")
256 // TODO: set drawOffer on in game (how ?)
260 this.opponents
.forEach(o
=> {
264 this.conn
.send(JSON
.stringify({code: "draw", oppid: o
.id
}));
265 } catch (INVALID_STATE_ERR
) {
272 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
273 receiveDrawOffer: function() {
275 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
276 // if accept: send message "draw"
278 abortGame: function() {
279 if (!confirm("Abort the game?"))
281 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
282 //send message: "gameOver" avec score "?"
284 resign: function(e
) {
285 if (!confirm("Resign the game?"))
287 if (this.mode
== "human" && this.oppConnected(this.oppid
))
290 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
291 } catch (INVALID_STATE_ERR
) {
295 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
297 translate: translate
,
298 newGameFromFen: function() {
299 this.vr
= new V(this.fen
);
302 this.fenStart
= this.fen
;
304 if (this.mode
== "analyze")
306 this.mycolor
= V
.ParseFen(this.fen
).turn
;
307 this.orientation
= this.mycolor
;
309 else if (this.mode
== "computer") //only other alternative (HH with gameId)
311 this.mycolor
= (Math
.random() < 0.5 ? "w" : "b");
312 this.orientation
= this.mycolor
;
313 this.compWorker
.postMessage(["init",this.fen
]);
314 if (this.mycolor
!= "w" || this.subMode
== "auto")
315 this.playComputerMove();
318 loadGame: function() {
319 // TODO: ask game to remote peer if this.remoteId is set
320 // (or just if game not found locally)
321 // NOTE: if it's a corr game, ask it from server
322 const game
= getGameFromStorage(this.gameRef
.id
, this.gameRef
.uid
); //uid may be blank
323 this.opponent
.id
= game
.oppid
; //opponent ID in case of running HH game
324 this.opponent
.name
= game
.oppname
; //maye be blank (if anonymous)
325 this.score
= game
.score
;
326 this.mycolor
= game
.mycolor
;
327 this.fenStart
= game
.fenStart
;
328 this.moves
= game
.moves
;
329 this.cursor
= game
.moves
.length
-1;
330 this.lastMove
= (game
.moves
.length
> 0 ? game
.moves
[this.cursor
] : null);
332 setEndgameMessage: function(score
) {
333 let eogMessage
= "Undefined";
337 eogMessage
= translations
["White win"];
340 eogMessage
= translations
["Black win"];
343 eogMessage
= translations
["Draw"];
346 eogMessage
= "Unfinished";
349 this.endgameMessage
= eogMessage
;
351 download: function() {
352 const content
= this.getPgn();
353 // Prepare and trigger download link
354 let downloadAnchor
= document
.getElementById("download");
355 downloadAnchor
.setAttribute("download", "game.pgn");
356 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
357 downloadAnchor
.click();
361 pgn
+= '[Site "vchess.club"]\n';
362 const opponent
= (this.mode
=="human" ? "Anonymous" : "Computer");
363 pgn
+= '[Variant "' + variant
.name
+ '"]\n';
364 pgn
+= '[Date "' + getDate(new Date()) + '"]\n';
365 const whiteName
= ["human","computer"].includes(this.mode
)
366 ? (this.mycolor
=='w'?'Myself':opponent
)
368 const blackName
= ["human","computer"].includes(this.mode
)
369 ? (this.mycolor
=='b'?'Myself':opponent
)
371 pgn
+= '[White "' + whiteName
+ '"]\n';
372 pgn
+= '[Black "' + blackName
+ '"]\n';
373 pgn
+= '[Fen "' + this.fenStart
+ '"]\n';
374 pgn
+= '[Result "' + this.score
+ '"]\n\n';
377 while (i
< this.moves
.length
)
379 pgn
+= (counter
++) + ".";
380 for (let color
of ["w","b"])
383 while (i
< this.moves
.length
&& this.moves
[i
].color
== color
)
384 move += this.moves
[i
++].notation
[0] + ",";
385 move = move.slice(0,-1); //remove last comma
386 pgn
+= move + (i
< this.moves
.length
-1 ? " " : "");
391 showScoreMsg: function(score
) {
392 this.setEndgameMessage(score
);
393 let modalBox
= document
.getElementById("modal-eog");
394 modalBox
.checked
= true;
395 setTimeout(() => { modalBox
.checked
= false; }, 2000);
397 endGame: function(score
) {
399 this.showScoreMsg(score
);
400 if (this.mode
== "human")
401 localStorage
["score"] = score
;
402 this.$emit("game-over");
404 oppConnected: function(uid
) {
405 return this.opponents
.any(o
=> o
.id
== uidi
&& o
.online
);
407 playComputerMove: function() {
408 this.timeStart
= Date
.now();
409 this.compWorker
.postMessage(["askmove"]);
411 animateMove: function(move) {
412 let startSquare
= document
.getElementById(getSquareId(move.start
));
413 let endSquare
= document
.getElementById(getSquareId(move.end
));
414 let rectStart
= startSquare
.getBoundingClientRect();
415 let rectEnd
= endSquare
.getBoundingClientRect();
416 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
418 document
.querySelector("#" + getSquareId(move.start
) + " > img.piece");
419 // HACK for animation (with positive translate, image slides "under background")
420 // Possible improvement: just alter squares on the piece's way...
421 squares
= document
.getElementsByClassName("board");
422 for (let i
=0; i
<squares
.length
; i
++)
424 let square
= squares
.item(i
);
425 if (square
.id
!= getSquareId(move.start
))
426 square
.style
.zIndex
= "-1";
428 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
429 translation
.y
+ "px)";
430 movingPiece
.style
.transitionDuration
= "0.2s";
431 movingPiece
.style
.zIndex
= "3000";
433 for (let i
=0; i
<squares
.length
; i
++)
434 squares
.item(i
).style
.zIndex
= "auto";
435 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
439 play: function(move, programmatic
) {
440 let navigate
= !move;
441 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
442 // (except if we receive opponent's move, human or computer)
443 if (!navigate
&& this.mode
!= "analyze" && !programmatic
444 && this.cursor
< this.moves
.length
-1)
450 if (this.cursor
== this.moves
.length
-1)
451 return; //no more moves
452 move = this.moves
[this.cursor
+1];
454 if (!!programmatic
) //computer or (remote) human opponent
456 if (this.cursor
< this.moves
.length
-1)
457 this.gotoEnd(); //required to play the move
458 return this.animateMove(move);
460 // Not programmatic, or animation is over
461 if (this.mode
== "human" && this.subMode
== "corr" && this.mycolor
== this.vr
.turn
)
463 // TODO: show confirm box "validate move ?"
466 move.notation
= this.vr
.getNotation(move);
468 move.color
= this.vr
.turn
;
471 this.lastMove
= move;
473 move.fen
= this.vr
.getFen();
474 if (this.settings
.sound
== 2)
475 new Audio("/sounds/move.mp3").play().catch(err
=> {});
476 if (this.mode
== "human")
478 updateStorage(move); //after our moves and opponent moves
479 if (this.vr
.turn
== this.mycolor
)
480 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
482 else if (this.mode
== "computer")
484 // Send the move to web worker (including his own moves)
485 this.compWorker
.postMessage(["newmove",move]);
487 if (!navigate
&& (this.score
== "*" || this.mode
== "analyze"))
489 // Stack move on movesList at current cursor
490 if (this.cursor
== this.moves
.length
)
491 this.moves
.push(move);
493 this.moves
= this.moves
.slice(0,this.cursor
).concat([move]);
495 // Is opponent in check?
496 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
497 const score
= this.vr
.getCurrentScore();
500 if (["human","computer"].includes(this.mode
))
502 else //just show score on screen (allow undo)
503 this.showScoreMsg(score
);
505 // subTurn condition for Marseille (and Avalanche) rules
506 else if ((this.mode
== "computer" && (!this.vr
.subTurn
|| this.vr
.subTurn
<= 1))
507 && (this.subMode
== "auto" || this.vr
.turn
!= this.mycolor
))
509 this.playComputerMove();
511 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
513 this.$children
[0].$forceUpdate(); //TODO!?
515 undo: function(move) {
516 let navigate
= !move;
520 return; //no more moves
521 move = this.moves
[this.cursor
];
525 this.lastMove
= (this.cursor
>= 0 ? this.moves
[this.cursor
] : undefined);
526 if (this.settings
.sound
== 2)
527 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
528 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
530 this.$children
[0].$forceUpdate(); //TODO!?
531 else if (this.mode
== "analyze") //TODO: can this happen?
534 gotoMove: function(index
) {
535 this.vr
= new V(this.moves
[index
].fen
);
537 this.lastMove
= this.moves
[index
];
539 gotoBegin: function() {
540 this.vr
= new V(this.fenStart
);
542 this.lastMove
= null;
544 gotoEnd: function() {
545 this.gotoMove(this.moves
.length
-1);
548 this.orientation
= V
.GetNextCol(this.orientation
);