Commit | Line | Data |
---|---|---|
1d184b4c BA |
1 | Vue.component('my-game', { |
2 | data: function() { | |
3 | return { | |
4 | vr: null, //object to check moves, store them, FEN.. | |
5 | mycolor: "w", | |
6 | possibleMoves: [], //filled after each valid click/dragstart | |
7 | choices: [], //promotion pieces, or checkered captures... (contain possible pieces) | |
8 | start: {}, //pixels coordinates + id of starting square (click or drag) | |
9 | selectedPiece: null, //moving piece (or clicked piece) | |
10 | conn: null, //socket messages | |
dfb4afc1 | 11 | score: "*", //'*' means 'unfinished' |
1d184b4c BA |
12 | mode: "idle", //human, computer or idle (when not playing) |
13 | oppid: "", //opponent ID in case of HH game | |
14 | oppConnected: false, | |
186516b8 | 15 | seek: false, |
762b7c9c | 16 | fenStart: "", |
4b5fe306 | 17 | incheck: [], |
3840e240 | 18 | pgnTxt: "", |
3ed62725 | 19 | expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false, |
efb20746 | 20 | gameId: "", //used to limit computer moves' time |
1d184b4c BA |
21 | }; |
22 | }, | |
23 | render(h) { | |
c94bc812 | 24 | const [sizeX,sizeY] = VariantRules.size; |
1d184b4c BA |
25 | // Precompute hints squares to facilitate rendering |
26 | let hintSquares = doubleArray(sizeX, sizeY, false); | |
27 | this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; }); | |
4b5fe306 BA |
28 | // Also precompute in-check squares |
29 | let incheckSq = doubleArray(sizeX, sizeY, false); | |
30 | this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; }); | |
1d184b4c | 31 | let elementArray = []; |
186516b8 BA |
32 | const playingHuman = (this.mode == "human"); |
33 | const playingComp = (this.mode == "computer"); | |
1d184b4c BA |
34 | let actionArray = [ |
35 | h('button', | |
36 | { | |
f3802fcd | 37 | on: { click: this.clickGameSeek }, |
1d184b4c | 38 | attrs: { "aria-label": 'New game VS human' }, |
186516b8 BA |
39 | 'class': { |
40 | "tooltip": true, | |
0706ea91 | 41 | "bottom": true, //display below |
186516b8 BA |
42 | "seek": this.seek, |
43 | "playing": playingHuman, | |
44 | }, | |
1d184b4c BA |
45 | }, |
46 | [h('i', { 'class': { "material-icons": true } }, "accessibility")]), | |
47 | h('button', | |
48 | { | |
f3802fcd | 49 | on: { click: this.clickComputerGame }, |
1d184b4c | 50 | attrs: { "aria-label": 'New game VS computer' }, |
186516b8 BA |
51 | 'class': { |
52 | "tooltip":true, | |
0706ea91 | 53 | "bottom": true, |
186516b8 BA |
54 | "playing": playingComp, |
55 | }, | |
1d184b4c BA |
56 | }, |
57 | [h('i', { 'class': { "material-icons": true } }, "computer")]) | |
58 | ]; | |
59 | if (!!this.vr) | |
60 | { | |
bdb1f12d BA |
61 | const square00 = document.getElementById("sq-0-0"); |
62 | const squareWidth = !!square00 | |
63 | ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2)) | |
64 | : 0; | |
65 | const indicWidth = (squareWidth>0 ? squareWidth/2 : 20); | |
1d184b4c BA |
66 | if (this.mode == "human") |
67 | { | |
68 | let connectedIndic = h( | |
69 | 'div', | |
70 | { | |
71 | "class": { | |
bdb1f12d BA |
72 | "topindicator": true, |
73 | "indic-left": true, | |
1d184b4c BA |
74 | "connected": this.oppConnected, |
75 | "disconnected": !this.oppConnected, | |
76 | }, | |
bdb1f12d BA |
77 | style: { |
78 | "width": indicWidth + "px", | |
79 | "height": indicWidth + "px", | |
80 | }, | |
1d184b4c BA |
81 | } |
82 | ); | |
83 | elementArray.push(connectedIndic); | |
84 | } | |
bdb1f12d BA |
85 | let turnIndic = h( |
86 | 'div', | |
87 | { | |
88 | "class": { | |
89 | "topindicator": true, | |
90 | "indic-right": true, | |
91 | "white-turn": this.vr.turn=="w", | |
92 | "black-turn": this.vr.turn=="b", | |
93 | }, | |
94 | style: { | |
95 | "width": indicWidth + "px", | |
96 | "height": indicWidth + "px", | |
97 | }, | |
98 | } | |
99 | ); | |
100 | elementArray.push(turnIndic); | |
3ed62725 BA |
101 | let expertSwitch = h( |
102 | 'button', | |
103 | { | |
104 | on: { click: this.toggleExpertMode }, | |
105 | attrs: { "aria-label": 'Toggle expert mode' }, | |
106 | 'class': { | |
107 | "tooltip":true, | |
108 | "topindicator": true, | |
109 | "indic-right": true, | |
110 | "expert-switch": true, | |
111 | "expert-mode": this.expert, | |
112 | }, | |
113 | }, | |
114 | [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")] | |
115 | ); | |
116 | elementArray.push(expertSwitch); | |
1d184b4c BA |
117 | let choices = h('div', |
118 | { | |
119 | attrs: { "id": "choices" }, | |
120 | 'class': { 'row': true }, | |
121 | style: { | |
1d184b4c BA |
122 | "display": this.choices.length>0?"block":"none", |
123 | "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px", | |
124 | "width": (this.choices.length * squareWidth) + "px", | |
125 | "height": squareWidth + "px", | |
126 | }, | |
127 | }, | |
128 | this.choices.map( m => { //a "choice" is a move | |
129 | return h('div', | |
130 | { | |
c94bc812 BA |
131 | 'class': { |
132 | 'board': true, | |
8a196305 | 133 | ['board'+sizeY]: true, |
c94bc812 | 134 | }, |
1d184b4c BA |
135 | style: { |
136 | 'width': (100/this.choices.length) + "%", | |
137 | 'padding-bottom': (100/this.choices.length) + "%", | |
138 | }, | |
139 | }, | |
140 | [h('img', | |
141 | { | |
4b353936 BA |
142 | attrs: { "src": '/images/pieces/' + |
143 | VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' }, | |
c94bc812 | 144 | 'class': { 'choice-piece': true }, |
1d184b4c BA |
145 | on: { "click": e => { this.play(m); this.choices=[]; } }, |
146 | }) | |
147 | ] | |
148 | ); | |
149 | }) | |
150 | ); | |
151 | // Create board element (+ reserves if needed by variant or mode) | |
152 | let gameDiv = h('div', | |
153 | { | |
154 | 'class': { 'game': true }, | |
155 | }, | |
156 | [_.range(sizeX).map(i => { | |
157 | let ci = this.mycolor=='w' ? i : sizeX-i-1; | |
158 | return h( | |
159 | 'div', | |
160 | { | |
161 | 'class': { | |
162 | 'row': true, | |
163 | }, | |
164 | style: { 'opacity': this.choices.length>0?"0.5":"1" }, | |
165 | }, | |
166 | _.range(sizeY).map(j => { | |
167 | let cj = this.mycolor=='w' ? j : sizeY-j-1; | |
168 | let elems = []; | |
169 | if (this.vr.board[ci][cj] != VariantRules.EMPTY) | |
170 | { | |
171 | elems.push( | |
172 | h( | |
173 | 'img', | |
174 | { | |
175 | 'class': { | |
176 | 'piece': true, | |
4b353936 BA |
177 | 'ghost': !!this.selectedPiece |
178 | && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj, | |
1d184b4c BA |
179 | }, |
180 | attrs: { | |
4b353936 BA |
181 | src: "/images/pieces/" + |
182 | VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg", | |
1d184b4c BA |
183 | }, |
184 | } | |
185 | ) | |
186 | ); | |
187 | } | |
3ed62725 | 188 | if (!this.expert && hintSquares[ci][cj]) |
1d184b4c BA |
189 | { |
190 | elems.push( | |
191 | h( | |
192 | 'img', | |
193 | { | |
194 | 'class': { | |
195 | 'mark-square': true, | |
196 | }, | |
197 | attrs: { | |
198 | src: "/images/mark.svg", | |
199 | }, | |
200 | } | |
201 | ) | |
202 | ); | |
203 | } | |
30ff6e04 | 204 | const lm = this.vr.lastMove; |
e64a4eff | 205 | const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj}); |
1d184b4c BA |
206 | return h( |
207 | 'div', | |
208 | { | |
209 | 'class': { | |
210 | 'board': true, | |
8a196305 | 211 | ['board'+sizeY]: true, |
3ed62725 BA |
212 | 'light-square': (i+j)%2==0 && (this.expert || !highlight), |
213 | 'dark-square': (i+j)%2==1 && (this.expert || !highlight), | |
214 | 'highlight': !this.expert && highlight, | |
215 | 'incheck': !this.expert && incheckSq[ci][cj], | |
1d184b4c BA |
216 | }, |
217 | attrs: { | |
218 | id: this.getSquareId({x:ci,y:cj}), | |
219 | }, | |
220 | }, | |
221 | elems | |
222 | ); | |
223 | }) | |
224 | ); | |
225 | }), choices] | |
226 | ); | |
204e289b BA |
227 | if (this.mode != "idle") |
228 | { | |
229 | actionArray.push( | |
230 | h('button', | |
231 | { | |
232 | on: { click: this.resign }, | |
233 | attrs: { "aria-label": 'Resign' }, | |
234 | 'class': { | |
235 | "tooltip":true, | |
236 | "bottom": true, | |
237 | }, | |
0706ea91 | 238 | }, |
204e289b BA |
239 | [h('i', { 'class': { "material-icons": true } }, "flag")]) |
240 | ); | |
241 | } | |
e64084da BA |
242 | else if (this.vr.moves.length > 0) |
243 | { | |
244 | // A game finished, and another is not started yet: allow navigation | |
245 | actionArray = actionArray.concat([ | |
246 | h('button', | |
247 | { | |
248 | style: { "margin-left": "30px" }, | |
249 | on: { click: e => this.undo() }, | |
250 | attrs: { "aria-label": 'Undo' }, | |
251 | 'class': { | |
252 | "tooltip":true, | |
253 | "bottom": true, | |
254 | }, | |
255 | }, | |
256 | [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]), | |
257 | h('button', | |
258 | { | |
259 | on: { click: e => this.play() }, | |
260 | attrs: { "aria-label": 'Play' }, | |
261 | 'class': { | |
262 | "tooltip":true, | |
263 | "bottom": true, | |
264 | }, | |
265 | }, | |
266 | [h('i', { 'class': { "material-icons": true } }, "fast_forward")]), | |
267 | ] | |
268 | ); | |
269 | } | |
1d184b4c | 270 | elementArray.push(gameDiv); |
5c42c64e | 271 | if (!!this.vr.reserve) |
1221ac47 | 272 | { |
6752407b | 273 | const shiftIdx = (this.mycolor=="w" ? 0 : 1); |
5c42c64e | 274 | let myReservePiecesArray = []; |
1221ac47 BA |
275 | for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++) |
276 | { | |
5c42c64e BA |
277 | myReservePiecesArray.push(h('div', |
278 | { | |
279 | 'class': {'board':true, ['board'+sizeY]:true}, | |
6752407b | 280 | attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) } |
5c42c64e BA |
281 | }, |
282 | [ | |
283 | h('img', | |
1221ac47 BA |
284 | { |
285 | 'class': {"piece":true}, | |
286 | attrs: { | |
287 | "src": "/images/pieces/" + | |
288 | this.vr.getReservePpath(this.mycolor,i) + ".svg", | |
1221ac47 | 289 | } |
5c42c64e BA |
290 | }), |
291 | h('sup', | |
292 | {style: { "padding-left":"40%"} }, | |
293 | [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ] | |
294 | ) | |
295 | ])); | |
296 | } | |
297 | let oppReservePiecesArray = []; | |
298 | const oppCol = this.vr.getOppCol(this.mycolor); | |
299 | for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++) | |
300 | { | |
301 | oppReservePiecesArray.push(h('div', | |
302 | { | |
303 | 'class': {'board':true, ['board'+sizeY]:true}, | |
6752407b | 304 | attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) } |
5c42c64e BA |
305 | }, |
306 | [ | |
307 | h('img', | |
308 | { | |
309 | 'class': {"piece":true}, | |
310 | attrs: { | |
311 | "src": "/images/pieces/" + | |
312 | this.vr.getReservePpath(oppCol,i) + ".svg", | |
313 | } | |
314 | }), | |
315 | h('sup', | |
316 | {style: { "padding-left":"40%"} }, | |
317 | [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ] | |
318 | ) | |
319 | ])); | |
1221ac47 | 320 | } |
5c42c64e BA |
321 | let reserves = h('div', |
322 | { | |
323 | 'class':{'game':true}, | |
324 | style: {"margin-bottom": "20px"}, | |
325 | }, | |
326 | [ | |
327 | h('div', | |
328 | { | |
329 | 'class': { 'row': true }, | |
330 | style: {"margin-bottom": "15px"}, | |
331 | }, | |
332 | myReservePiecesArray | |
333 | ), | |
1221ac47 BA |
334 | h('div', |
335 | { 'class': { 'row': true }}, | |
5c42c64e | 336 | oppReservePiecesArray |
1221ac47 | 337 | ) |
5c42c64e | 338 | ] |
1221ac47 | 339 | ); |
5c42c64e | 340 | elementArray.push(reserves); |
1221ac47 | 341 | } |
f3802fcd | 342 | const eogMessage = this.getEndgameMessage(this.score); |
1d184b4c BA |
343 | const modalEog = [ |
344 | h('input', | |
345 | { | |
ecf44502 | 346 | attrs: { "id": "modal-eog", type: "checkbox" }, |
1d184b4c BA |
347 | "class": { "modal": true }, |
348 | }), | |
349 | h('div', | |
350 | { | |
351 | attrs: { "role": "dialog", "aria-labelledby": "dialog-title" }, | |
352 | }, | |
353 | [ | |
354 | h('div', | |
355 | { | |
356 | "class": { "card": true, "smallpad": true }, | |
357 | }, | |
01a135e2 BA |
358 | [ |
359 | h('label', | |
360 | { | |
361 | attrs: { "for": "modal-eog" }, | |
362 | "class": { "modal-close": true }, | |
363 | } | |
364 | ), | |
365 | h('h3', | |
366 | { | |
367 | "class": { "section": true }, | |
368 | domProps: { innerHTML: eogMessage }, | |
369 | } | |
370 | ) | |
371 | ] | |
1d184b4c BA |
372 | ) |
373 | ] | |
374 | ) | |
375 | ]; | |
376 | elementArray = elementArray.concat(modalEog); | |
377 | } | |
378 | const modalNewgame = [ | |
379 | h('input', | |
380 | { | |
ecf44502 | 381 | attrs: { "id": "modal-newgame", type: "checkbox" }, |
1d184b4c BA |
382 | "class": { "modal": true }, |
383 | }), | |
384 | h('div', | |
385 | { | |
386 | attrs: { "role": "dialog", "aria-labelledby": "dialog-title" }, | |
387 | }, | |
388 | [ | |
389 | h('div', | |
390 | { | |
391 | "class": { "card": true, "smallpad": true }, | |
392 | }, | |
393 | [ | |
394 | h('label', | |
395 | { | |
ecf44502 | 396 | attrs: { "id": "close-newgame", "for": "modal-newgame" }, |
1d184b4c BA |
397 | "class": { "modal-close": true }, |
398 | } | |
399 | ), | |
400 | h('h3', | |
401 | { | |
402 | "class": { "section": true }, | |
403 | domProps: { innerHTML: "New game" }, | |
404 | } | |
405 | ), | |
406 | h('p', | |
407 | { | |
408 | "class": { "section": true }, | |
409 | domProps: { innerHTML: "Waiting for opponent..." }, | |
410 | } | |
411 | ) | |
412 | ] | |
413 | ) | |
414 | ] | |
415 | ) | |
416 | ]; | |
417 | elementArray = elementArray.concat(modalNewgame); | |
418 | const actions = h('div', | |
419 | { | |
420 | attrs: { "id": "actions" }, | |
421 | 'class': { 'text-center': true }, | |
422 | }, | |
423 | actionArray | |
424 | ); | |
425 | elementArray.push(actions); | |
01a135e2 BA |
426 | if (this.score != "*") |
427 | { | |
428 | elementArray.push( | |
429 | h('div', | |
01ca2adc | 430 | { attrs: { id: "pgn-div" } }, |
01a135e2 | 431 | [ |
01ca2adc BA |
432 | h('a', |
433 | { | |
434 | attrs: { | |
435 | id: "download", | |
436 | href: "#", | |
437 | } | |
438 | } | |
439 | ), | |
01a135e2 BA |
440 | h('p', |
441 | { | |
01ca2adc BA |
442 | attrs: { id: "pgn-game" }, |
443 | on: { click: this.download }, | |
85be503d BA |
444 | domProps: { innerHTML: this.pgnTxt } |
445 | } | |
446 | ) | |
447 | ] | |
448 | ) | |
449 | ); | |
450 | } | |
451 | else if (this.mode != "idle") | |
452 | { | |
453 | // Show current FEN (at least for debug) | |
454 | elementArray.push( | |
455 | h('div', | |
456 | { attrs: { id: "fen-div" } }, | |
457 | [ | |
458 | h('p', | |
459 | { | |
460 | attrs: { id: "fen-string" }, | |
461 | domProps: { innerHTML: this.vr.getBaseFen() } | |
01a135e2 BA |
462 | } |
463 | ) | |
464 | ] | |
465 | ) | |
466 | ); | |
467 | } | |
1d184b4c BA |
468 | return h( |
469 | 'div', | |
470 | { | |
471 | 'class': { | |
472 | "col-sm-12":true, | |
473 | "col-md-8":true, | |
474 | "col-md-offset-2":true, | |
475 | "col-lg-6":true, | |
476 | "col-lg-offset-3":true, | |
477 | }, | |
dda21a71 | 478 | // NOTE: click = mousedown + mouseup |
1d184b4c BA |
479 | on: { |
480 | mousedown: this.mousedown, | |
481 | mousemove: this.mousemove, | |
482 | mouseup: this.mouseup, | |
ffea77d9 BA |
483 | touchstart: this.mousedown, |
484 | touchmove: this.mousemove, | |
485 | touchend: this.mouseup, | |
1d184b4c BA |
486 | }, |
487 | }, | |
488 | elementArray | |
489 | ); | |
490 | }, | |
491 | created: function() { | |
492 | const url = socketUrl; | |
493 | const continuation = (localStorage.getItem("variant") === variant); | |
494 | this.myid = continuation | |
495 | ? localStorage.getItem("myid") | |
496 | // random enough (TODO: function) | |
497 | : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); | |
92ff5bae BA |
498 | if (!continuation) |
499 | { | |
500 | // HACK: play a small silent sound to allow "new game" sound later if tab not focused | |
501 | new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {}); | |
502 | } | |
1d184b4c | 503 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); |
d35f20e4 | 504 | const socketOpenListener = () => { |
1d184b4c BA |
505 | if (continuation) |
506 | { | |
dfb4afc1 BA |
507 | const fen = localStorage.getItem("fen"); |
508 | const mycolor = localStorage.getItem("mycolor"); | |
509 | const oppid = localStorage.getItem("oppid"); | |
510 | const moves = JSON.parse(localStorage.getItem("moves")); | |
511 | this.newGame("human", fen, mycolor, oppid, moves, true); | |
a29d9d6b | 512 | // Send ping to server (answer pong if opponent is connected) |
ecf44502 | 513 | this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid})); |
1d184b4c | 514 | } |
30ff6e04 BA |
515 | else if (localStorage.getItem("newgame") === variant) |
516 | { | |
517 | // New game request has been cancelled on disconnect | |
186516b8 | 518 | this.seek = true; |
001344b9 | 519 | this.newGame("human", undefined, undefined, undefined, undefined, "reconnect"); |
30ff6e04 | 520 | } |
1d184b4c | 521 | }; |
d35f20e4 | 522 | const socketMessageListener = msg => { |
1d184b4c BA |
523 | const data = JSON.parse(msg.data); |
524 | switch (data.code) | |
525 | { | |
526 | case "newgame": //opponent found | |
527 | this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID | |
528 | break; | |
529 | case "newmove": //..he played! | |
530 | this.play(data.move, "animate"); | |
531 | break; | |
f3802fcd | 532 | case "pong": //received if we sent a ping (game still alive on our side) |
1d184b4c | 533 | this.oppConnected = true; |
a29d9d6b | 534 | const L = this.vr.moves.length; |
f3802fcd | 535 | // Send our "last state" informations to opponent |
a29d9d6b BA |
536 | this.conn.send(JSON.stringify({ |
537 | code:"lastate", | |
f3802fcd | 538 | oppid:this.oppid, |
a29d9d6b BA |
539 | lastMove:L>0?this.vr.moves[L-1]:undefined, |
540 | movesCount:L, | |
541 | })); | |
1d184b4c | 542 | break; |
a29d9d6b BA |
543 | case "lastate": //got opponent infos about last move (we might have resigned) |
544 | if (this.mode!="human" || this.oppid!=data.oppid) | |
545 | { | |
546 | // OK, we resigned | |
547 | this.conn.send(JSON.stringify({ | |
548 | code:"lastate", | |
f3802fcd | 549 | oppid:this.oppid, |
a29d9d6b BA |
550 | lastMove:undefined, |
551 | movesCount:-1, | |
552 | })); | |
553 | } | |
554 | else if (data.movesCount < 0) | |
555 | { | |
556 | // OK, he resigned | |
557 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); | |
558 | } | |
559 | else if (data.movesCount < this.vr.moves.length) | |
560 | { | |
561 | // We must tell last move to opponent | |
562 | const L = this.vr.moves.length; | |
563 | this.conn.send(JSON.stringify({ | |
564 | code:"lastate", | |
f3802fcd | 565 | oppid:this.oppid, |
a29d9d6b BA |
566 | lastMove:this.vr.moves[L-1], |
567 | movesCount:L, | |
568 | })); | |
569 | } | |
570 | else if (data.movesCount > this.vr.moves.length) //just got last move from him | |
571 | this.play(data.lastMove, "animate"); | |
ecf44502 | 572 | break; |
1d184b4c | 573 | case "resign": //..you won! |
dfb4afc1 | 574 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); |
1d184b4c | 575 | break; |
f3802fcd | 576 | // TODO: also use (dis)connect info to count online players? |
1d184b4c BA |
577 | case "connect": |
578 | case "disconnect": | |
579 | if (this.mode == "human" && this.oppid == data.id) | |
580 | this.oppConnected = (data.code == "connect"); | |
581 | break; | |
582 | } | |
583 | }; | |
d35f20e4 | 584 | const socketCloseListener = () => { |
d35f20e4 BA |
585 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); |
586 | this.conn.addEventListener('open', socketOpenListener); | |
587 | this.conn.addEventListener('message', socketMessageListener); | |
588 | this.conn.addEventListener('close', socketCloseListener); | |
589 | }; | |
590 | this.conn.onopen = socketOpenListener; | |
591 | this.conn.onmessage = socketMessageListener; | |
592 | this.conn.onclose = socketCloseListener; | |
e64084da BA |
593 | // Listen to keyboard left/right to navigate in game |
594 | document.onkeydown = event => { | |
595 | if (this.mode == "idle" && this.vr.moves.length > 0 | |
596 | && [37,39].includes(event.keyCode)) | |
597 | { | |
598 | event.preventDefault(); | |
599 | if (event.keyCode == 37) //Back | |
600 | this.undo(); | |
601 | else //Forward (39) | |
602 | this.play(); | |
603 | } | |
604 | }; | |
1d184b4c BA |
605 | }, |
606 | methods: { | |
01ca2adc BA |
607 | download: function() { |
608 | let content = document.getElementById("pgn-game").innerHTML; | |
609 | content = content.replace(/<br>/g, "\n"); | |
610 | // Prepare and trigger download link | |
611 | let downloadAnchor = document.getElementById("download"); | |
612 | downloadAnchor.setAttribute("download", "game.pgn"); | |
613 | downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content); | |
614 | downloadAnchor.click(); | |
615 | }, | |
dfb4afc1 BA |
616 | endGame: function(score) { |
617 | this.score = score; | |
ecf44502 | 618 | let modalBox = document.getElementById("modal-eog"); |
186516b8 | 619 | modalBox.checked = true; |
204e289b | 620 | // Variants may have special PGN structure (so next function isn't defined here) |
3840e240 BA |
621 | this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode); |
622 | setTimeout(() => { modalBox.checked = false; }, 2000); | |
1d184b4c BA |
623 | if (this.mode == "human") |
624 | this.clearStorage(); | |
3840e240 | 625 | this.mode = "idle"; |
e64084da | 626 | this.cursor = this.vr.moves.length; //to navigate in finished game |
1d184b4c BA |
627 | this.oppid = ""; |
628 | }, | |
f3802fcd BA |
629 | getEndgameMessage: function(score) { |
630 | let eogMessage = "Unfinished"; | |
631 | switch (this.score) | |
632 | { | |
633 | case "1-0": | |
634 | eogMessage = "White win"; | |
635 | break; | |
636 | case "0-1": | |
637 | eogMessage = "Black win"; | |
638 | break; | |
639 | case "1/2": | |
640 | eogMessage = "Draw"; | |
641 | break; | |
642 | } | |
643 | return eogMessage; | |
644 | }, | |
3ed62725 BA |
645 | toggleExpertMode: function() { |
646 | this.expert = !this.expert; | |
647 | document.cookie = "expert=" + (this.expert ? "1" : "0"); | |
648 | }, | |
1d184b4c BA |
649 | resign: function() { |
650 | if (this.mode == "human" && this.oppConnected) | |
d35f20e4 BA |
651 | { |
652 | try { | |
653 | this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid})); | |
654 | } catch (INVALID_STATE_ERR) { | |
a29d9d6b | 655 | return; //socket is not ready (and not yet reconnected) |
d35f20e4 BA |
656 | } |
657 | } | |
dfb4afc1 | 658 | this.endGame(this.mycolor=="w"?"0-1":"1-0"); |
1d184b4c | 659 | }, |
762b7c9c BA |
660 | setStorage: function() { |
661 | localStorage.setItem("myid", this.myid); | |
662 | localStorage.setItem("variant", variant); | |
663 | localStorage.setItem("mycolor", this.mycolor); | |
664 | localStorage.setItem("oppid", this.oppid); | |
665 | localStorage.setItem("fenStart", this.fenStart); | |
666 | localStorage.setItem("moves", JSON.stringify(this.vr.moves)); | |
1d184b4c | 667 | localStorage.setItem("fen", this.vr.getFen()); |
762b7c9c BA |
668 | }, |
669 | updateStorage: function() { | |
dfb4afc1 | 670 | localStorage.setItem("moves", JSON.stringify(this.vr.moves)); |
762b7c9c | 671 | localStorage.setItem("fen", this.vr.getFen()); |
1d184b4c BA |
672 | }, |
673 | clearStorage: function() { | |
674 | delete localStorage["variant"]; | |
675 | delete localStorage["myid"]; | |
676 | delete localStorage["mycolor"]; | |
677 | delete localStorage["oppid"]; | |
762b7c9c | 678 | delete localStorage["fenStart"]; |
1d184b4c | 679 | delete localStorage["fen"]; |
dfb4afc1 | 680 | delete localStorage["moves"]; |
1d184b4c | 681 | }, |
f3802fcd BA |
682 | clickGameSeek: function() { |
683 | if (this.mode == "human") | |
684 | return; //no newgame while playing | |
685 | if (this.seek) | |
01a135e2 | 686 | { |
f3802fcd | 687 | delete localStorage["newgame"]; //cancel game seek |
01a135e2 BA |
688 | this.seek = false; |
689 | } | |
f3802fcd | 690 | else |
f3802fcd | 691 | this.newGame("human"); |
f3802fcd BA |
692 | }, |
693 | clickComputerGame: function() { | |
694 | if (this.mode == "human") | |
695 | return; //no newgame while playing | |
696 | this.newGame("computer"); | |
697 | }, | |
dfb4afc1 | 698 | newGame: function(mode, fenInit, color, oppId, moves, continuation) { |
55eb331d | 699 | const fen = fenInit || VariantRules.GenRandInitFen(); |
1d184b4c | 700 | console.log(fen); //DEBUG |
dfb4afc1 | 701 | this.score = "*"; |
1d184b4c BA |
702 | if (mode=="human" && !oppId) |
703 | { | |
cd3174c5 BA |
704 | const storageVariant = localStorage.getItem("variant"); |
705 | if (!!storageVariant && storageVariant !== variant) | |
706 | { | |
cd3174c5 BA |
707 | alert("Finish your " + storageVariant + " game first!"); |
708 | return; | |
709 | } | |
1d184b4c | 710 | // Send game request and wait.. |
01a135e2 BA |
711 | localStorage["newgame"] = variant; |
712 | this.seek = true; | |
1d184b4c | 713 | this.clearStorage(); //in case of |
d35f20e4 BA |
714 | try { |
715 | this.conn.send(JSON.stringify({code:"newgame", fen:fen})); | |
716 | } catch (INVALID_STATE_ERR) { | |
717 | return; //nothing achieved | |
718 | } | |
f3802fcd | 719 | if (continuation !== "reconnect") //TODO: bad HACK... |
a68d899d | 720 | { |
ecf44502 | 721 | let modalBox = document.getElementById("modal-newgame"); |
a68d899d BA |
722 | modalBox.checked = true; |
723 | setTimeout(() => { modalBox.checked = false; }, 2000); | |
724 | } | |
1d184b4c BA |
725 | return; |
726 | } | |
efb20746 BA |
727 | // random enough (TODO: function) |
728 | this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); | |
dfb4afc1 | 729 | this.vr = new VariantRules(fen, moves || []); |
3840e240 | 730 | this.pgnTxt = ""; //redundant with this.score = "*", but cleaner |
1d184b4c | 731 | this.mode = mode; |
1fcaa356 | 732 | this.incheck = []; //in case of |
762b7c9c BA |
733 | this.fenStart = continuation |
734 | ? localStorage.getItem("fenStart") | |
735 | : fen.split(" ")[0]; //Only the position matters | |
1d184b4c BA |
736 | if (mode=="human") |
737 | { | |
738 | // Opponent found! | |
739 | if (!continuation) | |
740 | { | |
ecf44502 | 741 | // Not playing sound on game continuation: |
ea8417ff | 742 | new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {}); |
ecf44502 | 743 | document.getElementById("modal-newgame").checked = false; |
1d184b4c BA |
744 | } |
745 | this.oppid = oppId; | |
746 | this.oppConnected = true; | |
747 | this.mycolor = color; | |
186516b8 | 748 | this.seek = false; |
e64a4eff BA |
749 | if (!!moves && moves.length > 0) //imply continuation |
750 | { | |
e64a4eff | 751 | const lastMove = moves[moves.length-1]; |
cd4cad04 | 752 | this.vr.undo(lastMove); |
46302e64 | 753 | this.incheck = this.vr.getCheckSquares(lastMove); |
e64a4eff BA |
754 | this.vr.play(lastMove, "ingame"); |
755 | } | |
186516b8 | 756 | delete localStorage["newgame"]; |
762b7c9c | 757 | this.setStorage(); //in case of interruptions |
1d184b4c BA |
758 | } |
759 | else //against computer | |
760 | { | |
f3c10e18 | 761 | this.mycolor = Math.random() < 0.5 ? 'w' : 'b'; |
1d184b4c BA |
762 | if (this.mycolor == 'b') |
763 | setTimeout(this.playComputerMove, 500); | |
764 | } | |
765 | }, | |
766 | playComputerMove: function() { | |
4b353936 | 767 | const timeStart = Date.now(); |
3c09dc49 | 768 | const nbMoves = this.vr.moves.length; //using played moves to know if search finished |
efb20746 | 769 | const gameId = this.gameId; //to know if game was reset before timer end |
3c09dc49 BA |
770 | setTimeout( |
771 | () => { | |
efb20746 BA |
772 | if (gameId != this.gameId) |
773 | return; //game stopped | |
3c09dc49 BA |
774 | const L = this.vr.moves.length; |
775 | if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish | |
776 | this.vr.shouldReturn = true; | |
777 | }, 5000); | |
46302e64 | 778 | const compMove = this.vr.getComputerMove(); |
4b353936 BA |
779 | // (first move) HACK: avoid selecting elements before they appear on page: |
780 | const delay = Math.max(500-(Date.now()-timeStart), 0); | |
781 | setTimeout(() => this.play(compMove, "animate"), delay); | |
1d184b4c BA |
782 | }, |
783 | // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y. | |
784 | getSquareId: function(o) { | |
785 | // NOTE: a separator is required to allow any size of board | |
786 | return "sq-" + o.x + "-" + o.y; | |
787 | }, | |
788 | // Inverse function | |
789 | getSquareFromId: function(id) { | |
790 | let idParts = id.split('-'); | |
791 | return [parseInt(idParts[1]), parseInt(idParts[2])]; | |
792 | }, | |
793 | mousedown: function(e) { | |
794 | e = e || window.event; | |
44461547 BA |
795 | let ingame = false; |
796 | let elem = e.target; | |
797 | while (!ingame && elem !== null) | |
798 | { | |
799 | if (elem.classList.contains("game")) | |
800 | { | |
801 | ingame = true; | |
802 | break; | |
803 | } | |
804 | elem = elem.parentElement; | |
805 | } | |
806 | if (!ingame) //let default behavior (click on button...) | |
807 | return; | |
1d184b4c BA |
808 | e.preventDefault(); //disable native drag & drop |
809 | if (!this.selectedPiece && e.target.classList.contains("piece")) | |
810 | { | |
811 | // Next few lines to center the piece on mouse cursor | |
812 | let rect = e.target.parentNode.getBoundingClientRect(); | |
813 | this.start = { | |
814 | x: rect.x + rect.width/2, | |
815 | y: rect.y + rect.width/2, | |
816 | id: e.target.parentNode.id | |
817 | }; | |
818 | this.selectedPiece = e.target.cloneNode(); | |
819 | this.selectedPiece.style.position = "absolute"; | |
820 | this.selectedPiece.style.top = 0; | |
821 | this.selectedPiece.style.display = "inline-block"; | |
822 | this.selectedPiece.style.zIndex = 3000; | |
823 | let startSquare = this.getSquareFromId(e.target.parentNode.id); | |
55eb331d | 824 | this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare) |
1d184b4c BA |
825 | ? this.vr.getPossibleMovesFrom(startSquare) |
826 | : []; | |
5bd679d5 BA |
827 | // Next line add moving piece just after current image (required for Crazyhouse reserve) |
828 | e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling); | |
1d184b4c BA |
829 | } |
830 | }, | |
831 | mousemove: function(e) { | |
832 | if (!this.selectedPiece) | |
833 | return; | |
834 | e = e || window.event; | |
835 | // If there is an active element, move it around | |
836 | if (!!this.selectedPiece) | |
837 | { | |
ffea77d9 BA |
838 | const [offsetX,offsetY] = !!e.clientX |
839 | ? [e.clientX,e.clientY] //desktop browser | |
840 | : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone | |
841 | this.selectedPiece.style.left = (offsetX-this.start.x) + "px"; | |
842 | this.selectedPiece.style.top = (offsetY-this.start.y) + "px"; | |
1d184b4c BA |
843 | } |
844 | }, | |
845 | mouseup: function(e) { | |
846 | if (!this.selectedPiece) | |
847 | return; | |
848 | e = e || window.event; | |
849 | // Read drop target (or parentElement, parentNode... if type == "img") | |
850 | this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates | |
ffea77d9 BA |
851 | const [offsetX,offsetY] = !!e.clientX |
852 | ? [e.clientX,e.clientY] | |
853 | : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; | |
854 | let landing = document.elementFromPoint(offsetX, offsetY); | |
1d184b4c BA |
855 | this.selectedPiece.style.zIndex = 3000; |
856 | while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight | |
857 | landing = landing.parentNode; | |
858 | if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled | |
859 | return; | |
860 | // OK: process move attempt | |
861 | let endSquare = this.getSquareFromId(landing.id); | |
862 | let moves = this.findMatchingMoves(endSquare); | |
863 | this.possibleMoves = []; | |
864 | if (moves.length > 1) | |
865 | this.choices = moves; | |
866 | else if (moves.length==1) | |
867 | this.play(moves[0]); | |
868 | // Else: impossible move | |
869 | this.selectedPiece.parentNode.removeChild(this.selectedPiece); | |
870 | delete this.selectedPiece; | |
871 | this.selectedPiece = null; | |
872 | }, | |
873 | findMatchingMoves: function(endSquare) { | |
874 | // Run through moves list and return the matching set (if promotions...) | |
875 | let moves = []; | |
876 | this.possibleMoves.forEach(function(m) { | |
877 | if (endSquare[0] == m.end.x && endSquare[1] == m.end.y) | |
878 | moves.push(m); | |
879 | }); | |
880 | return moves; | |
881 | }, | |
882 | animateMove: function(move) { | |
883 | let startSquare = document.getElementById(this.getSquareId(move.start)); | |
884 | let endSquare = document.getElementById(this.getSquareId(move.end)); | |
885 | let rectStart = startSquare.getBoundingClientRect(); | |
886 | let rectEnd = endSquare.getBoundingClientRect(); | |
887 | let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y}; | |
92ff5bae BA |
888 | let movingPiece = |
889 | document.querySelector("#" + this.getSquareId(move.start) + " > img.piece"); | |
890 | // HACK for animation (with positive translate, image slides "under background"...) | |
1d184b4c BA |
891 | // Possible improvement: just alter squares on the piece's way... |
892 | squares = document.getElementsByClassName("board"); | |
893 | for (let i=0; i<squares.length; i++) | |
894 | { | |
895 | let square = squares.item(i); | |
896 | if (square.id != this.getSquareId(move.start)) | |
897 | square.style.zIndex = "-1"; | |
898 | } | |
899 | movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)"; | |
900 | movingPiece.style.transitionDuration = "0.2s"; | |
901 | movingPiece.style.zIndex = "3000"; | |
902 | setTimeout( () => { | |
903 | for (let i=0; i<squares.length; i++) | |
904 | squares.item(i).style.zIndex = "auto"; | |
905 | movingPiece.style = {}; //required e.g. for 0-0 with KR swap | |
906 | this.play(move); | |
907 | }, 200); | |
908 | }, | |
909 | play: function(move, programmatic) { | |
e64084da BA |
910 | if (!move) |
911 | { | |
912 | // Navigate after game is over | |
913 | if (this.cursor >= this.vr.moves.length) | |
914 | return; //already at the end | |
915 | move = this.vr.moves[this.cursor++]; | |
916 | } | |
1d184b4c BA |
917 | if (!!programmatic) //computer or human opponent |
918 | { | |
919 | this.animateMove(move); | |
920 | return; | |
921 | } | |
46302e64 | 922 | this.incheck = this.vr.getCheckSquares(move); //is opponent in check? |
1d184b4c BA |
923 | // Not programmatic, or animation is over |
924 | if (this.mode == "human" && this.vr.turn == this.mycolor) | |
a29d9d6b | 925 | this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid})); |
ea8417ff | 926 | new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {}); |
e64084da BA |
927 | if (this.mode != "idle") |
928 | this.vr.play(move, "ingame"); | |
929 | else | |
930 | VariantRules.PlayOnBoard(this.vr.board, move); | |
1d184b4c BA |
931 | if (this.mode == "human") |
932 | this.updateStorage(); //after our moves and opponent moves | |
e64084da BA |
933 | if (this.mode != "idle") |
934 | { | |
935 | const eog = this.vr.checkGameOver(); | |
936 | if (eog != "*") | |
937 | this.endGame(eog); | |
938 | } | |
939 | if (this.mode == "computer" && this.vr.turn != this.mycolor) | |
1d184b4c BA |
940 | setTimeout(this.playComputerMove, 500); |
941 | }, | |
e64084da BA |
942 | undo: function() { |
943 | // Navigate after game is over | |
944 | if (this.cursor == 0) | |
945 | return; //already at the beginning | |
946 | const move = this.vr.moves[--this.cursor]; | |
947 | VariantRules.UndoOnBoard(this.vr.board, move); | |
948 | this.$forceUpdate(); //TODO: ?! | |
949 | } | |
1d184b4c BA |
950 | }, |
951 | }) |