1 // TODO: envoyer juste "light move", sans FEN ni notation ...etc
2 // TODO: also "observers" prop, we should send moves to them too (in a web worker ? webRTC ?)
3 // Game logic on a variant page: 3 modes, analyze, computer or human
4 Vue
.component('my-game', {
5 // gameId: to find the game in storage (assumption: it exists)
6 // fen: to start from a FEN without identifiers (analyze mode)
7 props: ["conn","gameId","fen","mode","allowChat","allowMovelist"],
10 oppConnected: false, //TODO?
11 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
12 sound: parseInt(localStorage
["sound"] || "2"),
13 // Web worker to play computer moves without freezing interface:
14 compWorker: new Worker('/javascripts/playCompMove.js'),
15 timeStart: undefined, //time when computer starts thinking
16 vr: null, //VariantRules object, describing the game state + rules
20 // if oppid == "computer" then mode = "computer" (otherwise human)
21 oppid: "", //opponent ID in case of HH game
22 score: "*", //'*' means 'unfinished'
23 // userColor: given by gameId, or fen (if no game Id)
26 moves: [], //TODO: initialize if gameId is defined...
32 fen: function(newFen
) {
33 this.vr
= new VariantRules(newFen
);
40 showChat: function() {
41 return this.allowChat
&& this.mode
=='human' && this.score
!= '*';
43 showMoves: function() {
45 return this.allowMovelist
&& window
.innerWidth
>= 768;
48 return variant
.name
!= "Dark" || this.score
!= "*";
51 // Modal end of game, and then sub-components
52 // TODO: provide chat parameters (connection, players ID...)
53 // TODO: controls: abort, clear, resign, draw (avec confirm box)
55 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
56 <input id="modal-eog" type="checkbox" class="modal"/>
57 <div role="dialog" aria-labelledby="eogMessage">
58 <div class="card smallpad small-modal text-center">
59 <label for="modal-eog" class="modal-close">
61 <h3 id="eogMessage" class="section">
66 <my-chat v-if="showChat">
68 <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play">
70 <div class="button-group">
71 <button @click="() => play()">Play</button>
72 <button @click="() => undo()">Undo</button>
73 <button @click="flip">Flip</button>
74 <button @click="gotoBegin">GotoBegin</button>
75 <button @click="gotoEnd">GotoEnd</button>
77 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
78 <p id="fen-string" class="text-center">
82 <div id="pgn-div" class="section-content">
83 <a id="download" href="#">
85 <button id="downloadBtn" @click="download">
86 {{ translate("Download PGN") }}
89 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
98 this.vr
= new VariantRules(this.fen
);
99 this.fenStart
= this.fen
;
101 // TODO: after game, archive in indexedDB
102 // TODO: this events listener is central. Refactor ? How ?
103 const socketMessageListener
= msg
=> {
104 const data
= JSON
.parse(msg
.data
);
108 case "newmove": //..he played!
109 this.play(data
.move, (variant
.name
!="Dark" ? "animate" : null));
111 case "pong": //received if we sent a ping (game still alive on our side)
112 if (this.gameId
!= data
.gameId
)
113 break; //games IDs don't match: definitely over...
114 this.oppConnected
= true;
115 // Send our "last state" informations to opponent
116 L
= this.vr
.moves
.length
;
117 this.conn
.send(JSON
.stringify({
121 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
125 case "lastate": //got opponent infos about last move
126 L
= this.vr
.moves
.length
;
127 if (this.gameId
!= data
.gameId
)
128 break; //games IDs don't match: nothing we can do...
129 // OK, opponent still in game (which might be over)
130 if (this.score
!= "*")
132 // We finished the game (any result possible)
133 this.conn
.send(JSON
.stringify({
140 else if (!!data
.score
) //opponent finished the game
141 this.endGame(data
.score
);
142 else if (data
.movesCount
< L
)
144 // We must tell last move to opponent
145 this.conn
.send(JSON
.stringify({
149 lastMove: this.vr
.moves
[L
-1],
153 else if (data
.movesCount
> L
) //just got last move from him
154 this.play(data
.lastMove
, "animate");
156 case "resign": //..you won!
157 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
159 // TODO: also use (dis)connect info to count online players?
162 if (this.mode
=="human" && this.oppid
== data
.id
)
163 this.oppConnected
= (data
.code
== "connect");
164 if (this.oppConnected
&& this.score
!= "*")
166 // Send our name to the opponent, in case of he hasn't it
167 this.conn
.send(JSON
.stringify({
168 code:"myname", name:this.myname
, oppid: this.oppid
}));
174 const socketCloseListener
= () => {
175 this.conn
.addEventListener('message', socketMessageListener
);
176 this.conn
.addEventListener('close', socketCloseListener
);
178 this.conn
.onmessage
= socketMessageListener
;
179 this.conn
.onclose
= socketCloseListener
;
181 // Computer moves web worker logic: (TODO: also for observers in HH games)
182 this.compWorker
.postMessage(["scripts",variant
.name
]);
184 this.compWorker
.onmessage = function(e
) {
185 let compMove
= e
.data
;
187 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
188 if (!Array
.isArray(compMove
))
189 compMove
= [compMove
]; //to deal with MarseilleRules
190 // TODO: imperfect attempt to avoid ghost move:
191 compMove
.forEach(m
=> { m
.computer
= true; });
192 // (first move) HACK: small delay to avoid selecting elements
193 // before they appear on page:
194 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
196 const animate
= (variant
.name
!="Dark" ? "animate" : null);
197 if (self
.mode
== "computer") //warning: mode could have changed!
198 self
.play(compMove
[0], animate
);
199 if (compMove
.length
== 2)
201 if (self
.mode
== "computer")
202 self
.play(compMove
[1], animate
);
207 // this.conn est une prop, donnée depuis variant.js
208 //dans variant.js (plutôt room.js) conn gère aussi les challenges
209 // Puis en webRTC, repenser tout ça.
211 translate: translate
,
212 loadGame: function() {
213 const game
= getGameFromStorage(this.gameId
);
214 this.oppid
= game
.oppid
; //opponent ID in case of running HH game
215 this.score
= game
.score
;
216 this.mycolor
= game
.mycolor
|| "w";
217 this.fenStart
= game
.fenStart
;
218 this.moves
= game
.moves
;
219 this.cursor
= game
.moves
.length
;
220 this.lastMove
= (game
.moves
.length
> 0 ? game
.moves
[this.cursor
-1] : null);
222 setEndgameMessage: function(score
) {
223 let eogMessage
= "Undefined";
227 eogMessage
= translations
["White win"];
230 eogMessage
= translations
["Black win"];
233 eogMessage
= translations
["Draw"];
236 eogMessage
= "Unfinished";
239 this.endgameMessage
= eogMessage
;
241 download: function() {
242 const content
= this.getPgn();
243 // Prepare and trigger download link
244 let downloadAnchor
= document
.getElementById("download");
245 downloadAnchor
.setAttribute("download", "game.pgn");
246 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
247 downloadAnchor
.click();
251 pgn
+= '[Site "vchess.club"]\n';
252 const opponent
= (this.mode
=="human" ? "Anonymous" : "Computer");
253 pgn
+= '[Variant "' + variant
.name
+ '"]\n';
254 pgn
+= '[Date "' + getDate(new Date()) + '"]\n';
255 const whiteName
= ["human","computer"].includes(this.mode
)
256 ? (this.mycolor
=='w'?'Myself':opponent
)
258 const blackName
= ["human","computer"].includes(this.mode
)
259 ? (this.mycolor
=='b'?'Myself':opponent
)
261 pgn
+= '[White "' + whiteName
+ '"]\n';
262 pgn
+= '[Black "' + blackName
+ '"]\n';
263 pgn
+= '[Fen "' + this.fenStart
+ '"]\n';
264 pgn
+= '[Result "' + this.score
+ '"]\n\n';
267 while (i
< this.moves
.length
)
269 pgn
+= (counter
++) + ".";
270 for (let color
of ["w","b"])
273 while (i
< this.moves
.length
&& this.moves
[i
].color
== color
)
274 move += this.moves
[i
++].notation
[0] + ",";
275 move = move.slice(0,-1); //remove last comma
276 pgn
+= move + (i
< this.moves
.length
-1 ? " " : "");
281 showScoreMsg: function(score
) {
282 this.setEndgameMessage(score
);
283 let modalBox
= document
.getElementById("modal-eog");
284 modalBox
.checked
= true;
285 setTimeout(() => { modalBox
.checked
= false; }, 2000);
287 endGame: function(score
) {
289 if (["human","computer"].includes(this.mode
))
291 const prefix
= (this.mode
=="computer" ? "comp-" : "");
292 localStorage
.setItem(prefix
+"score", score
);
294 this.showScoreMsg(score
);
295 if (this.mode
== "human" && this.oppConnected
)
297 // Send our nickname to opponent
298 this.conn
.send(JSON
.stringify({
299 code:"myname", name:this.myname
, oppid:this.oppid
}));
301 // TODO: what about cursor ?
302 //this.cursor = this.vr.moves.length; //to navigate in finished game
304 resign: function(e
) {
305 this.getRidOfTooltip(e
.currentTarget
);
306 if (this.mode
== "human" && this.oppConnected
)
309 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
310 } catch (INVALID_STATE_ERR
) {
311 return; //socket is not ready (and not yet reconnected)
314 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
316 playComputerMove: function() {
317 this.timeStart
= Date
.now();
318 this.compWorker
.postMessage(["askmove"]);
320 animateMove: function(move) {
321 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
322 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
323 let rectStart
= startSquare
.getBoundingClientRect();
324 let rectEnd
= endSquare
.getBoundingClientRect();
325 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
327 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
328 // HACK for animation (with positive translate, image slides "under background")
329 // Possible improvement: just alter squares on the piece's way...
330 squares
= document
.getElementsByClassName("board");
331 for (let i
=0; i
<squares
.length
; i
++)
333 let square
= squares
.item(i
);
334 if (square
.id
!= this.getSquareId(move.start
))
335 square
.style
.zIndex
= "-1";
337 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
338 translation
.y
+ "px)";
339 movingPiece
.style
.transitionDuration
= "0.2s";
340 movingPiece
.style
.zIndex
= "3000";
342 for (let i
=0; i
<squares
.length
; i
++)
343 squares
.item(i
).style
.zIndex
= "auto";
344 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
345 this.play(move); //TODO: plutôt envoyer message "please play"
348 play: function(move, programmatic
) {
349 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
350 if (this.mode
!= "analyze" && this.cursor
< this.moves
.length
-1)
352 let navigate
= !move;
355 if (this.cursor
== this.moves
.length
)
356 return; //no more moves
357 move = this.moves
[this.cursor
];
359 if (!!programmatic
) //computer or human opponent
360 return this.animateMove(move);
361 // Not programmatic, or animation is over
363 move.notation
= this.vr
.getNotation(move);
365 move.color
= this.vr
.turn
;
368 this.lastMove
= move;
370 move.fen
= this.vr
.getFen();
372 new Audio("/sounds/move.mp3").play().catch(err
=> {});
373 if (this.mode
== "human")
375 updateStorage(move); //after our moves and opponent moves
376 if (this.vr
.turn
== this.userColor
)
377 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
379 else if (this.mode
== "computer")
381 // Send the move to web worker (including his own moves)
382 this.compWorker
.postMessage(["newmove",move]);
384 if (!navigate
&& (this.score
== "*" || this.mode
== "analyze"))
386 // Stack move on movesList at current cursor
387 if (this.cursor
== this.moves
.length
)
388 this.moves
.push(move);
390 this.moves
= this.moves
.slice(0,this.cursor
-1).concat([move]);
392 // Is opponent in check?
393 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
394 const score
= this.vr
.getCurrentScore();
397 if (["human","computer"].includes(this.mode
))
399 else //just show score on screen (allow undo)
400 this.showScoreMsg(score
);
401 // TODO: notify end of game (give score)
403 else if (this.mode
== "computer" && this.vr
.turn
!= this.userColor
)
404 this.playComputerMove();
405 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
407 this.$children
[0].$forceUpdate(); //TODO!?
409 undo: function(move) {
410 let navigate
= !move;
413 if (this.cursor
== 0)
414 return; //no more moves
415 move = this.moves
[this.cursor
-1];
419 this.lastMove
= (this.cursor
> 0 ? this.moves
[this.cursor
-1] : undefined);
421 this.$children
[0].$forceUpdate(); //TODO!?
423 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
424 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
425 if (!navigate
&& this.mode
== "analyze")
428 this.$forceUpdate(); //TODO!?
430 gotoMove: function(index
) {
431 this.vr
= new VariantRules(this.moves
[index
].fen
);
432 this.cursor
= index
+1;
433 this.lastMove
= this.moves
[index
];
435 gotoBegin: function() {
436 this.vr
= new VariantRules(this.fenStart
);
438 this.lastMove
= null;
440 gotoEnd: function() {
441 this.gotoMove(this.moves
.length
-1);
442 this.lastMove
= this.moves
[this.moves
.length
-1];
445 this.orientation
= V
.GetNextCol(this.orientation
);
449 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
450 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
452 //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB