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