xchess
Version:
Chess Engine
95 lines (75 loc) • 1.52 kB
JavaScript
export {stateToHash, boardToHash}
function stateToHash(state){
return hash.stateToHash(state);
}
function boardToHash(board){
return hash.boardToHash(board);
}
import {squares} from './square.js'
const MaxGapLength = 19n;
const MaxShortGapLength = 3n;
class HashWriter {
value;
gapLength = 0n;
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 <<= size;
this.value |= BigInt(value);
}
board(board){
for(const square of squares)
this.square(board.get(square));
this.releaseGap();
}
square(piece){
piece ? this.piece(piece) : this.skip();
}
piece(piece){
this.releaseGap();
this.push(piece.code, 4n);
}
skip(){
this.gapLength ++;
if(this.gapLength >= MaxGapLength)
this.gap();
}
releaseGap(){
if(this.gapLength > 0n)
this.gap();
}
gap(){
if(this.gapLength > MaxShortGapLength)
this.longGap(this.gapLength);
else
this.shortGap(this.gapLength);
this.gapLength = 0n;
}
shortGap(value){
this.push(value + 11n, 4n);
}
longGap(value){
this.push(value + 236n, 8n);
}
state({color, enPassantTarget, wk, wq, bk, bq, board}){
this.push(color, 1n);
this.push(wk, 1n);
this.push(wq, 1n);
this.push(bk, 1n);
this.push(bq, 1n);
if(enPassantTarget){
this.push(1n, 1n);
this.push(enPassantTarget, 6n);
} else this.push(0n, 1n);
this.board(board);
}
}
const hash = new HashWriter();