X-Git-Url: https://git.auder.net/?a=blobdiff_plain;f=public%2Fjavascripts%2Fbase_rules.js;h=63b535dab609c5a8ff879b0b2e4066eaee7088af;hb=15c1295af871a5f416b0e5b43127512c8095497a;hp=a8f24893558a660f3b305210beb280aa2bdecc65;hpb=e82cd97976a6c7707467a384f7d6ca1daa9a0772;p=vchess.git diff --git a/public/javascripts/base_rules.js b/public/javascripts/base_rules.js index a8f24893..63b535da 100644 --- a/public/javascripts/base_rules.js +++ b/public/javascripts/base_rules.js @@ -727,8 +727,18 @@ class ChessRules this.kingPos[c] = [move.start.x, move.start.y]; } + // Hash of position+flags+turn after a move is played (to detect repetitions) + getHashState() + { + return hex_md5(this.getFen() + " " + this.turn); + } + play(move, ingame) { + // DEBUG: +// if (!this.states) this.states = []; +// if (!ingame) this.states.push(JSON.stringify(this.board)); + if (!!ingame) move.notation = [this.getNotation(move), this.getLongNotation(move)]; @@ -737,6 +747,9 @@ class ChessRules this.moves.push(move); this.epSquares.push( this.getEpSquare(move) ); VariantRules.PlayOnBoard(this.board, move); + + if (!!ingame) + move.hash = this.getHashState(); } undo(move) @@ -746,26 +759,34 @@ class ChessRules this.moves.pop(); this.unupdateVariables(move); this.parseFlags(JSON.parse(move.flags)); + + // DEBUG: +// if (JSON.stringify(this.board) != this.states[this.states.length-1]) +// debugger; +// this.states.pop(); } ////////////// // END OF GAME - // Basic check for 3 repetitions (in the last moves only) + // Check for 3 repetitions (position + flags + turn) checkRepetition() { - if (this.moves.length >= 8) + if (!this.hashStates) + this.hashStates = {}; + const startIndex = + Object.values(this.hashStates).reduce((a,b) => { return a+b; }, 0) + // Update this.hashStates with last move (or all moves if continuation) + // NOTE: redundant storage, but faster and moderate size + for (let i=startIndex; i { return (elt >= 3); }); } // Is game over ? And if yes, what is the score ? @@ -988,9 +1009,9 @@ class ChessRules // Setup the initial random (assymetric) position static GenRandInitFen() { - let pieces = [new Array(8), new Array(8)]; + let pieces = { "w": new Array(8), "b": new Array(8) }; // Shuffle pieces on first and last rank - for (let c = 0; c <= 1; c++) + for (let c of ["w","b"]) { let positions = _.range(8); @@ -1032,11 +1053,10 @@ class ChessRules pieces[c][knight2Pos] = 'n'; pieces[c][rook2Pos] = 'r'; } - let fen = pieces[0].join("") + + return pieces["b"].join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" + - pieces[1].join("").toUpperCase() + + pieces["w"].join("").toUpperCase() + " 1111"; //add flags - return fen; } // Return current fen according to pieces+colors state