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