Fix footer alignment
[vchess.git] / client / src / components / Game.vue
CommitLineData
cf2343ce
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 input#modalEog.modal(type="checkbox")
5 div(role="dialog" aria-labelledby="eogMessage")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
9 Chat(v-if="showChat" :opponents="opponents" :people="people")
10 Board(:vr="vr" :last-move="lastMove" :mode="mode" :user-color="mycolor"
11 :orientation="orientation" @play-move="play")
12 .button-group
13 button(@click="() => play()") Play
14 button(@click="() => undo()") Undo
15 button(@click="flip") Flip
16 button(@click="gotoBegin") GotoBegin
17 button(@click="gotoEnd") GotoEnd
18 .button-group(v-if="mode=='human'")
19 button(@click="offerDraw") Draw
20 button(@click="abortGame") Abort
21 button(@click="resign") Resign
22 div(v-if="mode=='human' && subMode=='corr'")
23 textarea(v-show="score=='*' && vr.turn==mycolor" v-model="corrMsg")
24 div(v-show="cursor>=0") {{ moves[cursor].message }}
25 .section-content(v-if="showFen && !!vr" id="fen-div")
26 p#fenString.text-center {{ vr.getFen() }}
27 #pgnDiv.section-content
28 a#download(href="#")
29 .button-group
30 button#downloadBtn(@click="download") {{ st.tr["Download PGN"] }}
31 button Import game
32 MoveList(v-if="showMoves"
33 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
34</template>
35
36<script>
37// Game logic on a variant page: 3 modes, analyze, computer or human
38// TODO: envoyer juste "light move", sans FEN ni notation ...etc
39// TODO: if I'm an observer and player(s) disconnect/reconnect, how to find me ?
40// onClick :: ask full game to remote player, and register as an observer in game
41// (use gameId to communicate)
42// on landing on game :: if gameId not found locally, check remotely
43// ==> il manque un param dans game : "remoteId"
44// TODO: import store, st
45import Board from "@/components/Board.vue";
46import Chat from "@/components/Chat.vue";
47import MoveList from "@/components/MoveList.vue";
48export default {
49 name: 'my-game',
50 // gameId: to find the game in storage (assumption: it exists)
51 // fen: to start from a FEN without identifiers (analyze mode)
52 // subMode: "auto" (game comp vs comp) or "corr" (correspondance game),
53 // or "examine" (after human game: TODO)
54 // gameRef in URL hash (listen for changes)
55 props: ["fen","mode","subMode"],
56 data: function() {
57 return {
58 gameRef: "",
59 // Web worker to play computer moves without freezing interface:
60 compWorker: new Worker('/javascripts/playCompMove.js'),
61 timeStart: undefined, //time when computer starts thinking
62 vr: null, //VariantRules object, describing the game state + rules
63 endgameMessage: "",
64 orientation: "w",
65 lockCompThink: false, //to avoid some ghost moves
66 myname: user.name, //may be anonymous (thus no name)
67 opponents: {}, //filled later (potentially 2 or 3 opponents)
68 drawOfferSent: false, //did I just ask for draw?
69 people: {}, //observers
70 score: "*", //'*' means 'unfinished'
71 // userColor: given by gameId, or fen in problems mode (if no game Id)...
72 mycolor: "w",
73 fenStart: "",
74 moves: [], //TODO: initialize if gameId is defined...
75 cursor: -1, //index of the move just played
76 lastMove: null,
77 };
78 },
79// watch: {
80// fen: function() {
81// // (Security) No effect if a computer move is in progress:
82// if (this.mode == "computer" && this.lockCompThink)
83// return this.$emit("computer-think");
84// this.newGameFromFen();
85// },
86//// // TODO: $route: ...
87//// gameRef: function() {
88//// this.loadGame();
89//// },
90// },
91// computed: {
92// showChat: function() {
93// return this.mode=='human' && this.score != '*';
94// },
95// showMoves: function() {
96// return true;
97// //return window.innerWidth >= 768;
98// },
99// showFen: function() {
100// return variant.name != "Dark" || this.score != "*";
101// },
102// },
103// // Modal end of game, and then sub-components
104// created: function() {
105// if (!!this.gameRef)
106// this.loadGame();
107// else if (!!this.fen)
108// {
109// this.vr = new V(this.fen);
110// this.fenStart = this.fen;
111// }
112// // TODO: if I'm one of the players in game, then:
113// // Send ping to server (answer pong if opponent is connected)
114// if (true && !!this.conn && !!this.gameRef)
115// {
116// this.conn.onopen = () => {
117// this.conn.send(JSON.stringify({
118// code:"ping",oppid:this.oppid,gameId:this.gameRef.id}));
119// };
120// }
121// // TODO: also handle "draw accepted" (use opponents array?)
122// // --> must give this info also when sending lastState...
123// // and, if all players agree then OK draw (end game ...etc)
124// const socketMessageListener = msg => {
125// const data = JSON.parse(msg.data);
126// let L = undefined;
127// switch (data.code)
128// {
129// case "newmove": //..he played!
130// this.play(data.move, variant.name!="Dark" ? "animate" : null);
131// break;
132// case "pong": //received if we sent a ping (game still alive on our side)
133// if (this.gameRef.id != data.gameId)
134// break; //games IDs don't match: definitely over...
135// this.oppConnected = true;
136// // Send our "last state" informations to opponent(s)
137// L = this.vr.moves.length;
138// Object.keys(this.opponents).forEach(oid => {
139// this.conn.send(JSON.stringify({
140// code: "lastate",
141// oppid: oid,
142// gameId: this.gameRef.id,
143// lastMove: (L>0?this.vr.moves[L-1]:undefined),
144// movesCount: L,
145// }));
146// });
147// break;
148// // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves (not just one)
149// case "lastate": //got opponent infos about last move
150// L = this.vr.moves.length;
151// if (this.gameRef.id != data.gameId)
152// break; //games IDs don't match: nothing we can do...
153// // OK, opponent still in game (which might be over)
154// if (this.score != "*")
155// {
156// // We finished the game (any result possible)
157// this.conn.send(JSON.stringify({
158// code: "lastate",
159// oppid: data.oppid,
160// gameId: this.gameRef.id,
161// score: this.score,
162// }));
163// }
164// else if (!!data.score) //opponent finished the game
165// this.endGame(data.score);
166// else if (data.movesCount < L)
167// {
168// // We must tell last move to opponent
169// this.conn.send(JSON.stringify({
170// code: "lastate",
171// oppid: this.opponent.id,
172// gameId: this.gameRef.id,
173// lastMove: this.vr.moves[L-1],
174// movesCount: L,
175// }));
176// }
177// else if (data.movesCount > L) //just got last move from him
178// this.play(data.lastMove, "animate");
179// break;
180// case "resign": //..you won!
181// this.endGame(this.mycolor=="w"?"1-0":"0-1");
182// break;
183// // TODO: also use (dis)connect info to count online players?
184// case "connect":
185// case "disconnect":
186// if (this.mode=="human")
187// {
188// const online = (data.code == "connect");
189// // If this is an opponent ?
190// if (!!this.opponents[data.id])
191// this.opponents[data.id].online = online;
192// else
193// {
194// // Or an observer ?
195// if (!online)
196// delete this.people[data.id];
197// else
198// this.people[data.id] = data.name;
199// }
200// }
201// break;
202// }
203// };
204// const socketCloseListener = () => {
205// this.conn.addEventListener('message', socketMessageListener);
206// this.conn.addEventListener('close', socketCloseListener);
207// };
208// if (!!this.conn)
209// {
210// this.conn.onmessage = socketMessageListener;
211// this.conn.onclose = socketCloseListener;
212// }
213// // Computer moves web worker logic: (TODO: also for observers in HH games ?)
214// this.compWorker.postMessage(["scripts",variant.name]);
215// this.compWorker.onmessage = e => {
216// this.lockCompThink = true; //to avoid some ghost moves
217// let compMove = e.data;
218// if (!Array.isArray(compMove))
219// compMove = [compMove]; //to deal with MarseilleRules
220// // Small delay for the bot to appear "more human"
221// const delay = Math.max(500-(Date.now()-this.timeStart), 0);
222// setTimeout(() => {
223// const animate = variant.name != "Dark";
224// this.play(compMove[0], animate);
225// if (compMove.length == 2)
226// setTimeout( () => { this.play(compMove[1], animate); }, 750);
227// else //250 == length of animation (TODO: should be a constant somewhere)
228// setTimeout( () => this.lockCompThink = false, 250);
229// }, delay);
230// }
231// },
232// // dans variant.js (plutôt room.js) conn gère aussi les challenges
233// // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
234// methods: {
235// offerDraw: function() {
236// if (!confirm("Offer draw?"))
237// return;
238// // Stay in "draw offer sent" state until next move is played
239// this.drawOfferSent = true;
240// if (this.subMode == "corr")
241// {
242// // TODO: set drawOffer on in game (how ?)
243// }
244// else //live game
245// {
246// this.opponents.forEach(o => {
247// if (!!o.online)
248// {
249// try {
250// this.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
251// } catch (INVALID_STATE_ERR) {
252// return;
253// }
254// }
255// });
256// }
257// },
258// // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
259// receiveDrawOffer: function() {
260// //if (...)
261// // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
262// // if accept: send message "draw"
263// },
264// abortGame: function() {
265// if (!confirm("Abort the game?"))
266// return;
267// //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
268// //send message: "gameOver" avec score "?"
269// },
270// resign: function(e) {
271// if (!confirm("Resign the game?"))
272// return;
273// if (this.mode == "human" && this.oppConnected(this.oppid))
274// {
275// try {
276// this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
277// } catch (INVALID_STATE_ERR) {
278// return;
279// }
280// }
281// this.endGame(this.mycolor=="w"?"0-1":"1-0");
282// },
283// translate: translate,
284// newGameFromFen: function() {
285// this.vr = new V(this.fen);
286// this.moves = [];
287// this.cursor = -1;
288// this.fenStart = this.fen;
289// this.score = "*";
290// if (this.mode == "analyze")
291// {
292// this.mycolor = V.ParseFen(this.fen).turn;
293// this.orientation = this.mycolor;
294// }
295// else if (this.mode == "computer") //only other alternative (HH with gameId)
296// {
297// this.mycolor = (Math.random() < 0.5 ? "w" : "b");
298// this.orientation = this.mycolor;
299// this.compWorker.postMessage(["init",this.fen]);
300// if (this.mycolor != "w" || this.subMode == "auto")
301// this.playComputerMove();
302// }
303// },
304// loadGame: function() {
305// // TODO: ask game to remote peer if this.remoteId is set
306// // (or just if game not found locally)
307// // NOTE: if it's a corr game, ask it from server
308// const game = getGameFromStorage(this.gameRef.id, this.gameRef.uid); //uid may be blank
309// this.opponent.id = game.oppid; //opponent ID in case of running HH game
310// this.opponent.name = game.oppname; //maye be blank (if anonymous)
311// this.score = game.score;
312// this.mycolor = game.mycolor;
313// this.fenStart = game.fenStart;
314// this.moves = game.moves;
315// this.cursor = game.moves.length-1;
316// this.lastMove = (game.moves.length > 0 ? game.moves[this.cursor] : null);
317// },
318// setEndgameMessage: function(score) {
319// let eogMessage = "Undefined";
320// switch (score)
321// {
322// case "1-0":
323// eogMessage = translations["White win"];
324// break;
325// case "0-1":
326// eogMessage = translations["Black win"];
327// break;
328// case "1/2":
329// eogMessage = translations["Draw"];
330// break;
331// case "?":
332// eogMessage = "Unfinished";
333// break;
334// }
335// this.endgameMessage = eogMessage;
336// },
337// download: function() {
338// const content = this.getPgn();
339// // Prepare and trigger download link
340// let downloadAnchor = document.getElementById("download");
341// downloadAnchor.setAttribute("download", "game.pgn");
342// downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
343// downloadAnchor.click();
344// },
345// getPgn: function() {
346// let pgn = "";
347// pgn += '[Site "vchess.club"]\n';
348// const opponent = (this.mode=="human" ? "Anonymous" : "Computer");
349// pgn += '[Variant "' + variant.name + '"]\n';
350// pgn += '[Date "' + getDate(new Date()) + '"]\n';
351// const whiteName = ["human","computer"].includes(this.mode)
352// ? (this.mycolor=='w'?'Myself':opponent)
353// : "analyze";
354// const blackName = ["human","computer"].includes(this.mode)
355// ? (this.mycolor=='b'?'Myself':opponent)
356// : "analyze";
357// pgn += '[White "' + whiteName + '"]\n';
358// pgn += '[Black "' + blackName + '"]\n';
359// pgn += '[Fen "' + this.fenStart + '"]\n';
360// pgn += '[Result "' + this.score + '"]\n\n';
361// let counter = 1;
362// let i = 0;
363// while (i < this.moves.length)
364// {
365// pgn += (counter++) + ".";
366// for (let color of ["w","b"])
367// {
368// let move = "";
369// while (i < this.moves.length && this.moves[i].color == color)
370// move += this.moves[i++].notation[0] + ",";
371// move = move.slice(0,-1); //remove last comma
372// pgn += move + (i < this.moves.length-1 ? " " : "");
373// }
374// }
375// return pgn + "\n";
376// },
377// showScoreMsg: function(score) {
378// this.setEndgameMessage(score);
379// let modalBox = document.getElementById("modal-eog");
380// modalBox.checked = true;
381// setTimeout(() => { modalBox.checked = false; }, 2000);
382// },
383// endGame: function(score) {
384// this.score = score;
385// this.showScoreMsg(score);
386// if (this.mode == "human")
387// localStorage["score"] = score;
388// this.$emit("game-over");
389// },
390// oppConnected: function(uid) {
391// return this.opponents.any(o => o.id == uidi && o.online);
392// },
393// playComputerMove: function() {
394// this.timeStart = Date.now();
395// this.compWorker.postMessage(["askmove"]);
396// },
397// animateMove: function(move) {
398// let startSquare = document.getElementById(getSquareId(move.start));
399// let endSquare = document.getElementById(getSquareId(move.end));
400// let rectStart = startSquare.getBoundingClientRect();
401// let rectEnd = endSquare.getBoundingClientRect();
402// let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
403// let movingPiece =
404// document.querySelector("#" + getSquareId(move.start) + " > img.piece");
405// // HACK for animation (with positive translate, image slides "under background")
406// // Possible improvement: just alter squares on the piece's way...
407// squares = document.getElementsByClassName("board");
408// for (let i=0; i<squares.length; i++)
409// {
410// let square = squares.item(i);
411// if (square.id != getSquareId(move.start))
412// square.style.zIndex = "-1";
413// }
414// movingPiece.style.transform = "translate(" + translation.x + "px," +
415// translation.y + "px)";
416// movingPiece.style.transitionDuration = "0.2s";
417// movingPiece.style.zIndex = "3000";
418// setTimeout( () => {
419// for (let i=0; i<squares.length; i++)
420// squares.item(i).style.zIndex = "auto";
421// movingPiece.style = {}; //required e.g. for 0-0 with KR swap
422// this.play(move);
423// }, 250);
424// },
425// play: function(move, programmatic) {
426// let navigate = !move;
427// // Forbid playing outside analyze mode when cursor isn't at moves.length-1
428// // (except if we receive opponent's move, human or computer)
429// if (!navigate && this.mode != "analyze" && !programmatic
430// && this.cursor < this.moves.length-1)
431// {
432// return;
433// }
434// if (navigate)
435// {
436// if (this.cursor == this.moves.length-1)
437// return; //no more moves
438// move = this.moves[this.cursor+1];
439// }
440// if (!!programmatic) //computer or (remote) human opponent
441// {
442// if (this.cursor < this.moves.length-1)
443// this.gotoEnd(); //required to play the move
444// return this.animateMove(move);
445// }
446// // Not programmatic, or animation is over
447// if (this.mode == "human" && this.subMode == "corr" && this.mycolor == this.vr.turn)
448// {
449// // TODO: show confirm box "validate move ?"
450// }
451// if (!move.notation)
452// move.notation = this.vr.getNotation(move);
453// if (!move.color)
454// move.color = this.vr.turn;
455// this.vr.play(move);
456// this.cursor++;
457// this.lastMove = move;
458// if (!move.fen)
459// move.fen = this.vr.getFen();
460// if (this.settings.sound == 2)
461// new Audio("/sounds/move.mp3").play().catch(err => {});
462// if (this.mode == "human")
463// {
464// updateStorage(move); //after our moves and opponent moves
465// if (this.vr.turn == this.mycolor)
466// this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
467// }
468// else if (this.mode == "computer")
469// {
470// // Send the move to web worker (including his own moves)
471// this.compWorker.postMessage(["newmove",move]);
472// }
473// if (!navigate && (this.score == "*" || this.mode == "analyze"))
474// {
475// // Stack move on movesList at current cursor
476// if (this.cursor == this.moves.length)
477// this.moves.push(move);
478// else
479// this.moves = this.moves.slice(0,this.cursor).concat([move]);
480// }
481// // Is opponent in check?
482// this.incheck = this.vr.getCheckSquares(this.vr.turn);
483// const score = this.vr.getCurrentScore();
484// if (score != "*")
485// {
486// if (["human","computer"].includes(this.mode))
487// this.endGame(score);
488// else //just show score on screen (allow undo)
489// this.showScoreMsg(score);
490// }
491// // subTurn condition for Marseille (and Avalanche) rules
492// else if ((this.mode == "computer" && (!this.vr.subTurn || this.vr.subTurn <= 1))
493// && (this.subMode == "auto" || this.vr.turn != this.mycolor))
494// {
495// this.playComputerMove();
496// }
497// // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
498// if (navigate)
499// this.$children[0].$forceUpdate(); //TODO!?
500// },
501// undo: function(move) {
502// let navigate = !move;
503// if (navigate)
504// {
505// if (this.cursor < 0)
506// return; //no more moves
507// move = this.moves[this.cursor];
508// }
509// this.vr.undo(move);
510// this.cursor--;
511// this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
512// if (this.settings.sound == 2)
513// new Audio("/sounds/undo.mp3").play().catch(err => {});
514// this.incheck = this.vr.getCheckSquares(this.vr.turn);
515// if (navigate)
516// this.$children[0].$forceUpdate(); //TODO!?
517// else if (this.mode == "analyze") //TODO: can this happen?
518// this.moves.pop();
519// },
520// gotoMove: function(index) {
521// this.vr = new V(this.moves[index].fen);
522// this.cursor = index;
523// this.lastMove = this.moves[index];
524// },
525// gotoBegin: function() {
526// this.vr = new V(this.fenStart);
527// this.cursor = -1;
528// this.lastMove = null;
529// },
530// gotoEnd: function() {
531// this.gotoMove(this.moves.length-1);
532// },
533// flip: function() {
534// this.orientation = V.GetNextCol(this.orientation);
535// },
536// },
537};
538</script>