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