1 // Game logic on a variant page
2 Vue
.component('my-game', {
3 props: ["gameId"], //to find the game in storage (assumption: it exists)
7 // TODO: merge next variables into "game"
8 // if oppid == "computer" then mode = "computer" (otherwise human)
9 myid: "", //our ID, always set
10 //this.myid = localStorage.getItem("myid")
11 oppid: "", //opponent ID in case of HH game
12 score: "*", //'*' means 'unfinished'
14 fromChallenge: false, //if true, show chat during game
16 conn: null, //socket connection
21 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
22 sound: parseInt(localStorage
["sound"] || "2"),
23 // Web worker to play computer moves without freezing interface:
24 compWorker: new Worker('/javascripts/playCompMove.js'),
25 timeStart: undefined, //time when computer starts thinking
30 return (this.game
.oppid
== "computer" ? "computer" ? "human");
32 showChat: function() {
33 return this.mode
=='human' &&
34 (this.game
.score
!= '*' || this.game
.fromChallenge
);
36 showMoves: function() {
37 return window
.innerWidth
>= 768;
40 // Modal end of game, and then sub-components
42 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
43 <input id="modal-eog" type="checkbox" class="modal"/>
44 <div role="dialog" aria-labelledby="eogMessage">
45 <div class="card smallpad small-modal text-center">
46 <label for="modal-eog" class="modal-close"></label>
47 <h3 id="eogMessage" class="section">{{ endgameMessage }}</h3>
51 <my-chat v-if="showChat"></my-chat>
52 //TODO: connection + turn indicators en haut à droite (superposé au menu)
54 // TODO: controls: abort, clear, resign, draw (avec confirm box)
55 // et si partie terminée : (mode analyse) just clear, back / play
56 // + flip button toujours disponible
58 <div id="pgn-div" class="section-content">
59 <a id="download" href: "#"></a>
60 <button id="downloadBtn" @click="download">
61 {{ translations["Download PGN"] }}
64 <my-move-list v-if="showMoves"></my-move-list>
68 endgameMessage: function() {
69 let eogMessage
= "Unfinished";
70 switch (this.game
.score
)
73 eogMessage
= translations
["White win"];
76 eogMessage
= translations
["Black win"];
79 eogMessage
= translations
["Draw"];
86 const url
= socketUrl
;
87 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
._id
);
88 // const socketOpenListener = () => {
91 // TODO: after game, archive in indexedDB
93 // TODO: this events listener is central. Refactor ? How ?
94 const socketMessageListener
= msg
=> {
95 const data
= JSON
.parse(msg
.data
);
99 case "newmove": //..he played!
100 this.play(data
.move, (variant
.name
!="Dark" ? "animate" : null));
102 case "pong": //received if we sent a ping (game still alive on our side)
103 if (this.gameId
!= data
.gameId
)
104 break; //games IDs don't match: definitely over...
105 this.oppConnected
= true;
106 // Send our "last state" informations to opponent
107 L
= this.vr
.moves
.length
;
108 this.conn
.send(JSON
.stringify({
112 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
116 case "lastate": //got opponent infos about last move
117 L
= this.vr
.moves
.length
;
118 if (this.gameId
!= data
.gameId
)
119 break; //games IDs don't match: nothing we can do...
120 // OK, opponent still in game (which might be over)
121 if (this.score
!= "*")
123 // We finished the game (any result possible)
124 this.conn
.send(JSON
.stringify({
131 else if (!!data
.score
) //opponent finished the game
132 this.endGame(data
.score
);
133 else if (data
.movesCount
< L
)
135 // We must tell last move to opponent
136 this.conn
.send(JSON
.stringify({
140 lastMove: this.vr
.moves
[L
-1],
144 else if (data
.movesCount
> L
) //just got last move from him
145 this.play(data
.lastMove
, "animate");
147 case "resign": //..you won!
148 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
150 // TODO: also use (dis)connect info to count online players?
153 if (this.mode
=="human" && this.oppid
== data
.id
)
154 this.oppConnected
= (data
.code
== "connect");
155 if (this.oppConnected
&& this.score
!= "*")
157 // Send our name to the opponent, in case of he hasn't it
158 this.conn
.send(JSON
.stringify({
159 code:"myname", name:this.myname
, oppid: this.oppid
}));
165 const socketCloseListener
= () => {
166 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
._id
);
167 //this.conn.addEventListener('open', socketOpenListener);
168 this.conn
.addEventListener('message', socketMessageListener
);
169 this.conn
.addEventListener('close', socketCloseListener
);
171 //this.conn.onopen = socketOpenListener;
172 this.conn
.onmessage
= socketMessageListener
;
173 this.conn
.onclose
= socketCloseListener
;
176 // Listen to keyboard left/right to navigate in game
177 // TODO: also mouse wheel !
178 document
.onkeydown
= event
=> {
179 if (["human","computer"].includes(this.mode
) &&
180 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
182 event
.preventDefault();
183 if (event
.keyCode
== 37) //Back
191 // Computer moves web worker logic: (TODO: also for observers in HH games)
192 this.compWorker
.postMessage(["scripts",variant
.name
]);
194 this.compWorker
.onmessage = function(e
) {
195 let compMove
= e
.data
;
197 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
198 if (!Array
.isArray(compMove
))
199 compMove
= [compMove
]; //to deal with MarseilleRules
200 // TODO: imperfect attempt to avoid ghost move:
201 compMove
.forEach(m
=> { m
.computer
= true; });
202 // (first move) HACK: small delay to avoid selecting elements
203 // before they appear on page:
204 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
206 const animate
= (variant
.name
!="Dark" ? "animate" : null);
207 if (self
.mode
== "computer") //warning: mode could have changed!
208 self
.play(compMove
[0], animate
);
209 if (compMove
.length
== 2)
211 if (self
.mode
== "computer")
212 self
.play(compMove
[1], animate
);
220 download: function() {
221 // Variants may have special PGN structure (so next function isn't defined here)
222 const content
= V
.GetPGN(this.moves
, this.mycolor
, this.score
, this.fenStart
, this.mode
);
223 // Prepare and trigger download link
224 let downloadAnchor
= document
.getElementById("download");
225 downloadAnchor
.setAttribute("download", "game.pgn");
226 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
227 downloadAnchor
.click();
229 showScoreMsg: function() {
230 let modalBox
= document
.getElementById("modal-eog");
231 modalBox
.checked
= true;
232 setTimeout(() => { modalBox
.checked
= false; }, 2000);
234 endGame: function(score
) {
236 if (["human","computer"].includes(this.mode
))
238 const prefix
= (this.mode
=="computer" ? "comp-" : "");
239 localStorage
.setItem(prefix
+"score", score
);
242 if (this.mode
== "human" && this.oppConnected
)
244 // Send our nickname to opponent
245 this.conn
.send(JSON
.stringify({
246 code:"myname", name:this.myname
, oppid:this.oppid
}));
248 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
250 resign: function(e
) {
251 this.getRidOfTooltip(e
.currentTarget
);
252 if (this.mode
== "human" && this.oppConnected
)
255 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
256 } catch (INVALID_STATE_ERR
) {
257 return; //socket is not ready (and not yet reconnected)
260 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
262 playComputerMove: function() {
263 this.timeStart
= Date
.now();
264 this.compWorker
.postMessage(["askmove"]);
266 // OK, these last functions can stay here (?!)
267 play: function(move, programmatic
) {
270 // Navigate after game is over
271 if (this.cursor
>= this.moves
.length
)
272 return; //already at the end
273 move = this.moves
[this.cursor
++];
275 if (!!programmatic
) //computer or human opponent
276 return this.animateMove(move);
277 // Not programmatic, or animation is over
278 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
279 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
282 // TODO: play move, and stack it on this.moves (if a move was provided; otherwise just navigate)
284 if (this.score
== "*") //TODO: I don't like this if()
286 // Emergency check, if human game started "at the same time"
287 // TODO: robustify this...
288 if (this.mode
== "human" && !!move.computer
)
290 this.vr
.play(move, "ingame");
291 // Is opponent in check?
292 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
294 new Audio("/sounds/move.mp3").play().catch(err
=> {});
295 if (this.mode
== "computer")
297 // Send the move to web worker (TODO: including his own moves?!)
298 this.compWorker
.postMessage(["newmove",move]);
300 const eog
= this.vr
.getCurrentScore();
303 if (["human","computer"].includes(this.mode
))
307 // Just show score on screen (allow undo)
315 // VariantRules.PlayOnBoard(this.vr.board, move);
316 // this.$forceUpdate(); //TODO: ?!
318 if (["human","computer","friend"].includes(this.mode
))
319 this.updateStorage(); //after our moves and opponent moves
320 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
321 this.playComputerMove();
323 // TODO: merge two next functions
325 // Navigate after game is over
326 if (this.cursor
== 0)
327 return; //already at the beginning
328 if (this.cursor
== this.vr
.moves
.length
)
329 this.incheck
= []; //in case of...
330 const move = this.vr
.moves
[--this.cursor
];
331 VariantRules
.UndoOnBoard(this.vr
.board
, move);
332 this.$forceUpdate(); //TODO: ?!
334 undoInGame: function() {
335 const lm
= this.vr
.lastMove
;
340 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
341 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
347 //// TODO: keep moves list here
350 // const L = this.moves.length;
351 // return (L>0 ? this.moves[L-1] : null);
355 // move.notation = this.getNotation(move);
356 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
357 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,