Commit | Line | Data |
---|---|---|
30ff6e04 BA |
1 | // TODO: use indexedDB instead of localStorage: more flexible. |
2 | ||
1d184b4c BA |
3 | Vue.component('my-game', { |
4 | data: function() { | |
5 | return { | |
6 | vr: null, //object to check moves, store them, FEN.. | |
7 | mycolor: "w", | |
8 | possibleMoves: [], //filled after each valid click/dragstart | |
9 | choices: [], //promotion pieces, or checkered captures... (contain possible pieces) | |
10 | start: {}, //pixels coordinates + id of starting square (click or drag) | |
11 | selectedPiece: null, //moving piece (or clicked piece) | |
12 | conn: null, //socket messages | |
13 | endofgame: "", //end of game message | |
14 | mode: "idle", //human, computer or idle (when not playing) | |
15 | oppid: "", //opponent ID in case of HH game | |
16 | oppConnected: false, | |
17 | }; | |
18 | }, | |
19 | render(h) { | |
20 | let [sizeX,sizeY] = VariantRules.size; | |
21 | // Precompute hints squares to facilitate rendering | |
22 | let hintSquares = doubleArray(sizeX, sizeY, false); | |
23 | this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; }); | |
24 | let elementArray = []; | |
25 | let square00 = document.getElementById("sq-0-0"); | |
26 | let squareWidth = !!square00 | |
27 | ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2)) | |
28 | : 0; | |
29 | let actionArray = [ | |
30 | h('button', | |
31 | { | |
30ff6e04 BA |
32 | on: { |
33 | click: () => { | |
34 | if (localStorage.getItem("newgame") === variant) | |
35 | delete localStorage["newgame"]; //cancel game seek | |
36 | else | |
37 | { | |
38 | localStorage["newgame"] = variant; | |
39 | this.newGame("human"); | |
40 | } | |
41 | } | |
42 | }, | |
1d184b4c BA |
43 | attrs: { "aria-label": 'New game VS human' }, |
44 | 'class': { "tooltip":true }, | |
45 | }, | |
46 | [h('i', { 'class': { "material-icons": true } }, "accessibility")]), | |
47 | h('button', | |
48 | { | |
49 | on: { click: () => this.newGame("computer") }, | |
50 | attrs: { "aria-label": 'New game VS computer' }, | |
51 | 'class': { "tooltip":true }, | |
52 | }, | |
53 | [h('i', { 'class': { "material-icons": true } }, "computer")]) | |
54 | ]; | |
55 | if (!!this.vr) | |
56 | { | |
57 | if (this.mode == "human") | |
58 | { | |
59 | let connectedIndic = h( | |
60 | 'div', | |
61 | { | |
62 | "class": { | |
63 | "connected": this.oppConnected, | |
64 | "disconnected": !this.oppConnected, | |
65 | }, | |
66 | } | |
67 | ); | |
68 | elementArray.push(connectedIndic); | |
69 | } | |
70 | let choices = h('div', | |
71 | { | |
72 | attrs: { "id": "choices" }, | |
73 | 'class': { 'row': true }, | |
74 | style: { | |
75 | //"position": "relative", | |
76 | "display": this.choices.length>0?"block":"none", | |
77 | "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px", | |
78 | "width": (this.choices.length * squareWidth) + "px", | |
79 | "height": squareWidth + "px", | |
80 | }, | |
81 | }, | |
82 | this.choices.map( m => { //a "choice" is a move | |
83 | return h('div', | |
84 | { | |
85 | 'class': { 'board': true }, | |
86 | style: { | |
87 | 'width': (100/this.choices.length) + "%", | |
88 | 'padding-bottom': (100/this.choices.length) + "%", | |
89 | }, | |
90 | }, | |
91 | [h('img', | |
92 | { | |
93 | attrs: { "src": '/images/pieces/' + VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' }, | |
94 | 'class': { 'choice-piece': true, 'board': true }, | |
95 | on: { "click": e => { this.play(m); this.choices=[]; } }, | |
96 | }) | |
97 | ] | |
98 | ); | |
99 | }) | |
100 | ); | |
101 | // Create board element (+ reserves if needed by variant or mode) | |
102 | let gameDiv = h('div', | |
103 | { | |
104 | 'class': { 'game': true }, | |
105 | }, | |
106 | [_.range(sizeX).map(i => { | |
107 | let ci = this.mycolor=='w' ? i : sizeX-i-1; | |
108 | return h( | |
109 | 'div', | |
110 | { | |
111 | 'class': { | |
112 | 'row': true, | |
113 | }, | |
114 | style: { 'opacity': this.choices.length>0?"0.5":"1" }, | |
115 | }, | |
116 | _.range(sizeY).map(j => { | |
117 | let cj = this.mycolor=='w' ? j : sizeY-j-1; | |
118 | let elems = []; | |
119 | if (this.vr.board[ci][cj] != VariantRules.EMPTY) | |
120 | { | |
121 | elems.push( | |
122 | h( | |
123 | 'img', | |
124 | { | |
125 | 'class': { | |
126 | 'piece': true, | |
127 | 'ghost': !!this.selectedPiece && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj, | |
128 | }, | |
129 | attrs: { | |
130 | src: "/images/pieces/" + VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg", | |
131 | }, | |
132 | } | |
133 | ) | |
134 | ); | |
135 | } | |
136 | if (hintSquares[ci][cj]) | |
137 | { | |
138 | elems.push( | |
139 | h( | |
140 | 'img', | |
141 | { | |
142 | 'class': { | |
143 | 'mark-square': true, | |
144 | }, | |
145 | attrs: { | |
146 | src: "/images/mark.svg", | |
147 | }, | |
148 | } | |
149 | ) | |
150 | ); | |
151 | } | |
30ff6e04 | 152 | const lm = this.vr.lastMove; |
1d184b4c BA |
153 | const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj}); //&& _.isMatch(lm.start, {x:ci,y:cj}) |
154 | return h( | |
155 | 'div', | |
156 | { | |
157 | 'class': { | |
158 | 'board': true, | |
159 | 'light-square': !highlight && (i+j)%2==0, | |
160 | 'dark-square': !highlight && (i+j)%2==1, | |
161 | 'highlight': highlight, | |
162 | }, | |
163 | attrs: { | |
164 | id: this.getSquareId({x:ci,y:cj}), | |
165 | }, | |
166 | }, | |
167 | elems | |
168 | ); | |
169 | }) | |
170 | ); | |
171 | }), choices] | |
172 | ); | |
173 | actionArray.push( | |
174 | h('button', | |
175 | { | |
176 | on: { click: this.resign }, | |
177 | attrs: { "aria-label": 'Resign' }, | |
178 | 'class': { "tooltip":true }, | |
179 | }, | |
180 | [h('i', { 'class': { "material-icons": true } }, "flag")]) | |
181 | ); | |
182 | elementArray.push(gameDiv); | |
183 | // if (!!vr.reserve) | |
184 | // { | |
185 | // let reserve = h('div', | |
186 | // {'class':{'game':true}}, [ | |
187 | // h('div', | |
188 | // { 'class': { 'row': true }}, | |
189 | // [ | |
190 | // h('div', | |
191 | // {'class':{'board':true}}, | |
192 | // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})] | |
193 | // ) | |
194 | // ] | |
195 | // ) | |
196 | // ], | |
197 | // ); | |
198 | // elementArray.push(reserve); | |
199 | // } | |
200 | const modalEog = [ | |
201 | h('input', | |
202 | { | |
203 | attrs: { "id": "modal-control", type: "checkbox" }, | |
204 | "class": { "modal": true }, | |
205 | }), | |
206 | h('div', | |
207 | { | |
208 | attrs: { "role": "dialog", "aria-labelledby": "dialog-title" }, | |
209 | }, | |
210 | [ | |
211 | h('div', | |
212 | { | |
213 | "class": { "card": true, "smallpad": true }, | |
214 | }, | |
215 | [ | |
216 | h('label', | |
217 | { | |
218 | attrs: { "for": "modal-control" }, | |
219 | "class": { "modal-close": true }, | |
220 | } | |
221 | ), | |
222 | h('h3', | |
223 | { | |
224 | "class": { "section": true }, | |
225 | domProps: { innerHTML: "End of game" }, | |
226 | } | |
227 | ), | |
228 | h('p', | |
229 | { | |
230 | "class": { "section": true }, | |
231 | domProps: { innerHTML: this.endofgame }, | |
232 | } | |
233 | ) | |
234 | ] | |
235 | ) | |
236 | ] | |
237 | ) | |
238 | ]; | |
239 | elementArray = elementArray.concat(modalEog); | |
240 | } | |
241 | const modalNewgame = [ | |
242 | h('input', | |
243 | { | |
244 | attrs: { "id": "modal-control2", type: "checkbox" }, | |
245 | "class": { "modal": true }, | |
246 | }), | |
247 | h('div', | |
248 | { | |
249 | attrs: { "role": "dialog", "aria-labelledby": "dialog-title" }, | |
250 | }, | |
251 | [ | |
252 | h('div', | |
253 | { | |
254 | "class": { "card": true, "smallpad": true }, | |
255 | }, | |
256 | [ | |
257 | h('label', | |
258 | { | |
259 | attrs: { "id": "close-newgame", "for": "modal-control2" }, | |
260 | "class": { "modal-close": true }, | |
261 | } | |
262 | ), | |
263 | h('h3', | |
264 | { | |
265 | "class": { "section": true }, | |
266 | domProps: { innerHTML: "New game" }, | |
267 | } | |
268 | ), | |
269 | h('p', | |
270 | { | |
271 | "class": { "section": true }, | |
272 | domProps: { innerHTML: "Waiting for opponent..." }, | |
273 | } | |
274 | ) | |
275 | ] | |
276 | ) | |
277 | ] | |
278 | ) | |
279 | ]; | |
280 | elementArray = elementArray.concat(modalNewgame); | |
281 | const actions = h('div', | |
282 | { | |
283 | attrs: { "id": "actions" }, | |
284 | 'class': { 'text-center': true }, | |
285 | }, | |
286 | actionArray | |
287 | ); | |
288 | elementArray.push(actions); | |
289 | return h( | |
290 | 'div', | |
291 | { | |
292 | 'class': { | |
293 | "col-sm-12":true, | |
294 | "col-md-8":true, | |
295 | "col-md-offset-2":true, | |
296 | "col-lg-6":true, | |
297 | "col-lg-offset-3":true, | |
298 | }, | |
299 | // NOTE: click = mousedown + mouseup --> what about smartphone?! | |
300 | on: { | |
301 | mousedown: this.mousedown, | |
302 | mousemove: this.mousemove, | |
303 | mouseup: this.mouseup, | |
304 | touchdown: this.mousedown, | |
305 | touchmove: this.mousemove, | |
306 | touchup: this.mouseup, | |
307 | }, | |
308 | }, | |
309 | elementArray | |
310 | ); | |
311 | }, | |
312 | created: function() { | |
313 | const url = socketUrl; | |
314 | const continuation = (localStorage.getItem("variant") === variant); | |
315 | this.myid = continuation | |
316 | ? localStorage.getItem("myid") | |
317 | // random enough (TODO: function) | |
318 | : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); | |
319 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); | |
d35f20e4 | 320 | const socketOpenListener = () => { |
1d184b4c BA |
321 | if (continuation) |
322 | { | |
323 | // TODO: check FEN integrity with opponent | |
324 | this.newGame("human", localStorage.getItem("fen"), | |
325 | localStorage.getItem("mycolor"), localStorage.getItem("oppid"), true); | |
326 | // Send ping to server, which answers pong if opponent is connected | |
327 | this.conn.send(JSON.stringify({code:"ping", oppid:this.oppId})); | |
328 | } | |
30ff6e04 BA |
329 | else if (localStorage.getItem("newgame") === variant) |
330 | { | |
331 | // New game request has been cancelled on disconnect | |
332 | this.newGame("human"); | |
333 | } | |
1d184b4c | 334 | }; |
d35f20e4 | 335 | const socketMessageListener = msg => { |
1d184b4c BA |
336 | const data = JSON.parse(msg.data); |
337 | switch (data.code) | |
338 | { | |
339 | case "newgame": //opponent found | |
340 | this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID | |
341 | break; | |
342 | case "newmove": //..he played! | |
343 | this.play(data.move, "animate"); | |
344 | break; | |
345 | case "pong": //sent when opponent stayed online after we disconnected | |
346 | this.oppConnected = true; | |
347 | break; | |
348 | case "resign": //..you won! | |
349 | this.endGame("Victory!"); | |
350 | break; | |
351 | // TODO: also use (dis)connect info to count online players | |
352 | case "connect": | |
353 | case "disconnect": | |
354 | if (this.mode == "human" && this.oppid == data.id) | |
355 | this.oppConnected = (data.code == "connect"); | |
356 | break; | |
357 | } | |
358 | }; | |
d35f20e4 | 359 | const socketCloseListener = () => { |
30ff6e04 | 360 | console.log("Lost connection -- reconnect"); |
d35f20e4 BA |
361 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); |
362 | this.conn.addEventListener('open', socketOpenListener); | |
363 | this.conn.addEventListener('message', socketMessageListener); | |
364 | this.conn.addEventListener('close', socketCloseListener); | |
365 | }; | |
366 | this.conn.onopen = socketOpenListener; | |
367 | this.conn.onmessage = socketMessageListener; | |
368 | this.conn.onclose = socketCloseListener; | |
1d184b4c BA |
369 | }, |
370 | methods: { | |
371 | endGame: function(message) { | |
372 | this.endofgame = message; | |
373 | document.getElementById("modal-control").checked = true; | |
374 | if (this.mode == "human") | |
375 | this.clearStorage(); | |
376 | this.mode = "idle"; | |
377 | this.oppid = ""; | |
378 | }, | |
379 | resign: function() { | |
380 | if (this.mode == "human" && this.oppConnected) | |
d35f20e4 BA |
381 | { |
382 | try { | |
383 | this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid})); | |
384 | } catch (INVALID_STATE_ERR) { | |
385 | return; //resign failed for some reason... | |
386 | } | |
387 | } | |
1d184b4c BA |
388 | this.endGame("Try again!"); |
389 | }, | |
390 | updateStorage: function() { | |
391 | if (!localStorage.getItem("myid")) | |
392 | { | |
393 | localStorage.setItem("myid", this.myid); | |
394 | localStorage.setItem("variant", variant); | |
395 | localStorage.setItem("mycolor", this.mycolor); | |
396 | localStorage.setItem("oppid", this.oppid); | |
397 | } | |
398 | localStorage.setItem("fen", this.vr.getFen()); | |
399 | }, | |
400 | clearStorage: function() { | |
401 | delete localStorage["variant"]; | |
402 | delete localStorage["myid"]; | |
403 | delete localStorage["mycolor"]; | |
404 | delete localStorage["oppid"]; | |
405 | delete localStorage["fen"]; | |
406 | }, | |
407 | newGame: function(mode, fenInit, color, oppId, continuation) { | |
408 | const fen = fenInit || VariantRules.GenRandInitFen(); | |
409 | console.log(fen); //DEBUG | |
410 | if (mode=="human" && !oppId) | |
411 | { | |
412 | // Send game request and wait.. | |
413 | this.clearStorage(); //in case of | |
d35f20e4 BA |
414 | try { |
415 | this.conn.send(JSON.stringify({code:"newgame", fen:fen})); | |
416 | } catch (INVALID_STATE_ERR) { | |
417 | return; //nothing achieved | |
418 | } | |
1d184b4c BA |
419 | document.getElementById("modal-control2").checked = true; |
420 | return; | |
421 | } | |
422 | this.vr = new VariantRules(fen); | |
423 | this.mode = mode; | |
424 | if (mode=="human") | |
425 | { | |
426 | // Opponent found! | |
427 | if (!continuation) | |
428 | { | |
429 | // Playing sound fails on game continuation: | |
430 | new Audio("/sounds/newgame.mp3").play(); | |
431 | document.getElementById("modal-control2").checked = false; | |
432 | } | |
433 | this.oppid = oppId; | |
434 | this.oppConnected = true; | |
435 | this.mycolor = color; | |
436 | } | |
437 | else //against computer | |
438 | { | |
439 | this.mycolor = Math.random() < 0.5 ? 'w' : 'b'; | |
440 | if (this.mycolor == 'b') | |
441 | setTimeout(this.playComputerMove, 500); | |
442 | } | |
443 | }, | |
444 | playComputerMove: function() { | |
445 | const compColor = this.mycolor=='w' ? 'b' : 'w'; | |
446 | const compMove = this.vr.getComputerMove(compColor); | |
447 | // HACK: avoid selecting elements before they appear on page: | |
448 | setTimeout(() => this.play(compMove, "animate"), 500); | |
449 | }, | |
450 | // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y. | |
451 | getSquareId: function(o) { | |
452 | // NOTE: a separator is required to allow any size of board | |
453 | return "sq-" + o.x + "-" + o.y; | |
454 | }, | |
455 | // Inverse function | |
456 | getSquareFromId: function(id) { | |
457 | let idParts = id.split('-'); | |
458 | return [parseInt(idParts[1]), parseInt(idParts[2])]; | |
459 | }, | |
460 | mousedown: function(e) { | |
461 | e = e || window.event; | |
462 | e.preventDefault(); //disable native drag & drop | |
463 | if (!this.selectedPiece && e.target.classList.contains("piece")) | |
464 | { | |
465 | // Next few lines to center the piece on mouse cursor | |
466 | let rect = e.target.parentNode.getBoundingClientRect(); | |
467 | this.start = { | |
468 | x: rect.x + rect.width/2, | |
469 | y: rect.y + rect.width/2, | |
470 | id: e.target.parentNode.id | |
471 | }; | |
472 | this.selectedPiece = e.target.cloneNode(); | |
473 | this.selectedPiece.style.position = "absolute"; | |
474 | this.selectedPiece.style.top = 0; | |
475 | this.selectedPiece.style.display = "inline-block"; | |
476 | this.selectedPiece.style.zIndex = 3000; | |
477 | let startSquare = this.getSquareFromId(e.target.parentNode.id); | |
478 | this.possibleMoves = this.vr.canIplay(this.mycolor,startSquare) | |
479 | ? this.vr.getPossibleMovesFrom(startSquare) | |
480 | : []; | |
481 | e.target.parentNode.appendChild(this.selectedPiece); | |
482 | } | |
483 | }, | |
484 | mousemove: function(e) { | |
485 | if (!this.selectedPiece) | |
486 | return; | |
487 | e = e || window.event; | |
488 | // If there is an active element, move it around | |
489 | if (!!this.selectedPiece) | |
490 | { | |
491 | this.selectedPiece.style.left = (e.clientX-this.start.x) + "px"; | |
492 | this.selectedPiece.style.top = (e.clientY-this.start.y) + "px"; | |
493 | } | |
494 | }, | |
495 | mouseup: function(e) { | |
496 | if (!this.selectedPiece) | |
497 | return; | |
498 | e = e || window.event; | |
499 | // Read drop target (or parentElement, parentNode... if type == "img") | |
500 | this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates | |
501 | let landing = document.elementFromPoint(e.clientX, e.clientY); | |
502 | this.selectedPiece.style.zIndex = 3000; | |
503 | while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight | |
504 | landing = landing.parentNode; | |
505 | if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled | |
506 | return; | |
507 | // OK: process move attempt | |
508 | let endSquare = this.getSquareFromId(landing.id); | |
509 | let moves = this.findMatchingMoves(endSquare); | |
510 | this.possibleMoves = []; | |
511 | if (moves.length > 1) | |
512 | this.choices = moves; | |
513 | else if (moves.length==1) | |
514 | this.play(moves[0]); | |
515 | // Else: impossible move | |
516 | this.selectedPiece.parentNode.removeChild(this.selectedPiece); | |
517 | delete this.selectedPiece; | |
518 | this.selectedPiece = null; | |
519 | }, | |
520 | findMatchingMoves: function(endSquare) { | |
521 | // Run through moves list and return the matching set (if promotions...) | |
522 | let moves = []; | |
523 | this.possibleMoves.forEach(function(m) { | |
524 | if (endSquare[0] == m.end.x && endSquare[1] == m.end.y) | |
525 | moves.push(m); | |
526 | }); | |
527 | return moves; | |
528 | }, | |
529 | animateMove: function(move) { | |
530 | let startSquare = document.getElementById(this.getSquareId(move.start)); | |
531 | let endSquare = document.getElementById(this.getSquareId(move.end)); | |
532 | let rectStart = startSquare.getBoundingClientRect(); | |
533 | let rectEnd = endSquare.getBoundingClientRect(); | |
534 | let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y}; | |
535 | let movingPiece = document.querySelector("#" + this.getSquareId(move.start) + " > img.piece"); | |
536 | // HACK for animation (otherwise with positive translate, image slides "under background"...) | |
537 | // Possible improvement: just alter squares on the piece's way... | |
538 | squares = document.getElementsByClassName("board"); | |
539 | for (let i=0; i<squares.length; i++) | |
540 | { | |
541 | let square = squares.item(i); | |
542 | if (square.id != this.getSquareId(move.start)) | |
543 | square.style.zIndex = "-1"; | |
544 | } | |
545 | movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)"; | |
546 | movingPiece.style.transitionDuration = "0.2s"; | |
547 | movingPiece.style.zIndex = "3000"; | |
548 | setTimeout( () => { | |
549 | for (let i=0; i<squares.length; i++) | |
550 | squares.item(i).style.zIndex = "auto"; | |
551 | movingPiece.style = {}; //required e.g. for 0-0 with KR swap | |
552 | this.play(move); | |
553 | }, 200); | |
554 | }, | |
555 | play: function(move, programmatic) { | |
556 | if (!!programmatic) //computer or human opponent | |
557 | { | |
558 | this.animateMove(move); | |
559 | return; | |
560 | } | |
561 | // Not programmatic, or animation is over | |
562 | if (this.mode == "human" && this.vr.turn == this.mycolor) | |
563 | { | |
564 | if (!this.oppConnected) | |
565 | return; //abort move if opponent is gone | |
0cb758e0 BA |
566 | try { |
567 | this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid})); | |
568 | } catch(INVALID_STATE_ERR) { | |
d35f20e4 | 569 | return; //abort also if sending failed |
0cb758e0 | 570 | } |
1d184b4c BA |
571 | } |
572 | new Audio("/sounds/chessmove1.mp3").play(); | |
573 | this.vr.play(move, "ingame"); | |
574 | if (this.mode == "human") | |
575 | this.updateStorage(); //after our moves and opponent moves | |
576 | const eog = this.vr.checkGameOver(this.vr.turn); | |
577 | if (eog != "*") | |
578 | this.endGame(eog); | |
579 | else if (this.mode == "computer" && this.vr.turn != this.mycolor) | |
580 | setTimeout(this.playComputerMove, 500); | |
581 | }, | |
582 | }, | |
583 | }) |