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