<commit_before>import * as round from './round';
import { game, status } from 'game';
import * as ground from './ground';
import { make as makeSocket, RoundSocket } from './socket';
import * as title from './title';
import * as promotion from './promotion';
import * as blur from './blur';
import * as blind from './blind';
import * as cg from 'chessground/types';
import { Config as CgConfig } from 'chessground/config';
import { Api as CgApi } from 'chessground/api';
import { ClockController } from './clock/clockCtrl';
import { CorresClockController, ctrl as makeCorresClock } from './corresClock/corresClockCtrl';
import MoveOn from './moveOn';
import atomic = require('./atomic');
import sound = require('./sound');
import util = require('./util');
import xhr = require('./xhr');
import { valid as crazyValid } from './crazy/crazyCtrl';
import { ctrl as makeKeyboardMove, KeyboardMove } from './keyboardMove';
import renderUser = require('./view/user');
import cevalSub = require('./cevalSub');
import * as keyboard from './keyboard';

import { RoundOpts, RoundData, ApiMove, ApiEnd, Redraw, SocketMove, SocketDrop, SocketOpts, MoveMetadata } from './interfaces';

interface GoneBerserk {
  white?: boolean;
  black?: boolean;
};

const li = window.lichess;

export default class RoundController {

  opts: RoundOpts;
  data: RoundData;
  redraw: Redraw;
  socket: RoundSocket;
  chessground: CgApi;
  clock?: ClockController;
  corresClock?: CorresClockController;
  trans: Trans;
  keyboardMove?: KeyboardMove;
  moveOn: MoveOn;

  ply: number;
  firstSeconds: boolean = true;
  flip: boolean = false;
  loading: boolean = false;
  loadingTimeout: number;
  redirecting: boolean = false;
  moveToSubmit?: SocketMove;
  dropToSubmit?: SocketDrop;
  goneBerserk: GoneBerserk = {};
  resignConfirm: boolean = false;
  drawConfirm: boolean = false;
  autoScroll: () => void = $.noop; // will be replaced by view layer
  challengeRematched: boolean = false;
  justDropped?: cg.Role;
  justCaptured?: cg.Piece;
  shouldSendMoveTime: boolean = false;
  preDrop?: cg.Role;
  lastDrawOfferAtPly?: Ply;

  private music?: any;

  constructor(opts: RoundOpts, redraw: Redraw) {

    round.massage(opts.data);

    const d = this.data = opts.data;

    this.opts = opts;
    this.redraw = redraw;

    this.ply = round.lastPly(d);
    this.goneBerserk[d.player.color] = d.player.berserk;
    this.goneBerserk[d.opponent.color] = d.opponent.berserk;

    setTimeout(() => { this.firstSeconds = false; this.redraw(); }, 3000);

    this.socket = makeSocket(opts.socketSend, this);

    if (d.clock) this.clock = new ClockController(d, {
      onFlag: () => { this.socket.outoftime(); this.redraw(); },
      soundColor: (d.simul || d.player.spectator || !d.pref.clockSound) ? undefined : d.player.color
    });
    else this.makeCorrespondenceClock();

    if (this.clock) {
      const tickNow = () => {
        this.clock!.tick();
        if (game.playable(this.data)) setTimeout(tickNow, 100);
      };
      setTimeout(tickNow, 100);
    } else setInterval(this.corresClockTick, 1000);

    this.setQuietMode();

    this.moveOn = new MoveOn(this, 'lichess.move_on');

    this.trans = li.trans(opts.i18n);

    setTimeout(this.delayedInit, 200);

    setTimeout(this.showYourMoveNotification, 500);

    // at the end:
    li.pubsub.on('jump', ply => { this.jump(parseInt(ply)); this.redraw(); });

    li.pubsub.on('sound_set', set => {
      if (!this.music && set === 'music')
        li.loadScript('/assets/javascripts/music/play.js').then(() => {
          this.music = window.lichessPlayMusic();
        });
        if (this.music && set !== 'music') this.music = undefined;
    });
  }

  private onUserMove = (orig: cg.Key, dest: cg.Key, meta: cg.MoveMetadata) => {
    if (li.ab && (!this.keyboardMove || !this.keyboardMove.usedSan)) li.ab(this, meta);
    if (!promotion.start(this, orig, dest, meta)) this.sendMove(orig, dest, undefined, meta);
  };

  private onUserNewPiece = (role: cg.Role, key: cg.Key, meta: cg.MoveMetadata) => {
    if (!this.replaying() && crazyValid(this.data, role, key)) {
      this.sendNewPiece(role, key, !!meta.predrop);
    } else this.jump(this.ply);
  };

