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