UNPKG

xchess

Version:

Chess Engine

116 lines (93 loc) 1.78 kB
export {stateToHash, boardToHash} import {squares} from './square.js' function stateToHash(state){ return hash.stateToHash(state); } function boardToHash(board){ return hash.boardToHash(board); } function BitLength(n) { let length = 0; while (n > 0) { n >>= 1; length ++; } return length; } class HashWriter { value; gapLength = 0; stateToHash(state){ this.value = 1n; this.state(state); return this.value; } boardToHash(board){ this.value = 1n; this.board(board); return this.value; } push(value, size){ this.value <<= BigInt(size); this.value |= BigInt(value); } gamma(value){ this.push(value, 2 * BitLength(value) - 1); } board(board){ for(const square of squares) this.square(board.get(square)); this.releaseGap(); } square(piece){ piece ? this.piece(piece) : this.sep(); } piece(piece){ this.releaseGap(); if(piece.code > 11) this.extendedPiece(piece); else this.regularPiece(piece); } regularPiece(piece){ this.gamma(piece.code + 2); } extendedPiece(piece){ this.gamma(piece.code + 27); } sep(){ this.gapLength ++; if(this.gapLength >= 32) this.gap(); } releaseGap(){ if(this.gapLength > 0) this.gap(); } gap(){ if(this.gapLength > 7) this.longGap(this.gapLength); else this.shortGap(this.gapLength); this.gapLength = 0; } shortGap(value){ while(value -- > 0) this.gamma(1); } longGap(value){ this.gamma(value + 6); } state({color, enPassantTarget, wk, wq, bk, bq, board}){ this.push(color, 1); this.push(wk, 1); this.push(wq, 1); this.push(bk, 1); this.push(bq, 1); if(enPassantTarget){ this.push(1, 1); this.push(enPassantTarget, 6); } else this.push(0, 1); this.board(board); } } const hash = new HashWriter()