UNPKG

xchess

Version:

Chess Engine

79 lines (68 loc) 1.97 kB
export {test, allMoves} import {white, black} from './color.js' import { Move, Capture, PawnDoubleMove, EnPassant, PromotionRequest, CaptureAndPromotionRequest, } from './move.js' const INIT_INDEX = 2; const EN_PASSANT_INDEX = 5; const PROMOTION_INDEX = 7; const leftDX = -1; const rightDX = 1; function test(pawn, target, board){ const source = board.find(pawn); if(source){ if(pawn.color == white) return source.isTopD(target); if(pawn.color == black) return source.isBottomD(target); } return false; } function * allMoves(pawn, context){ const {board} = context; // Position const from = board.find(pawn); if(!from) return; const ownY = pawn.color.ownIndex(from.y); if(ownY > PROMOTION_INDEX) return; // Forward const forwardDY = pawn.color.ownDir(1); const doubleForwardDY = pawn.color.ownDir(2); const F = from.to(0, forwardDY); if(board.isPassable(F, pawn.color)){ if(ownY == PROMOTION_INDEX) yield new PromotionRequest(pawn, from, F); else yield new Move(pawn, from, F); const D = from.to(0, doubleForwardDY); if(ownY == INIT_INDEX && board.isPassable(D, pawn.color)) yield new PawnDoubleMove(pawn, from, D); } // Captures right / left yield * CaptureMoves(pawn, from, rightDX, forwardDY, ownY, context); yield * CaptureMoves(pawn, from, leftDX, forwardDY, ownY, context); } function * CaptureMoves(pawn, from, dx, dy, ownY, context){ const {board} = context; const to = from.to(dx, dy); if(to){ const capture = board.get(to); if(capture){ if(capture.isCapturable(pawn.color, board)){ if(ownY == PROMOTION_INDEX) yield new CaptureAndPromotionRequest(pawn, from, to, capture); else yield new Capture(pawn, from, to, capture); } } else if(ownY == EN_PASSANT_INDEX){ const captureAt = from.to(dx, 0); const capture = board.get(captureAt); if(capture && context.doubleMovePawn === capture) yield new EnPassant(pawn, from, to, capture, captureAt); } } }