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
57 // Show current FEN (just below board, lower right corner)
58 // (if mode != Dark ...)
62 attrs: { id: "fen-div" },
63 "class": { "section-content": true },
68 attrs: { id: "fen-string" },
69 domProps: { innerHTML: this.vr.getBaseFen() },
70 "class": { "text-center": true },
77 <div id="pgn-div" class="section-content">
78 <a id="download" href: "#"></a>
79 <button id="downloadBtn" @click="download">
80 {{ translations["Download PGN"] }}
83 <my-move-list v-if="showMoves"></my-move-list>
87 endgameMessage: function() {
88 let eogMessage
= "Unfinished";
89 switch (this.game
.score
)
92 eogMessage
= translations
["White win"];
95 eogMessage
= translations
["Black win"];
98 eogMessage
= translations
["Draw"];
104 created: function() {
105 const url
= socketUrl
;
106 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
._id
);
107 // const socketOpenListener = () => {
110 // TODO: after game, archive in indexedDB
112 // TODO: this events listener is central. Refactor ? How ?
113 const socketMessageListener
= msg
=> {
114 const data
= JSON
.parse(msg
.data
);
118 case "newmove": //..he played!
119 this.play(data
.move, (variant
.name
!="Dark" ? "animate" : null));
121 case "pong": //received if we sent a ping (game still alive on our side)
122 if (this.gameId
!= data
.gameId
)
123 break; //games IDs don't match: definitely over...
124 this.oppConnected
= true;
125 // Send our "last state" informations to opponent
126 L
= this.vr
.moves
.length
;
127 this.conn
.send(JSON
.stringify({
131 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
135 case "lastate": //got opponent infos about last move
136 L
= this.vr
.moves
.length
;
137 if (this.gameId
!= data
.gameId
)
138 break; //games IDs don't match: nothing we can do...
139 // OK, opponent still in game (which might be over)
140 if (this.score
!= "*")
142 // We finished the game (any result possible)
143 this.conn
.send(JSON
.stringify({
150 else if (!!data
.score
) //opponent finished the game
151 this.endGame(data
.score
);
152 else if (data
.movesCount
< L
)
154 // We must tell last move to opponent
155 this.conn
.send(JSON
.stringify({
159 lastMove: this.vr
.moves
[L
-1],
163 else if (data
.movesCount
> L
) //just got last move from him
164 this.play(data
.lastMove
, "animate");
166 case "resign": //..you won!
167 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
169 // TODO: also use (dis)connect info to count online players?
172 if (this.mode
=="human" && this.oppid
== data
.id
)
173 this.oppConnected
= (data
.code
== "connect");
174 if (this.oppConnected
&& this.score
!= "*")
176 // Send our name to the opponent, in case of he hasn't it
177 this.conn
.send(JSON
.stringify({
178 code:"myname", name:this.myname
, oppid: this.oppid
}));
184 const socketCloseListener
= () => {
185 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
._id
);
186 //this.conn.addEventListener('open', socketOpenListener);
187 this.conn
.addEventListener('message', socketMessageListener
);
188 this.conn
.addEventListener('close', socketCloseListener
);
190 //this.conn.onopen = socketOpenListener;
191 this.conn
.onmessage
= socketMessageListener
;
192 this.conn
.onclose
= socketCloseListener
;
195 // Listen to keyboard left/right to navigate in game
196 // TODO: also mouse wheel !
197 document
.onkeydown
= event
=> {
198 if (["human","computer"].includes(this.mode
) &&
199 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
201 event
.preventDefault();
202 if (event
.keyCode
== 37) //Back
210 // Computer moves web worker logic: (TODO: also for observers in HH games)
211 this.compWorker
.postMessage(["scripts",variant
.name
]);
213 this.compWorker
.onmessage = function(e
) {
214 let compMove
= e
.data
;
216 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
217 if (!Array
.isArray(compMove
))
218 compMove
= [compMove
]; //to deal with MarseilleRules
219 // TODO: imperfect attempt to avoid ghost move:
220 compMove
.forEach(m
=> { m
.computer
= true; });
221 // (first move) HACK: small delay to avoid selecting elements
222 // before they appear on page:
223 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
225 const animate
= (variant
.name
!="Dark" ? "animate" : null);
226 if (self
.mode
== "computer") //warning: mode could have changed!
227 self
.play(compMove
[0], animate
);
228 if (compMove
.length
== 2)
230 if (self
.mode
== "computer")
231 self
.play(compMove
[1], animate
);
239 download: function() {
240 // Variants may have special PGN structure (so next function isn't defined here)
241 const content
= V
.GetPGN(this.moves
, this.mycolor
, this.score
, this.fenStart
, this.mode
);
242 // Prepare and trigger download link
243 let downloadAnchor
= document
.getElementById("download");
244 downloadAnchor
.setAttribute("download", "game.pgn");
245 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
246 downloadAnchor
.click();
248 showScoreMsg: function() {
249 let modalBox
= document
.getElementById("modal-eog");
250 modalBox
.checked
= true;
251 setTimeout(() => { modalBox
.checked
= false; }, 2000);
253 endGame: function(score
) {
255 if (["human","computer"].includes(this.mode
))
257 const prefix
= (this.mode
=="computer" ? "comp-" : "");
258 localStorage
.setItem(prefix
+"score", score
);
261 if (this.mode
== "human" && this.oppConnected
)
263 // Send our nickname to opponent
264 this.conn
.send(JSON
.stringify({
265 code:"myname", name:this.myname
, oppid:this.oppid
}));
267 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
269 resign: function(e
) {
270 this.getRidOfTooltip(e
.currentTarget
);
271 if (this.mode
== "human" && this.oppConnected
)
274 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
275 } catch (INVALID_STATE_ERR
) {
276 return; //socket is not ready (and not yet reconnected)
279 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
281 playComputerMove: function() {
282 this.timeStart
= Date
.now();
283 this.compWorker
.postMessage(["askmove"]);
285 // OK, these last functions can stay here (?!)
289 //// TODO: keep moves list here
292 // const L = this.moves.length;
293 // return (L>0 ? this.moves[L-1] : null);
297 // move.notation = this.getNotation(move);
298 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
299 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
302 // send move from here:
303 //if (this.mode == "human" && this.vr.turn == this.mycolor)
304 //this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
305 // TODO: play move, and stack it on this.moves (if a move was provided; otherwise just navigate)
307 // if (["human","computer","friend"].includes(this.mode))
308 // this.updateStorage(); //after our moves and opponent moves
309 // if (this.mode == "computer" && this.vr.turn != this.mycolor && this.score == "*")
310 // this.playComputerMove();
311 // if (this.mode == "computer")
313 // // Send the move to web worker (TODO: including his own moves?!)
314 // this.compWorker.postMessage(["newmove",move]);
316 // if (["human","computer"].includes(this.mode))
317 // this.endGame(eog);
320 // // Just show score on screen (allow undo)
322 // this.showScoreMsg();