37cdec193654940872aff8eff47a14202bfb4d40
1 // TODO: envoyer juste "light move", sans FEN ni notation ...etc
2 // TODO: also "observers" prop (human mode only), 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 // subMode: "auto" (game comp vs comp) or "corr" (correspondance game)
8 props: ["conn","gameId","fen","mode","subMode","allowChat","allowMovelist","queryHash","settings"],
11 oppConnected: false, //TODO?
12 // Web worker to play computer moves without freezing interface:
13 compWorker: new Worker('/javascripts/playCompMove.js'),
14 timeStart: undefined, //time when computer starts thinking
15 vr: null, //VariantRules object, describing the game state + rules
18 lockCompThink: false, //used to avoid some ghost moves
20 oppid: "", //opponent ID in case of HH game
21 score: "*", //'*' means 'unfinished'
22 // userColor: given by gameId, or fen in problems mode (if no game Id)...
25 moves: [], //TODO: initialize if gameId is defined...
26 cursor: -1, //index of the move just played
31 fen: function(newFen
) {
32 // (Security) No effect if a computer move is in progress:
33 if (this.mode
== "computer" && this.lockCompThink
)
34 return this.$emit("computer-think");
35 this.vr
= new VariantRules(newFen
);
38 this.fenStart
= newFen
;
40 if (this.mode
== "analyze")
42 this.mycolor
= V
.ParseFen(newFen
).turn
;
43 this.orientation
= "w"; //convention (TODO?!)
45 else if (this.mode
== "computer") //only other alternative (HH with gameId)
47 this.mycolor
= (Math
.random() < 0.5 ? "w" : "b");
48 this.orientation
= this.mycolor
;
49 this.compWorker
.postMessage(["init",newFen
]);
50 if (this.mycolor
!= "w" || this.subMode
== "auto")
51 this.playComputerMove();
57 queryHash: function(newQhash
) {
58 // New query hash = "id=42"; get 42 as gameId
59 this.gameId
= parseInt(newQhash
.substr(2));
64 showChat: function() {
65 return this.allowChat
&& this.mode
=='human' && this.score
!= '*';
67 showMoves: function() {
69 return this.allowMovelist
&& window
.innerWidth
>= 768;
72 return variant
.name
!= "Dark" || this.score
!= "*";
75 // Modal end of game, and then sub-components
76 // TODO: provide chat parameters (connection, players ID...)
77 // TODO: controls: abort, clear, resign, draw (avec confirm box)
78 // TODO: add corrMsg to sent move in case of corr game
80 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
81 <input id="modal-eog" type="checkbox" class="modal"/>
82 <div role="dialog" aria-labelledby="eogMessage">
83 <div class="card smallpad small-modal text-center">
84 <label for="modal-eog" class="modal-close">
86 <h3 id="eogMessage" class="section">
91 <my-chat v-if="showChat">
93 <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode"
94 :orientation="orientation" :user-color="mycolor" :settings="settings"
97 <div class="button-group">
98 <button @click="() => play()">Play</button>
99 <button @click="() => undo()">Undo</button>
100 <button @click="flip">Flip</button>
101 <button @click="gotoBegin">GotoBegin</button>
102 <button @click="gotoEnd">GotoEnd</button>
104 <div v-if="mode=='human' && subMode=='corr'">
105 <textarea v-show="score=='*' && vr.turn==mycolor" v-model="corrMsg">
107 <div v-show="cursor>=0">
108 {{ moves[cursor].message }}
111 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
112 <p id="fen-string" class="text-center">
116 <div id="pgn-div" class="section-content">
117 <a id="download" href="#">
119 <button id="downloadBtn" @click="download">
120 {{ translate("Download PGN") }}
123 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
127 created: function() {
132 this.vr
= new VariantRules(this.fen
);
133 this.fenStart
= this.fen
;
135 // TODO: after game, archive in indexedDB
136 // TODO: this events listener is central. Refactor ? How ?
137 const socketMessageListener
= msg
=> {
138 const data
= JSON
.parse(msg
.data
);
142 case "newmove": //..he played!
143 this.play(data
.move, (variant
.name
!="Dark" ? "animate" : null));
145 case "pong": //received if we sent a ping (game still alive on our side)
146 if (this.gameId
!= data
.gameId
)
147 break; //games IDs don't match: definitely over...
148 this.oppConnected
= true;
149 // Send our "last state" informations to opponent
150 L
= this.vr
.moves
.length
;
151 this.conn
.send(JSON
.stringify({
155 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
159 case "lastate": //got opponent infos about last move
160 L
= this.vr
.moves
.length
;
161 if (this.gameId
!= data
.gameId
)
162 break; //games IDs don't match: nothing we can do...
163 // OK, opponent still in game (which might be over)
164 if (this.score
!= "*")
166 // We finished the game (any result possible)
167 this.conn
.send(JSON
.stringify({
174 else if (!!data
.score
) //opponent finished the game
175 this.endGame(data
.score
);
176 else if (data
.movesCount
< L
)
178 // We must tell last move to opponent
179 this.conn
.send(JSON
.stringify({
183 lastMove: this.vr
.moves
[L
-1],
187 else if (data
.movesCount
> L
) //just got last move from him
188 this.play(data
.lastMove
, "animate");
190 case "resign": //..you won!
191 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
193 // TODO: also use (dis)connect info to count online players?
196 if (this.mode
=="human" && this.oppid
== data
.id
)
197 this.oppConnected
= (data
.code
== "connect");
198 if (this.oppConnected
&& this.score
!= "*")
200 // Send our name to the opponent, in case of he hasn't it
201 this.conn
.send(JSON
.stringify({
202 code:"myname", name:this.myname
, oppid: this.oppid
}));
208 const socketCloseListener
= () => {
209 this.conn
.addEventListener('message', socketMessageListener
);
210 this.conn
.addEventListener('close', socketCloseListener
);
214 this.conn
.onmessage
= socketMessageListener
;
215 this.conn
.onclose
= socketCloseListener
;
218 // Computer moves web worker logic: (TODO: also for observers in HH games)
219 this.compWorker
.postMessage(["scripts",variant
.name
]);
220 this.compWorker
.onmessage
= e
=> {
221 this.lockCompThink
= true; //to avoid some ghost moves
222 let compMove
= e
.data
;
223 if (!Array
.isArray(compMove
))
224 compMove
= [compMove
]; //to deal with MarseilleRules
225 // Small delay for the bot to appear "more human"
226 const delay
= Math
.max(500-(Date
.now()-this.timeStart
), 0);
228 const animate
= variant
.name
!= "Dark";
229 this.play(compMove
[0], animate
);
230 if (compMove
.length
== 2)
231 setTimeout( () => { this.play(compMove
[1], animate
); }, 750);
232 else //250 == length of animation (TODO: should be a constant somewhere)
233 setTimeout( () => this.lockCompThink
= false, 250);
237 // this.conn est une prop, donnée depuis variant.js
238 //dans variant.js (plutôt room.js) conn gère aussi les challenges
239 // Puis en webRTC, repenser tout ça.
241 translate: translate
,
242 loadGame: function() {
243 const game
= getGameFromStorage(this.gameId
);
244 this.oppid
= game
.oppid
; //opponent ID in case of running HH game
245 this.score
= game
.score
;
246 this.mycolor
= game
.mycolor
|| "w";
247 this.fenStart
= game
.fenStart
;
248 this.moves
= game
.moves
;
249 this.cursor
= game
.moves
.length
-1;
250 this.lastMove
= (game
.moves
.length
> 0 ? game
.moves
[this.cursor
] : null);
252 setEndgameMessage: function(score
) {
253 let eogMessage
= "Undefined";
257 eogMessage
= translations
["White win"];
260 eogMessage
= translations
["Black win"];
263 eogMessage
= translations
["Draw"];
266 eogMessage
= "Unfinished";
269 this.endgameMessage
= eogMessage
;
271 download: function() {
272 const content
= this.getPgn();
273 // Prepare and trigger download link
274 let downloadAnchor
= document
.getElementById("download");
275 downloadAnchor
.setAttribute("download", "game.pgn");
276 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
277 downloadAnchor
.click();
281 pgn
+= '[Site "vchess.club"]\n';
282 const opponent
= (this.mode
=="human" ? "Anonymous" : "Computer");
283 pgn
+= '[Variant "' + variant
.name
+ '"]\n';
284 pgn
+= '[Date "' + getDate(new Date()) + '"]\n';
285 const whiteName
= ["human","computer"].includes(this.mode
)
286 ? (this.mycolor
=='w'?'Myself':opponent
)
288 const blackName
= ["human","computer"].includes(this.mode
)
289 ? (this.mycolor
=='b'?'Myself':opponent
)
291 pgn
+= '[White "' + whiteName
+ '"]\n';
292 pgn
+= '[Black "' + blackName
+ '"]\n';
293 pgn
+= '[Fen "' + this.fenStart
+ '"]\n';
294 pgn
+= '[Result "' + this.score
+ '"]\n\n';
297 while (i
< this.moves
.length
)
299 pgn
+= (counter
++) + ".";
300 for (let color
of ["w","b"])
303 while (i
< this.moves
.length
&& this.moves
[i
].color
== color
)
304 move += this.moves
[i
++].notation
[0] + ",";
305 move = move.slice(0,-1); //remove last comma
306 pgn
+= move + (i
< this.moves
.length
-1 ? " " : "");
311 showScoreMsg: function(score
) {
312 this.setEndgameMessage(score
);
313 let modalBox
= document
.getElementById("modal-eog");
314 modalBox
.checked
= true;
315 setTimeout(() => { modalBox
.checked
= false; }, 2000);
317 endGame: function(score
) {
319 this.showScoreMsg(score
);
320 this.$emit("game-over", score
);
321 if (this.mode
== "human")
323 localStorage
["score"] = score
;
324 if (this.oppConnected
)
326 // Send our nickname to opponent
327 this.conn
.send(JSON
.stringify({
328 code:"myname", name:this.myname
, oppid:this.oppid
}));
332 resign: function(e
) {
333 this.getRidOfTooltip(e
.currentTarget
);
334 if (this.mode
== "human" && this.oppConnected
)
337 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
338 } catch (INVALID_STATE_ERR
) {
339 return; //socket is not ready (and not yet reconnected)
342 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
344 playComputerMove: function() {
345 this.timeStart
= Date
.now();
346 this.compWorker
.postMessage(["askmove"]);
348 animateMove: function(move) {
349 let startSquare
= document
.getElementById(getSquareId(move.start
));
350 let endSquare
= document
.getElementById(getSquareId(move.end
));
351 let rectStart
= startSquare
.getBoundingClientRect();
352 let rectEnd
= endSquare
.getBoundingClientRect();
353 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
355 document
.querySelector("#" + getSquareId(move.start
) + " > img.piece");
356 // HACK for animation (with positive translate, image slides "under background")
357 // Possible improvement: just alter squares on the piece's way...
358 squares
= document
.getElementsByClassName("board");
359 for (let i
=0; i
<squares
.length
; i
++)
361 let square
= squares
.item(i
);
362 if (square
.id
!= getSquareId(move.start
))
363 square
.style
.zIndex
= "-1";
365 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
366 translation
.y
+ "px)";
367 movingPiece
.style
.transitionDuration
= "0.2s";
368 movingPiece
.style
.zIndex
= "3000";
370 for (let i
=0; i
<squares
.length
; i
++)
371 squares
.item(i
).style
.zIndex
= "auto";
372 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
373 this.play(move); //TODO: plutôt envoyer message "please play"
376 play: function(move, programmatic
) {
377 let navigate
= !move;
378 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
379 // (except if we receive opponent's move, human or computer)
380 if (!navigate
&& this.mode
!= "analyze" && !programmatic
381 && this.cursor
< this.moves
.length
-1)
387 if (this.cursor
== this.moves
.length
-1)
388 return; //no more moves
389 move = this.moves
[this.cursor
+1];
391 if (!!programmatic
) //computer or (remote) human opponent
393 if (this.cursor
< this.moves
.length
-1)
394 this.gotoEnd(); //required to play the move
395 return this.animateMove(move);
397 // Not programmatic, or animation is over
399 move.notation
= this.vr
.getNotation(move);
401 move.color
= this.vr
.turn
;
404 this.lastMove
= move;
406 move.fen
= this.vr
.getFen();
407 if (this.settings
.sound
== 2)
408 new Audio("/sounds/move.mp3").play().catch(err
=> {});
409 if (this.mode
== "human")
411 updateStorage(move); //after our moves and opponent moves
412 if (this.vr
.turn
== this.mycolor
)
413 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
415 else if (this.mode
== "computer")
417 // Send the move to web worker (including his own moves)
418 this.compWorker
.postMessage(["newmove",move]);
420 if (!navigate
&& (this.score
== "*" || this.mode
== "analyze"))
422 // Stack move on movesList at current cursor
423 if (this.cursor
== this.moves
.length
)
424 this.moves
.push(move);
426 this.moves
= this.moves
.slice(0,this.cursor
-1).concat([move]);
428 // Is opponent in check?
429 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
430 const score
= this.vr
.getCurrentScore();
433 if (["human","computer"].includes(this.mode
))
435 else //just show score on screen (allow undo)
436 this.showScoreMsg(score
);
437 // TODO: notify end of game (give score)
439 // subTurn condition for Marseille (and Avalanche) rules
440 else if ((this.mode
== "computer" && (!this.vr
.subTurn
|| this.vr
.subTurn
<= 1))
441 && (this.subMode
== "auto" || this.vr
.turn
!= this.mycolor
))
443 this.playComputerMove();
445 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
447 this.$children
[0].$forceUpdate(); //TODO!?
449 undo: function(move) {
450 let navigate
= !move;
454 return; //no more moves
455 move = this.moves
[this.cursor
];
459 this.lastMove
= (this.cursor
>= 0 ? this.moves
[this.cursor
] : undefined);
461 this.$children
[0].$forceUpdate(); //TODO!?
462 if (this.settings
.sound
== 2)
463 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
464 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
465 if (!navigate
&& this.mode
== "analyze")
468 this.$forceUpdate(); //TODO!?
470 gotoMove: function(index
) {
471 this.vr
= new VariantRules(this.moves
[index
].fen
);
473 this.lastMove
= this.moves
[index
];
475 gotoBegin: function() {
476 this.vr
= new VariantRules(this.fenStart
);
478 this.lastMove
= null;
480 gotoEnd: function() {
481 this.gotoMove(this.moves
.length
-1);
484 this.orientation
= V
.GetNextCol(this.orientation
);
488 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
489 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
491 //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB