Commit | Line | Data |
---|---|---|
fd373b27 BA |
1 | // TODO: envoyer juste "light move", sans FEN ni notation ...etc |
2 | ||
3 | // Game logic on a variant page: 3 modes, analyze, computer or human | |
1d184b4c | 4 | Vue.component('my-game', { |
fd373b27 BA |
5 | // gameId: to find the game in storage (assumption: it exists) |
6 | props: ["gameId","mode","allowChat","allowMovelist"], | |
1d184b4c BA |
7 | data: function() { |
8 | return { | |
81da2786 | 9 | // if oppid == "computer" then mode = "computer" (otherwise human) |
3a609580 | 10 | myid: "", //our ID, always set |
fd373b27 | 11 | //this.myid = localStorage.getItem("myid") |
1d184b4c | 12 | oppid: "", //opponent ID in case of HH game |
81da2786 BA |
13 | score: "*", //'*' means 'unfinished' |
14 | mycolor: "w", | |
fd373b27 BA |
15 | conn: null, //socket connection (et WebRTC connection ?!) |
16 | oppConnected: false, //TODO? | |
3840e240 | 17 | pgnTxt: "", |
a897b421 | 18 | // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always |
e6dcb115 | 19 | sound: parseInt(localStorage["sound"] || "2"), |
643479f8 BA |
20 | // Web worker to play computer moves without freezing interface: |
21 | compWorker: new Worker('/javascripts/playCompMove.js'), | |
22 | timeStart: undefined, //time when computer starts thinking | |
fd373b27 | 23 | vr: null, //VariantRules object, describing the game state + rules |
1d184b4c BA |
24 | }; |
25 | }, | |
81da2786 | 26 | computed: { |
81da2786 | 27 | showChat: function() { |
fd373b27 | 28 | return this.allowChat && this.mode=='human' && this.score != '*'; |
81da2786 BA |
29 | }, |
30 | showMoves: function() { | |
fd373b27 BA |
31 | return this.allowMovelist && window.innerWidth >= 768; |
32 | }, | |
33 | showFen: function() { | |
34 | return variant.name != "Dark" || this.score != "*"; | |
c794dbb8 BA |
35 | }, |
36 | }, | |
81da2786 | 37 | // Modal end of game, and then sub-components |
fd373b27 BA |
38 | // TODO: provide chat parameters (connection, players ID...) |
39 | // and alwo moveList parameters (just moves ?) | |
40 | // TODO: connection + turn indicators en haut à droite (superposé au menu) | |
41 | // TODO: controls: abort, clear, resign, draw (avec confirm box) | |
42 | // et si partie terminée : (mode analyse) just clear, back / play | |
43 | // + flip button toujours disponible | |
44 | // gotoMove : vr = new VariantRules(fen stocké dans le coup [TODO]) | |
81da2786 BA |
45 | template: ` |
46 | <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2"> | |
47 | <input id="modal-eog" type="checkbox" class="modal"/> | |
48 | <div role="dialog" aria-labelledby="eogMessage"> | |
49 | <div class="card smallpad small-modal text-center"> | |
fd373b27 BA |
50 | <label for="modal-eog" class="modal-close"> |
51 | </label> | |
52 | <h3 id="eogMessage" class="section"> | |
53 | {{ endgameMessage }} | |
54 | </h3> | |
936dc463 BA |
55 | </div> |
56 | </div> | |
fd373b27 BA |
57 | <my-chat v-if="showChat"> |
58 | </my-chat> | |
59 | <my-board v-bind:vr="vr"> | |
60 | </my-board> | |
61 | <div v-show="showFen" id="fen-div" class="section-content"> | |
62 | <p id="fen-string" class="text-center"> | |
63 | {{ vr.getFen() }} | |
64 | </p> | |
65 | </div> | |
81da2786 | 66 | <div id="pgn-div" class="section-content"> |
fd373b27 BA |
67 | <a id="download" href: "#"> |
68 | </a> | |
81da2786 BA |
69 | <button id="downloadBtn" @click="download"> |
70 | {{ translations["Download PGN"] }} | |
71 | </button> | |
fd373b27 BA |
72 | </div> |
73 | <my-move-list v-if="showMoves"> | |
74 | </my-move-list> | |
81da2786 BA |
75 | </div> |
76 | `, | |
1d184b4c BA |
77 | created: function() { |
78 | const url = socketUrl; | |
8d7e2786 | 79 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant._id); |
fd373b27 | 80 | // TODO: after game, archive in indexedDB |
067c675b | 81 | // TODO: this events listener is central. Refactor ? How ? |
d35f20e4 | 82 | const socketMessageListener = msg => { |
1d184b4c | 83 | const data = JSON.parse(msg.data); |
edcd679a | 84 | let L = undefined; |
1d184b4c BA |
85 | switch (data.code) |
86 | { | |
1d184b4c | 87 | case "newmove": //..he played! |
8d7e2786 | 88 | this.play(data.move, (variant.name!="Dark" ? "animate" : null)); |
1d184b4c | 89 | break; |
f3802fcd | 90 | case "pong": //received if we sent a ping (game still alive on our side) |
56a683cd BA |
91 | if (this.gameId != data.gameId) |
92 | break; //games IDs don't match: definitely over... | |
1d184b4c | 93 | this.oppConnected = true; |
f3802fcd | 94 | // Send our "last state" informations to opponent |
edcd679a | 95 | L = this.vr.moves.length; |
a29d9d6b | 96 | this.conn.send(JSON.stringify({ |
56a683cd BA |
97 | code: "lastate", |
98 | oppid: this.oppid, | |
99 | gameId: this.gameId, | |
100 | lastMove: (L>0?this.vr.moves[L-1]:undefined), | |
101 | movesCount: L, | |
a29d9d6b | 102 | })); |
1d184b4c | 103 | break; |
56a683cd | 104 | case "lastate": //got opponent infos about last move |
edcd679a | 105 | L = this.vr.moves.length; |
56a683cd BA |
106 | if (this.gameId != data.gameId) |
107 | break; //games IDs don't match: nothing we can do... | |
108 | // OK, opponent still in game (which might be over) | |
edcd679a | 109 | if (this.score != "*") |
a29d9d6b | 110 | { |
56a683cd | 111 | // We finished the game (any result possible) |
a29d9d6b | 112 | this.conn.send(JSON.stringify({ |
56a683cd BA |
113 | code: "lastate", |
114 | oppid: data.oppid, | |
115 | gameId: this.gameId, | |
116 | score: this.score, | |
a29d9d6b BA |
117 | })); |
118 | } | |
56a683cd BA |
119 | else if (!!data.score) //opponent finished the game |
120 | this.endGame(data.score); | |
121 | else if (data.movesCount < L) | |
a29d9d6b BA |
122 | { |
123 | // We must tell last move to opponent | |
a29d9d6b | 124 | this.conn.send(JSON.stringify({ |
56a683cd BA |
125 | code: "lastate", |
126 | oppid: this.oppid, | |
edcd679a | 127 | gameId: this.gameId, |
56a683cd BA |
128 | lastMove: this.vr.moves[L-1], |
129 | movesCount: L, | |
a29d9d6b BA |
130 | })); |
131 | } | |
56a683cd | 132 | else if (data.movesCount > L) //just got last move from him |
a29d9d6b | 133 | this.play(data.lastMove, "animate"); |
ecf44502 | 134 | break; |
1d184b4c | 135 | case "resign": //..you won! |
dfb4afc1 | 136 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); |
1d184b4c | 137 | break; |
f3802fcd | 138 | // TODO: also use (dis)connect info to count online players? |
1d184b4c BA |
139 | case "connect": |
140 | case "disconnect": | |
4f7723a1 | 141 | if (this.mode=="human" && this.oppid == data.id) |
1d184b4c | 142 | this.oppConnected = (data.code == "connect"); |
4f7723a1 | 143 | if (this.oppConnected && this.score != "*") |
3a609580 BA |
144 | { |
145 | // Send our name to the opponent, in case of he hasn't it | |
146 | this.conn.send(JSON.stringify({ | |
147 | code:"myname", name:this.myname, oppid: this.oppid})); | |
148 | } | |
1d184b4c BA |
149 | break; |
150 | } | |
151 | }; | |
067c675b | 152 | |
d35f20e4 | 153 | const socketCloseListener = () => { |
8d7e2786 | 154 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant._id); |
d35f20e4 BA |
155 | this.conn.addEventListener('message', socketMessageListener); |
156 | this.conn.addEventListener('close', socketCloseListener); | |
157 | }; | |
d35f20e4 BA |
158 | this.conn.onmessage = socketMessageListener; |
159 | this.conn.onclose = socketCloseListener; | |
81da2786 | 160 | |
067c675b | 161 | // Computer moves web worker logic: (TODO: also for observers in HH games) |
8d7e2786 | 162 | this.compWorker.postMessage(["scripts",variant.name]); |
643479f8 BA |
163 | const self = this; |
164 | this.compWorker.onmessage = function(e) { | |
aa78cc74 | 165 | let compMove = e.data; |
78bab51e BA |
166 | if (!compMove) |
167 | return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...) | |
6e62b1c7 BA |
168 | if (!Array.isArray(compMove)) |
169 | compMove = [compMove]; //to deal with MarseilleRules | |
170 | // TODO: imperfect attempt to avoid ghost move: | |
171 | compMove.forEach(m => { m.computer = true; }); | |
643479f8 BA |
172 | // (first move) HACK: small delay to avoid selecting elements |
173 | // before they appear on page: | |
174 | const delay = Math.max(500-(Date.now()-self.timeStart), 0); | |
175 | setTimeout(() => { | |
8d7e2786 | 176 | const animate = (variant.name!="Dark" ? "animate" : null); |
aa78cc74 | 177 | if (self.mode == "computer") //warning: mode could have changed! |
5915f720 | 178 | self.play(compMove[0], animate); |
6e62b1c7 BA |
179 | if (compMove.length == 2) |
180 | setTimeout( () => { | |
181 | if (self.mode == "computer") | |
5915f720 | 182 | self.play(compMove[1], animate); |
78bab51e | 183 | }, 750); |
643479f8 BA |
184 | }, delay); |
185 | } | |
1d184b4c | 186 | }, |
fd373b27 BA |
187 | //TODO: conn pourrait être une prop, donnée depuis variant.js |
188 | //dans variant.js (plutôt room.js) conn gère aussi les challenges | |
189 | // Puis en webRTC, repenser tout ça. | |
81da2786 | 190 | methods: { |
fd373b27 BA |
191 | setEndgameMessage: function(score) { |
192 | let eogMessage = "Undefined"; | |
193 | switch (score) | |
194 | { | |
195 | case "1-0": | |
196 | eogMessage = translations["White win"]; | |
197 | break; | |
198 | case "0-1": | |
199 | eogMessage = translations["Black win"]; | |
200 | break; | |
201 | case "1/2": | |
202 | eogMessage = translations["Draw"]; | |
203 | break; | |
204 | case "?": | |
205 | eogMessage = "Unfinished"; | |
206 | break; | |
207 | } | |
208 | this.endgameMessage = eogMessage; | |
209 | }, | |
01ca2adc | 210 | download: function() { |
edcd679a | 211 | // Variants may have special PGN structure (so next function isn't defined here) |
fd373b27 BA |
212 | // TODO: get fenStart from local game (using gameid) |
213 | const content = V.GetPGN(this.moves, this.mycolor, this.score, fenStart, this.mode); | |
01ca2adc BA |
214 | // Prepare and trigger download link |
215 | let downloadAnchor = document.getElementById("download"); | |
216 | downloadAnchor.setAttribute("download", "game.pgn"); | |
edcd679a | 217 | downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content); |
01ca2adc BA |
218 | downloadAnchor.click(); |
219 | }, | |
fd373b27 BA |
220 | showScoreMsg: function(score) { |
221 | this.setEndgameMessage(score); | |
ecf44502 | 222 | let modalBox = document.getElementById("modal-eog"); |
186516b8 | 223 | modalBox.checked = true; |
1a788978 BA |
224 | setTimeout(() => { modalBox.checked = false; }, 2000); |
225 | }, | |
226 | endGame: function(score) { | |
227 | this.score = score; | |
56a683cd BA |
228 | if (["human","computer"].includes(this.mode)) |
229 | { | |
230 | const prefix = (this.mode=="computer" ? "comp-" : ""); | |
231 | localStorage.setItem(prefix+"score", score); | |
232 | } | |
fd373b27 | 233 | this.showScoreMsg(score); |
3a609580 BA |
234 | if (this.mode == "human" && this.oppConnected) |
235 | { | |
236 | // Send our nickname to opponent | |
237 | this.conn.send(JSON.stringify({ | |
238 | code:"myname", name:this.myname, oppid:this.oppid})); | |
239 | } | |
fd373b27 BA |
240 | // TODO: what about cursor ? |
241 | //this.cursor = this.vr.moves.length; //to navigate in finished game | |
1d184b4c | 242 | }, |
067c675b BA |
243 | resign: function(e) { |
244 | this.getRidOfTooltip(e.currentTarget); | |
245 | if (this.mode == "human" && this.oppConnected) | |
246 | { | |
247 | try { | |
248 | this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid})); | |
249 | } catch (INVALID_STATE_ERR) { | |
250 | return; //socket is not ready (and not yet reconnected) | |
251 | } | |
252 | } | |
253 | this.endGame(this.mycolor=="w"?"0-1":"1-0"); | |
254 | }, | |
1d184b4c | 255 | playComputerMove: function() { |
643479f8 BA |
256 | this.timeStart = Date.now(); |
257 | this.compWorker.postMessage(["askmove"]); | |
1d184b4c | 258 | }, |
fd373b27 BA |
259 | animateMove: function(move) { |
260 | let startSquare = document.getElementById(this.getSquareId(move.start)); | |
261 | let endSquare = document.getElementById(this.getSquareId(move.end)); | |
262 | let rectStart = startSquare.getBoundingClientRect(); | |
263 | let rectEnd = endSquare.getBoundingClientRect(); | |
264 | let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y}; | |
265 | let movingPiece = | |
266 | document.querySelector("#" + this.getSquareId(move.start) + " > img.piece"); | |
267 | // HACK for animation (with positive translate, image slides "under background") | |
268 | // Possible improvement: just alter squares on the piece's way... | |
269 | squares = document.getElementsByClassName("board"); | |
270 | for (let i=0; i<squares.length; i++) | |
271 | { | |
272 | let square = squares.item(i); | |
273 | if (square.id != this.getSquareId(move.start)) | |
274 | square.style.zIndex = "-1"; | |
275 | } | |
276 | movingPiece.style.transform = "translate(" + translation.x + "px," + | |
277 | translation.y + "px)"; | |
278 | movingPiece.style.transitionDuration = "0.2s"; | |
279 | movingPiece.style.zIndex = "3000"; | |
280 | setTimeout( () => { | |
281 | for (let i=0; i<squares.length; i++) | |
282 | squares.item(i).style.zIndex = "auto"; | |
283 | movingPiece.style = {}; //required e.g. for 0-0 with KR swap | |
284 | this.play(move); //TODO: plutôt envoyer message "please play" | |
285 | }, 250); | |
286 | }, | |
287 | play: function(move, programmatic) { | |
288 | if (!!programmatic) //computer or human opponent | |
289 | return this.animateMove(move); | |
290 | // Not programmatic, or animation is over | |
291 | if (!move.notation) | |
292 | move.notation = this.vr.getNotation(move); | |
293 | this.vr.play(move); | |
294 | if (!move.fen) | |
295 | move.fen = this.vr.getFen(); | |
296 | if (this.sound == 2) | |
297 | new Audio("/sounds/move.mp3").play().catch(err => {}); | |
298 | if (this.mode == "human") | |
299 | { | |
300 | updateStorage(move); //after our moves and opponent moves | |
301 | if (this.vr.turn == this.userColor) | |
302 | this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid})); | |
303 | } | |
304 | else if (this.mode == "computer") | |
305 | { | |
306 | // Send the move to web worker (including his own moves) | |
307 | this.compWorker.postMessage(["newmove",move]); | |
308 | } | |
309 | if (this.score == "*" || this.mode == "analyze") | |
310 | { | |
311 | // Stack move on movesList | |
312 | this.moves.push(move); | |
313 | } | |
314 | // Is opponent in check? | |
315 | this.incheck = this.vr.getCheckSquares(this.vr.turn); | |
316 | const score = this.vr.getCurrentScore(); | |
317 | if (score != "*") | |
318 | { | |
319 | if (["human","computer"].includes(this.mode)) | |
320 | this.endGame(score); | |
321 | else //just show score on screen (allow undo) | |
322 | this.showScoreMsg(score); | |
323 | // TODO: notify end of game (give score) | |
324 | } | |
325 | else if (this.mode == "computer" && this.vr.turn != this.userColor) | |
326 | this.playComputerMove(); | |
327 | }, | |
328 | undo: function(move) { | |
329 | this.vr.undo(move); | |
330 | if (this.sound == 2) | |
331 | new Audio("/sounds/undo.mp3").play().catch(err => {}); | |
332 | this.incheck = this.vr.getCheckSquares(this.vr.turn); | |
333 | if (this.mode == "analyze") | |
334 | this.moves.pop(); | |
335 | }, | |
1d184b4c BA |
336 | }, |
337 | }) | |
fd373b27 | 338 | // cursor + ........ |
067c675b BA |
339 | //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle" |
340 | //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions, | |
341 | //comme sur lichess | |
fd373b27 BA |
342 | // |
343 | //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB |