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