+ loadGame: function(game) {
+ const afterRetrieval = async (game) => {
+ const vModule = await import("@/variants/" + game.vname + ".js");
+ window.V = vModule.VariantRules;
+ this.vr = new V(game.fen);
+ const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
+ this.game = Object.assign({},
+ game,
+ // NOTE: assign mycolor here, since BaseGame could also bs VS computer
+ {
+ mycolor: [undefined,"w","b"][myIdx+1],
+ // opponent sid not strictly required, but easier
+ oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
+ }
+ );
+ if (!!this.game.oppid)
+ {
+ // Send ping to server (answer pong if players[s] are connected)
+ this.st.conn.send(JSON.stringify({code:"ping",
+ target:this.game.oppid, gameId:this.gameRef.id}));
+ }
+ };
+ if (!!game)
+ return afterRetrival(game);
+ if (!!this.gameRef.rid)
+ {
+ // TODO: just send a game request message to the remote player,
+ // and when receiving answer just call loadGame(received_game)
+ // + remote peer should have registered us as an observer
+ // (send moves updates + resign/abort/draw actions)
+ }
+ else
+ {
+ GameStorage.get(this.gameRef.id, async (game) => {
+ afterRetrieval(game);
+ });
+ }
+ },
+ // Post-process a move (which was just played)
+ processMove: function(move) {
+ if (!this.game.mycolor)
+ return; //I'm just an observer
+ // Update storage (corr or live)
+ const colorIdx = ["w","b"].indexOf(move.color);
+ // https://stackoverflow.com/a/38750895
+ const allowed_fields = ["appear", "vanish", "start", "end"];
+ const filtered_move = Object.keys(move)
+ .filter(key => allowed_fields.includes(key))
+ .reduce((obj, key) => {
+ obj[key] = move[key];
+ return obj;
+ }, {});
+ // Send move ("newmove" event) to opponent(s) (if ours)
+ let addTime = undefined;
+ if (move.color == this.game.mycolor)
+ {
+ const elapsed = Date.now() - this.game.initime[colorIdx];
+ // elapsed time is measured in milliseconds
+ addTime = this.game.increment - elapsed/1000;
+ this.st.conn.send(JSON.stringify({
+ code: "newmove",
+ target: this.game.oppid,
+ move: Object.assign({}, filtered_move, {addTime: addTime}),
+ }));
+ }
+ else
+ addTime = move.addTime; //supposed transmitted
+ const nextIdx = ["w","b"].indexOf(this.vr.turn);
+ GameStorage.update(this.gameRef.id,
+ {
+ colorIdx: colorIdx,
+ nextIdx: nextIdx,
+ move: filtered_move,
+ fen: move.fen,
+ addTime: addTime,
+ });
+ // Also update current game object:
+ this.game.moves.push(move);
+ this.game.fen = move.fen;
+ //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
+ this.$set(this.game.clocks, colorIdx,
+ this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
+ this.game.initime[nextIdx] = Date.now();