X-Git-Url: https://git.auder.net/?a=blobdiff_plain;f=public%2Fjavascripts%2Fbase_rules.js;h=a10a43ca270f405ff5dde22e0c7ba04170f577c6;hb=331fc58c932d6d7055b202d0c6dc0d77212a89f8;hp=750cd2d4ab72313fc4e1149dd76103ff4926147a;hpb=32cfcea44bf00b0c6c4d172cca715823076ff490;p=vchess.git diff --git a/public/javascripts/base_rules.js b/public/javascripts/base_rules.js index 750cd2d4..a10a43ca 100644 --- a/public/javascripts/base_rules.js +++ b/public/javascripts/base_rules.js @@ -54,6 +54,7 @@ class ChessRules constructor(fen, moves) { this.moves = moves; + this.hashStates = {}; //for repetitions detection // Use fen string to initialize variables, flags and board this.board = VariantRules.GetBoard(fen); this.setFlags(fen); @@ -727,8 +728,24 @@ class ChessRules this.kingPos[c] = [move.start.x, move.start.y]; } + // Store a hash of the position + flags + turn after a move is played + // (for repetitions detection) + addHashState() + { + const strToHash = this.getFen() + " " + this.turn; + const hash = hex_md5(strToHash); + if (!this.hashStates[hash]) + this.hashStates[hash] = 1; + else + this.hashStates[hash]++; + } + 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 +754,9 @@ class ChessRules this.moves.push(move); this.epSquares.push( this.getEpSquare(move) ); VariantRules.PlayOnBoard(this.board, move); + + if (!!ingame) + this.addHashState(); } undo(move) @@ -746,27 +766,20 @@ 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) - // TODO: extend to usual 3-repetition recognition (storing FEN with move?) + // Check for 3 repetitions (position + flags + turn) checkRepetition() { - if (this.moves.length >= 8) - { - const L = this.moves.length; - if (_.isEqual(this.moves[L-1], this.moves[L-5]) && - _.isEqual(this.moves[L-2], this.moves[L-6]) && - _.isEqual(this.moves[L-3], this.moves[L-7]) && - _.isEqual(this.moves[L-4], this.moves[L-8])) - { - return true; - } - } - return false; + return Object.values(this.hashStates).some(elt => { return (elt >= 3); }); } // Is game over ? And if yes, what is the score ? @@ -1033,11 +1046,10 @@ class ChessRules pieces[c][knight2Pos] = 'n'; pieces[c][rook2Pos] = 'r'; } - let fen = pieces["b"].join("") + + return pieces["b"].join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" + pieces["w"].join("").toUpperCase() + " 1111"; //add flags - return fen; } // Return current fen according to pieces+colors state