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