  private onMove = (_: cg.Key, dest: cg.Key, captured?: cg.Piece) => {
    if (captured) {
      if (this.data.game.variant.key === 'atomic') {
        sound.explode();
        atomic.capture(this, dest);
      } else sound.capture();
    } else sound.move();
  };

  private onPremove = (orig: cg.Key, dest: cg.Key, meta: cg.MoveMetadata) => {
    promotion.start(this, orig, dest, meta);
  };

  private onCancelPremove = () => {
    promotion.cancelPrePromotion(this);
  };

  private onPredrop = (role: cg.Role | undefined, _?: Key) => {
    this.preDrop = role;
    this.redraw();
  };

  makeCgHooks = () => ({
    onUserMove: this.onUserMove,
    onUserNewPiece: this.onUserNewPiece,
    onMove: this.onMove,
    onNewPiece: sound.move,
    onPremove: this.onPremove,
    onCancelPremove: this.onCancelPremove,
    onPredrop: this.onPredrop
  });

  replaying = (): boolean => this.ply !== round.lastPly(this.data);

  userJump = (ply: Ply): void => {
    this.cancelMove();
    this.chessground.selectSquare(null);
    this.jump(ply);
  };

  jump = (ply: Ply): boolean => {
    if (ply < round.firstPly(this.data) || ply > round.lastPly(this.data)) return false;
    this.ply = ply;
    this.justDropped = undefined;
    this.preDrop = undefined;
    const s = round.plyStep(this.data, ply),
    config: CgConfig = {
      fen: s.fen,
      lastMove: util.uci2move(s.uci),
      check: !!s.check,
      turnColor: this.ply % 2 === 0 ? 'white' : 'black'
    };
    if (this.replaying()) this.chessground.stop();
    else config.movable = {
      color: game.isPlayerPlaying(this.data) ? this.data.player.color : undefined,
      dests: util.parsePossibleMoves(this.data.possibleMoves)
    }
    this.chessground.set(config);
    if (s.san) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
      if (/[+#]/.test(s.san)) sound.check();
    }
    this.autoScroll();
    if (this.keyboardMove) this.keyboardMove.update(s);
    return true;
  };

  replayEnabledByPref = (): boolean => {<commit_msg>don't play the move sound on game end<commit_after>import * as round from './round';
import { game, status } from 'game';
import * as ground from './ground';
import { make as makeSocket, RoundSocket } from './socket';
import * as title from './title';
import * as promotion from './promotion';
import * as blur from './blur';
import * as blind from './blind';
import * as cg from 'chessground/types';
import { Config as CgConfig } from 'chessground/config';
import { Api as CgApi } from 'chessground/api';
import { ClockController } from './clock/clockCtrl';
import { CorresClockController, ctrl as makeCorresClock } from './corresClock/corresClockCtrl';
import MoveOn from './moveOn';
import atomic = require('./atomic');
import sound = require('./sound');
import util = require('./util');
import xhr = require('./xhr');
import { valid as crazyValid } from './crazy/crazyCtrl';
import { ctrl as makeKeyboardMove, KeyboardMove } from './keyboardMove';
import renderUser = require('./view/user');
import cevalSub = require('./cevalSub');
import * as keyboard from './keyboard';

import { RoundOpts, RoundData, ApiMove, ApiEnd, Redraw, SocketMove, SocketDrop, SocketOpts, MoveMetadata } from './interfaces';

interface GoneBerserk {
  white?: boolean;
  black?: boolean;
};

const li = window.lichess;

export default class RoundController {

  opts: RoundOpts;
  data: RoundData;
  redraw: Redraw;
  socket: RoundSocket;
  chessground: CgApi;
  clock?: ClockController;
  corresClock?: CorresClockController;
  trans: Trans;
  keyboardMove?: KeyboardMove;
  moveOn: MoveOn;

  ply: number;
  firstSeconds: boolean = true;
  flip: boolean = false;
  loading: boolean = false;
  loadingTimeout: number;
  redirecting: boolean = false;
  moveToSubmit?: SocketMove;
  dropToSubmit?: SocketDrop;
  goneBerserk: GoneBerserk = {};
  resignConfirm: boolean = false;
  drawConfirm: boolean = false;
  autoScroll: () => void = $.noop; // will be replaced by view layer
  challengeRematched: boolean = false;
  justDropped?: cg.Role;
  justCaptured?: cg.Piece;
  shouldSendMoveTime: boolean = false;
  preDrop?: cg.Role;
  lastDrawOfferAtPly?: Ply;

  private music?: any;

  constructor(opts: RoundOpts, redraw: Redraw) {

    round.massage(opts.data);

    const d = this.data = opts.data;

    this.opts = opts;
    this.redraw = redraw;

    this.ply = round.lastPly(d);
    this.goneBerserk[d.player.color] = d.player.berserk;
    this.goneBerserk[d.opponent.color] = d.opponent.berserk;

    setTimeout(() => { this.firstSeconds = false; this.redraw(); }, 3000);

    this.socket = makeSocket(opts.socketSend, this);

    if (d.clock) this.clock = new ClockController(d, {
      onFlag: () => { this.socket.outoftime(); this.redraw(); },
      soundColor: (d.simul || d.player.spectator || !d.pref.clockSound) ? undefined : d.player.color
    });
    else this.makeCorrespondenceClock();

    if (this.clock) {
      const tickNow = () => {
        this.clock!.tick();
        if (game.playable(this.data)) setTimeout(tickNow, 100);
      };
      setTimeout(tickNow, 100);
    } else setInterval(this.corresClockTick, 1000);

    this.setQuietMode();

    this.moveOn = new MoveOn(this, 'lichess.move_on');

    this.trans = li.trans(opts.i18n);

    setTimeout(this.delayedInit, 200);

    setTimeout(this.showYourMoveNotification, 500);

    // at the end:
    li.pubsub.on('jump', ply => { this.jump(parseInt(ply)); this.redraw(); });

    li.pubsub.on('sound_set', set => {
      if (!this.music && set === 'music')
        li.loadScript('/assets/javascripts/music/play.js').then(() => {
          this.music = window.lichessPlayMusic();
        });
        if (this.music && set !== 'music') this.music = undefined;
    });
  }

  private onUserMove = (orig: cg.Key, dest: cg.Key, meta: cg.MoveMetadata) => {
    if (li.ab && (!this.keyboardMove || !this.keyboardMove.usedSan)) li.ab(this, meta);
    if (!promotion.start(this, orig, dest, meta)) this.sendMove(orig, dest, undefined, meta);
  };

  private onUserNewPiece = (role: cg.Role, key: cg.Key, meta: cg.MoveMetadata) => {
    if (!this.replaying() && crazyValid(this.data, role, key)) {
      this.sendNewPiece(role, key, !!meta.predrop);
    } else this.jump(this.ply);
  };

  private onMove = (_: cg.Key, dest: cg.Key, captured?: cg.Piece) => {
    if (captured) {
      if (this.data.game.variant.key === 'atomic') {
        sound.explode();
        atomic.capture(this, dest);
      } else sound.capture();
    } else sound.move();
  };

  private onPremove = (orig: cg.Key, dest: cg.Key, meta: cg.MoveMetadata) => {
    promotion.start(this, orig, dest, meta);
  };

  private onCancelPremove = () => {
    promotion.cancelPrePromotion(this);
  };

  private onPredrop = (role: cg.Role | undefined, _?: Key) => {
    this.preDrop = role;
    this.redraw();
  };

  makeCgHooks = () => ({
    onUserMove: this.onUserMove,
    onUserNewPiece: this.onUserNewPiece,
    onMove: this.onMove,
    onNewPiece: sound.move,
    onPremove: this.onPremove,
    onCancelPremove: this.onCancelPremove,
    onPredrop: this.onPredrop
  });

  replaying = (): boolean => this.ply !== round.lastPly(this.data);

  userJump = (ply: Ply): void => {
    this.cancelMove();
    this.chessground.selectSquare(null);
    this.jump(ply);
  };

  jump = (ply: Ply): boolean => {
    if (ply < round.firstPly(this.data) || ply > round.lastPly(this.data)) return false;
    const samePly = this.ply === ply;
    this.ply = ply;
    this.justDropped = undefined;
    this.preDrop = undefined;
    const s = round.plyStep(this.data, ply),
    config: CgConfig = {
      fen: s.fen,
      lastMove: util.uci2move(s.uci),
      check: !!s.check,
      turnColor: this.ply % 2 === 0 ? 'white' : 'black'
    };
    if (this.replaying()) this.chessground.stop();
    else config.movable = {
      color: game.isPlayerPlaying(this.data) ? this.data.player.color : undefined,
      dests: util.parsePossibleMoves(this.data.possibleMoves)
    }
    this.chessground.set(config);
    if (s.san && !samePly) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
      if (/[+#]/.test(s.san)) sound.check();
    }
    this.autoScroll();
    if (this.keyboardMove) this.keyboardMove.update(s);
    return true;
  };

  replayEnabledByPref = (): boolean => {
{'fraction_non_alphanumeric': 0.15978312868760963, 'fraction_numerical': 0.004146069207462925, 'mean_word_length': 3.371906587661206, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '313229', 'n_tokens_mistral': 4343, 'n_tokens_neox': 4200, 'n_words': 962}