4048a3d404190ecdf93d6b9743dba9d8cac243b6
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 ?)
4 // Game logic on a variant page: 3 modes, analyze, computer or human
5 Vue
.component('my-game', {
6 // gameId: to find the game in storage (assumption: it exists)
7 // fen: to start from a FEN without identifiers (analyze mode)
8 props: ["conn","gameId","fen","mode","allowChat","allowMovelist"],
11 // if oppid == "computer" then mode = "computer" (otherwise human)
12 myid: "", //our ID, always set
13 //this.myid = localStorage.getItem("myid")
14 oppid: "", //opponent ID in case of HH game
15 score: "*", //'*' means 'unfinished'
17 oppConnected: false, //TODO?
19 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
20 sound: parseInt(localStorage
["sound"] || "2"),
21 // Web worker to play computer moves without freezing interface:
22 compWorker: new Worker('/javascripts/playCompMove.js'),
23 timeStart: undefined, //time when computer starts thinking
24 vr: null, //VariantRules object, describing the game state + rules
29 moves: [], //TODO: initialize if gameId is defined...
31 // orientation :: button flip
32 // userColor: given by gameId, or fen (if no game Id)
33 // gameOver: known if gameId; otherwise assue false
34 // lastMove: update after every play, initialize with last move from list (if continuation)
35 //orientation ? userColor ? gameOver ? lastMove ?
40 fen: function(newFen
) {
41 this.vr
= new VariantRules(newFen
);
48 showChat: function() {
49 return this.allowChat
&& this.mode
=='human' && this.score
!= '*';
51 showMoves: function() {
53 return this.allowMovelist
&& window
.innerWidth
>= 768;
56 return variant
.name
!= "Dark" || this.score
!= "*";
59 // Modal end of game, and then sub-components
60 // TODO: provide chat parameters (connection, players ID...)
61 // and also moveList parameters (just moves ?)
62 // TODO: connection + turn indicators en haut à droite (superposé au menu)
63 // TODO: controls: abort, clear, resign, draw (avec confirm box)
64 // et si partie terminée : (mode analyse) just clear, back / play
65 // + flip button toujours disponible
66 // gotoMove : vr = new VariantRules(fen stocké dans le coup [TODO])
68 // NOTE: move.color must be fulfilled after each move played, because of Marseille (or Avalanche) chess
69 // --> useful in moveList component (universal comma separator ?)
72 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
73 <input id="modal-eog" type="checkbox" class="modal"/>
74 <div role="dialog" aria-labelledby="eogMessage">
75 <div class="card smallpad small-modal text-center">
76 <label for="modal-eog" class="modal-close">
78 <h3 id="eogMessage" class="section">
83 <my-chat v-if="showChat">
85 <my-board v-bind:vr="vr" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play">
87 <div class="button-group">
88 <button @click="() => play()">Play</button>
89 <button @click="() => undo()">Undo</button>
90 <button @click="flip">Flip</button>
91 <button @click="gotoBegin">GotoBegin</button>
92 <button @click="gotoEnd">GotoEnd</button>
94 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
95 <p id="fen-string" class="text-center">
99 <div id="pgn-div" class="section-content">
100 <a id="download" href="#">
102 <button id="downloadBtn" @click="download">
103 {{ translate("Download PGN") }}
106 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
110 created: function() {
115 this.vr
= new VariantRules(this.fen
);
116 this.fenStart
= this.fen
;
118 // TODO: after game, archive in indexedDB
119 // TODO: this events listener is central. Refactor ? How ?
120 const socketMessageListener
= msg
=> {
121 const data
= JSON
.parse(msg
.data
);
125 case "newmove": //..he played!
126 this.play(data
.move, (variant
.name
!="Dark" ? "animate" : null));
128 case "pong": //received if we sent a ping (game still alive on our side)
129 if (this.gameId
!= data
.gameId
)
130 break; //games IDs don't match: definitely over...
131 this.oppConnected
= true;
132 // Send our "last state" informations to opponent
133 L
= this.vr
.moves
.length
;
134 this.conn
.send(JSON
.stringify({
138 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
142 case "lastate": //got opponent infos about last move
143 L
= this.vr
.moves
.length
;
144 if (this.gameId
!= data
.gameId
)
145 break; //games IDs don't match: nothing we can do...
146 // OK, opponent still in game (which might be over)
147 if (this.score
!= "*")
149 // We finished the game (any result possible)
150 this.conn
.send(JSON
.stringify({
157 else if (!!data
.score
) //opponent finished the game
158 this.endGame(data
.score
);
159 else if (data
.movesCount
< L
)
161 // We must tell last move to opponent
162 this.conn
.send(JSON
.stringify({
166 lastMove: this.vr
.moves
[L
-1],
170 else if (data
.movesCount
> L
) //just got last move from him
171 this.play(data
.lastMove
, "animate");
173 case "resign": //..you won!
174 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
176 // TODO: also use (dis)connect info to count online players?
179 if (this.mode
=="human" && this.oppid
== data
.id
)
180 this.oppConnected
= (data
.code
== "connect");
181 if (this.oppConnected
&& this.score
!= "*")
183 // Send our name to the opponent, in case of he hasn't it
184 this.conn
.send(JSON
.stringify({
185 code:"myname", name:this.myname
, oppid: this.oppid
}));
191 const socketCloseListener
= () => {
192 this.conn
.addEventListener('message', socketMessageListener
);
193 this.conn
.addEventListener('close', socketCloseListener
);
195 this.conn
.onmessage
= socketMessageListener
;
196 this.conn
.onclose
= socketCloseListener
;
198 // Computer moves web worker logic: (TODO: also for observers in HH games)
199 this.compWorker
.postMessage(["scripts",variant
.name
]);
201 this.compWorker
.onmessage = function(e
) {
202 let compMove
= e
.data
;
204 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
205 if (!Array
.isArray(compMove
))
206 compMove
= [compMove
]; //to deal with MarseilleRules
207 // TODO: imperfect attempt to avoid ghost move:
208 compMove
.forEach(m
=> { m
.computer
= true; });
209 // (first move) HACK: small delay to avoid selecting elements
210 // before they appear on page:
211 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
213 const animate
= (variant
.name
!="Dark" ? "animate" : null);
214 if (self
.mode
== "computer") //warning: mode could have changed!
215 self
.play(compMove
[0], animate
);
216 if (compMove
.length
== 2)
218 if (self
.mode
== "computer")
219 self
.play(compMove
[1], animate
);
224 // this.conn est une prop, donnée depuis variant.js
225 //dans variant.js (plutôt room.js) conn gère aussi les challenges
226 // Puis en webRTC, repenser tout ça.
228 translate: translate
,
229 loadGame: function() {
230 // TODO: load this.gameId ...
232 setEndgameMessage: function(score
) {
233 let eogMessage
= "Undefined";
237 eogMessage
= translations
["White win"];
240 eogMessage
= translations
["Black win"];
243 eogMessage
= translations
["Draw"];
246 eogMessage
= "Unfinished";
249 this.endgameMessage
= eogMessage
;
251 download: function() {
252 // Variants may have special PGN structure (so next function isn't defined here)
253 // TODO: get fenStart from local game (using gameid)
254 const content
= V
.GetPGN(this.moves
, this.mycolor
, this.score
, fenStart
, this.mode
);
255 // Prepare and trigger download link
256 let downloadAnchor
= document
.getElementById("download");
257 downloadAnchor
.setAttribute("download", "game.pgn");
258 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
259 downloadAnchor
.click();
261 showScoreMsg: function(score
) {
262 this.setEndgameMessage(score
);
263 let modalBox
= document
.getElementById("modal-eog");
264 modalBox
.checked
= true;
265 setTimeout(() => { modalBox
.checked
= false; }, 2000);
267 endGame: function(score
) {
269 if (["human","computer"].includes(this.mode
))
271 const prefix
= (this.mode
=="computer" ? "comp-" : "");
272 localStorage
.setItem(prefix
+"score", score
);
274 this.showScoreMsg(score
);
275 if (this.mode
== "human" && this.oppConnected
)
277 // Send our nickname to opponent
278 this.conn
.send(JSON
.stringify({
279 code:"myname", name:this.myname
, oppid:this.oppid
}));
281 // TODO: what about cursor ?
282 //this.cursor = this.vr.moves.length; //to navigate in finished game
284 resign: function(e
) {
285 this.getRidOfTooltip(e
.currentTarget
);
286 if (this.mode
== "human" && this.oppConnected
)
289 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
290 } catch (INVALID_STATE_ERR
) {
291 return; //socket is not ready (and not yet reconnected)
294 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
296 playComputerMove: function() {
297 this.timeStart
= Date
.now();
298 this.compWorker
.postMessage(["askmove"]);
300 animateMove: function(move) {
301 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
302 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
303 let rectStart
= startSquare
.getBoundingClientRect();
304 let rectEnd
= endSquare
.getBoundingClientRect();
305 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
307 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
308 // HACK for animation (with positive translate, image slides "under background")
309 // Possible improvement: just alter squares on the piece's way...
310 squares
= document
.getElementsByClassName("board");
311 for (let i
=0; i
<squares
.length
; i
++)
313 let square
= squares
.item(i
);
314 if (square
.id
!= this.getSquareId(move.start
))
315 square
.style
.zIndex
= "-1";
317 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
318 translation
.y
+ "px)";
319 movingPiece
.style
.transitionDuration
= "0.2s";
320 movingPiece
.style
.zIndex
= "3000";
322 for (let i
=0; i
<squares
.length
; i
++)
323 squares
.item(i
).style
.zIndex
= "auto";
324 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
325 this.play(move); //TODO: plutôt envoyer message "please play"
328 play: function(move, programmatic
) {
329 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
330 if (this.mode
!= "analyze" && this.cursor
< this.moves
.length
-1)
332 let navigate
= !move;
335 if (this.cursor
== this.moves
.length
)
336 return; //no more moves
337 move = this.moves
[this.cursor
];
339 if (!!programmatic
) //computer or human opponent
340 return this.animateMove(move);
341 // Not programmatic, or animation is over
343 move.notation
= this.vr
.getNotation(move);
345 move.color
= this.vr
.turn
;
349 move.fen
= this.vr
.getFen();
351 new Audio("/sounds/move.mp3").play().catch(err
=> {});
352 if (this.mode
== "human")
354 updateStorage(move); //after our moves and opponent moves
355 if (this.vr
.turn
== this.userColor
)
356 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
358 else if (this.mode
== "computer")
360 // Send the move to web worker (including his own moves)
361 this.compWorker
.postMessage(["newmove",move]);
363 if (!navigate
&& (this.score
== "*" || this.mode
== "analyze"))
365 // Stack move on movesList at current cursor
366 if (this.cursor
== this.moves
.length
)
367 this.moves
.push(move);
369 this.moves
= this.moves
.slice(0,this.cursor
-1).concat([move]);
371 // Is opponent in check?
372 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
373 const score
= this.vr
.getCurrentScore();
376 if (["human","computer"].includes(this.mode
))
378 else //just show score on screen (allow undo)
379 this.showScoreMsg(score
);
380 // TODO: notify end of game (give score)
382 else if (this.mode
== "computer" && this.vr
.turn
!= this.userColor
)
383 this.playComputerMove();
385 this.$children
[0].$forceUpdate(); //TODO!?
387 undo: function(move) {
388 let navigate
= !move;
391 if (this.cursor
== 0)
392 return; //no more moves
393 move = this.moves
[this.cursor
-1];
398 this.$children
[0].$forceUpdate(); //TODO!?
400 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
401 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
402 if (!navigate
&& this.mode
== "analyze")
405 this.$forceUpdate(); //TODO!?
407 gotoMove: function(index
) {
408 this.vr
= new VariantRules(this.moves
[index
].fen
);
409 this.cursor
= index
+1;
411 gotoBegin: function() {
412 this.vr
= new VariantRules(this.fenStart
);
415 gotoEnd: function() {
416 this.gotoMove(this.moves
.length
-1);
419 this.orientation
= V
.GetNextCol(this.orientation
);
423 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
424 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
427 //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB