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