UNPKG

xchess

Version:

Chess Engine

76 lines (66 loc) 2.12 kB
export {ParseMove, ParseCastling, ParseICCF, ParseAlgebraic} import {Square} from './square.js' import {File} from './file.js' import {Rank} from './rank.js' import {INVALID_MOVE_STRING} from './errors.js' const IccfPromotion = [, 'queen', 'rook', 'bishop', 'knight']; const AlgebraicPromotion = new Map(); AlgebraicPromotion.set('Q', 'queen'); AlgebraicPromotion.set('R', 'rook'); AlgebraicPromotion.set('B', 'bishop'); AlgebraicPromotion.set('N', 'knight'); const KC = /^[0O]-[0O]$/i; const QC = /^[0O]-[0O]-[0O]$/i; const ICCF = /^([1-8][1-8])([1-8][1-8])([1-4])?$/; const ALGEBRAIC = /^((?<Sign>[♔-♟])|(?<Char>[QKRBNP]))?(?<FromFile>[a-h])?(?<FromRank>[1-8])?(-|\s+|(?<Capture>x))?(?<To>[a-h][1-8])([/=]?(?<Promotion>[QRBNqrbn]))?/; function AlgebraicToPromotion(value){ return AlgebraicPromotion.get(value.toUpperCase()); } function ParseMove(value){ const MoveCond = ParseCastling(value) ?? ParseICCF(value) ?? ParseAlgebraic(value); if(MoveCond) return MoveCond; throw INVALID_MOVE_STRING(value); } function ParseCastling(value){ if(KC.test(value)) return {kc: true}; if(QC.test(value)) return {qc: true}; return null; } function ParseICCF(value){ const iccf = ICCF.exec(value); if(iccf){ const [, From, To, Promotion] = iccf; const from = Square.from(From); const to = Square.from(To); const result = {from, to}; if(Promotion) result.promotion = IccfPromotion[+ Promotion]; return result; } return null; } function ParseAlgebraic(value){ const config = ALGEBRAIC.exec(value); if(config){ const {Sign, Char, FromFile, FromRank, Capture, To, Promotion} = config.groups; const result = {to: Square.from(To)}; if(FromFile && FromRank) result.from = Square.from(FromFile + FromRank); else if(FromFile) result.file = File.from(FromFile); else if(FromRank) result.rank = Rank.from(FromRank); if(Sign) result.sign = Sign; else if(Char) result.char = Char; else if(!result.from) result.char = 'P'; if(Capture) result.capture = true; if(Promotion) result.promotion = AlgebraicToPromotion(Promotion); return result; } return null; }