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