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>
49 <my-chat v-if="showChat"></my-chat>
50 //TODO: connection + turn indicators en haut à droite (superposé au menu)
52 // TODO: controls: abort, clear, resign, draw (avec confirm box)
53 // et si partie terminée : (mode analyse) just clear, back / play
54 // + flip button toujours disponible
56 <div id="pgn-div" class="section-content">
57 <a id="download" href: "#"></a>
58 <button id="downloadBtn" @click="download">
59 {{ translations["Download PGN"] }}
62 <my-move-list v-if="showMoves"></my-move-list>
66 endgameMessage: function() {
67 let eogMessage
= "Unfinished";
68 switch (this.game
.score
)
71 eogMessage
= translations
["White win"];
74 eogMessage
= translations
["Black win"];
77 eogMessage
= translations
["Draw"];
84 const url
= socketUrl
;
85 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
86 // const socketOpenListener = () => {
89 // TODO: after game, archive in indexedDB
91 // TODO: this events listener is central. Refactor ? How ?
92 const socketMessageListener
= msg
=> {
93 const data
= JSON
.parse(msg
.data
);
97 case "newmove": //..he played!
98 this.play(data
.move, (variant
!="Dark" ? "animate" : null));
100 case "pong": //received if we sent a ping (game still alive on our side)
101 if (this.gameId
!= data
.gameId
)
102 break; //games IDs don't match: definitely over...
103 this.oppConnected
= true;
104 // Send our "last state" informations to opponent
105 L
= this.vr
.moves
.length
;
106 this.conn
.send(JSON
.stringify({
110 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
114 case "lastate": //got opponent infos about last move
115 L
= this.vr
.moves
.length
;
116 if (this.gameId
!= data
.gameId
)
117 break; //games IDs don't match: nothing we can do...
118 // OK, opponent still in game (which might be over)
119 if (this.score
!= "*")
121 // We finished the game (any result possible)
122 this.conn
.send(JSON
.stringify({
129 else if (!!data
.score
) //opponent finished the game
130 this.endGame(data
.score
);
131 else if (data
.movesCount
< L
)
133 // We must tell last move to opponent
134 this.conn
.send(JSON
.stringify({
138 lastMove: this.vr
.moves
[L
-1],
142 else if (data
.movesCount
> L
) //just got last move from him
143 this.play(data
.lastMove
, "animate");
145 case "resign": //..you won!
146 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
148 // TODO: also use (dis)connect info to count online players?
151 if (this.mode
=="human" && this.oppid
== data
.id
)
152 this.oppConnected
= (data
.code
== "connect");
153 if (this.oppConnected
&& this.score
!= "*")
155 // Send our name to the opponent, in case of he hasn't it
156 this.conn
.send(JSON
.stringify({
157 code:"myname", name:this.myname
, oppid: this.oppid
}));
163 const socketCloseListener
= () => {
164 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
165 //this.conn.addEventListener('open', socketOpenListener);
166 this.conn
.addEventListener('message', socketMessageListener
);
167 this.conn
.addEventListener('close', socketCloseListener
);
169 //this.conn.onopen = socketOpenListener;
170 this.conn
.onmessage
= socketMessageListener
;
171 this.conn
.onclose
= socketCloseListener
;
174 // Listen to keyboard left/right to navigate in game
175 // TODO: also mouse wheel !
176 document
.onkeydown
= event
=> {
177 if (["human","computer"].includes(this.mode
) &&
178 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
180 event
.preventDefault();
181 if (event
.keyCode
== 37) //Back
189 // Computer moves web worker logic: (TODO: also for observers in HH games)
190 this.compWorker
.postMessage(["scripts",variant
]);
192 this.compWorker
.onmessage = function(e
) {
193 let compMove
= e
.data
;
195 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
196 if (!Array
.isArray(compMove
))
197 compMove
= [compMove
]; //to deal with MarseilleRules
198 // TODO: imperfect attempt to avoid ghost move:
199 compMove
.forEach(m
=> { m
.computer
= true; });
200 // (first move) HACK: small delay to avoid selecting elements
201 // before they appear on page:
202 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
204 const animate
= (variant
!="Dark" ? "animate" : null);
205 if (self
.mode
== "computer") //warning: mode could have changed!
206 self
.play(compMove
[0], animate
);
207 if (compMove
.length
== 2)
209 if (self
.mode
== "computer")
210 self
.play(compMove
[1], animate
);
218 download: function() {
219 // Variants may have special PGN structure (so next function isn't defined here)
220 const content
= V
.GetPGN(this.moves
, this.mycolor
, this.score
, this.fenStart
, this.mode
);
221 // Prepare and trigger download link
222 let downloadAnchor
= document
.getElementById("download");
223 downloadAnchor
.setAttribute("download", "game.pgn");
224 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
225 downloadAnchor
.click();
227 showScoreMsg: function() {
228 let modalBox
= document
.getElementById("modal-eog");
229 modalBox
.checked
= true;
230 setTimeout(() => { modalBox
.checked
= false; }, 2000);
232 endGame: function(score
) {
234 if (["human","computer"].includes(this.mode
))
236 const prefix
= (this.mode
=="computer" ? "comp-" : "");
237 localStorage
.setItem(prefix
+"score", score
);
240 if (this.mode
== "human" && this.oppConnected
)
242 // Send our nickname to opponent
243 this.conn
.send(JSON
.stringify({
244 code:"myname", name:this.myname
, oppid:this.oppid
}));
246 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
248 resign: function(e
) {
249 this.getRidOfTooltip(e
.currentTarget
);
250 if (this.mode
== "human" && this.oppConnected
)
253 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
254 } catch (INVALID_STATE_ERR
) {
255 return; //socket is not ready (and not yet reconnected)
258 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
260 playComputerMove: function() {
261 this.timeStart
= Date
.now();
262 this.compWorker
.postMessage(["askmove"]);
264 // OK, these last functions can stay here (?!)
265 play: function(move, programmatic
) {
268 // Navigate after game is over
269 if (this.cursor
>= this.moves
.length
)
270 return; //already at the end
271 move = this.moves
[this.cursor
++];
273 if (!!programmatic
) //computer or human opponent
274 return this.animateMove(move);
275 // Not programmatic, or animation is over
276 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
277 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
280 // TODO: play move, and stack it on this.moves (if a move was provided; otherwise just navigate)
282 if (this.score
== "*") //TODO: I don't like this if()
284 // Emergency check, if human game started "at the same time"
285 // TODO: robustify this...
286 if (this.mode
== "human" && !!move.computer
)
288 this.vr
.play(move, "ingame");
289 // Is opponent in check?
290 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
292 new Audio("/sounds/move.mp3").play().catch(err
=> {});
293 if (this.mode
== "computer")
295 // Send the move to web worker (TODO: including his own moves?!)
296 this.compWorker
.postMessage(["newmove",move]);
298 const eog
= this.vr
.getCurrentScore();
301 if (["human","computer"].includes(this.mode
))
305 // Just show score on screen (allow undo)
313 // VariantRules.PlayOnBoard(this.vr.board, move);
314 // this.$forceUpdate(); //TODO: ?!
316 if (["human","computer","friend"].includes(this.mode
))
317 this.updateStorage(); //after our moves and opponent moves
318 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
319 this.playComputerMove();
321 // TODO: merge two next functions
323 // Navigate after game is over
324 if (this.cursor
== 0)
325 return; //already at the beginning
326 if (this.cursor
== this.vr
.moves
.length
)
327 this.incheck
= []; //in case of...
328 const move = this.vr
.moves
[--this.cursor
];
329 VariantRules
.UndoOnBoard(this.vr
.board
, move);
330 this.$forceUpdate(); //TODO: ?!
332 undoInGame: function() {
333 const lm
= this.vr
.lastMove
;
338 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
339 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
345 //// TODO: keep moves list here
348 // const L = this.moves.length;
349 // return (L>0 ? this.moves[L-1] : null);
353 // move.notation = this.getNotation(move);
354 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
355 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,