// ========================================== // HAND LIBRARY v1.0 // Pre-loaded bridge hands from international tournaments // Pure data — no dependencies // // FORMAT: Each string is ~ delimited: // N_hand~E_hand~S_hand~W_hand~dealer~vul~board~auction~event // // CHANGELOG: // v1.0 — 40 hands: Lederer 26 (29), Dutch Premier League 2025-26 (11) // ========================================== var VUGRAPH_LIBRARY = [ "sj98732hk2dt52ckj~sk6h9765dq9c97543~saq54haq3dakj8ca8~sthjt84d7643cqt62~s~n~11~2C,P,2D,P,2H,P,2S,P,2N,P,4D,P,4H,P,4S,P,4N,P,5D,P,6S,P,P,P~Lederer 26", "sakj6hq8632dqcaq8~s52hat54d854cj754~st743hk9dt32ck632~sq98hj7dakj976ct9~w~e~12~1D,X,P,1S,2D,3S,4D,4S,P,P,P~Lederer 26", "sq97543hkj942dc52~saj8hqt653d52ckj8~st6h7dakqj974c743~sk2ha8dt863caqt96~n~b~13~P,1H,2D,3C,P,3D,P,3H,P,3S,P,4C,P,5C,P,P,P~Lederer 26", "sakj84h4daj92cq63~sq732haj87dk8ckj9~s9hkq2dqt543ca742~st65ht9653d76ct85~e~n~14~1N,P,2D,2S,3H,P,P,X,P,P,P~Lederer 26", "s6hq9dk98643caqj7~skq8543hdat7ck532~sajt7hkt543dj2ct6~s92haj8762dq5c984~s~e~15~P,2D,P,2H,P,P,P~Lederer 26", "skq65hat9dkq9caqj~sajt932hq864d74c9~s84hk52dj52c85432~s7hj73dat863ckt76~n~n~33~2N,P,3C,P,3D,P,3N,P,P,P~Dutch Premier League final 2025-2026", "sqt9hjt6432dqct43~saj643hqdat54caq9~s875hadk93cj87652~sk2hk9875dj8762ck~e~e~34~1S,P,1N,P,2C,P,2D,P,2N,P,3H,P,3N,P,P,P~Dutch Premier League final 2025-2026", "sk5hq93dakj3cjt52~sq983ht642dqt9c43~sat7ha75d52cakq98~sj642hkj8d8764c76~s~o~35~1C,P,1D,P,1N,P,2C,P,2D,P,3D,P,3H,P,3S,P,4C,P,4D,P,4H,P,4S,P,4N,P,5C,P,6C,P,P,P~Dutch Premier League final 2025-2026", "s932hq976dqjtckt2~saj86hkjd74caj983~sk74hat85dk952cq7~sqt5h432da863c654~w~b~36~P,P,1N,P,P,P~Dutch Premier League final 2025-2026", "st863h76dt7ckj972~s97hqjda9832ca853~sq54hk9854dkj654c~sakj2hat32dqcqt64~n~e~37~P,1N,P,2C,X,P,P,XX,P,2S,P,3N,P,P,P~Dutch Premier League final 2025-2026", "s8haqt862daq3c873~sk7h74d9642cqt965~sat63hkj9dkt85c42~sqj9542h53dj7cakj~e~o~38~P,1N,2D,4C,P,4H,P,P,P~Dutch Premier League final 2025-2026", "sakj93h4d854caj65~s2hqt5da92ckt9432~sq84haj9dkqt76cq7~st765hk87632dj3c8~s~b~39~1N,P,2H,P,2S,P,2N,P,4S,P,P,P~Dutch Premier League final 2025-2026", "s86hkt86dat9cj963~sj54hqj7dk852cakq~saqt9732hadq74c42~skh95432dj63ct875~w~n~40~P,P,1N,2D,P,2S,P,3S,P,4S,P,P,P~Dutch Premier League final 2025-2026", "sak8h83daqt4cq853~s763hj94d97632ck7~sq9hat652dk85cj92~sjt542hkq7djcat64~n~o~41~1C,P,1H,1S,P,P,1N,P,P,P~Dutch Premier League final 2025-2026", "skqj74hj973d972c7~s5hak8djt84ckt932~sa9862h6dk653cqj8~st3hqt542daqca654~e~b~42~1C,1S,2D,4S,P,P,X,P,5H,P,P,P~Dutch Premier League final 2025-2026", "sq865hj53dt95ck94~s3hk862dj83cjt872~skj942ha74d742cq5~sat7hqt9dakq6ca63~s~n~43~P,1C,P,1D,1S,1N,2S,X,P,2N,P,3C,P,3D,P,3H,P,P,P~Dutch Premier League final 2025-2026", "skqj6h2dj73caqt53~s9hak8da862c98742~sa8543hj954dt54ck~st72hqt763dkq9cj6~w~e~44~P,1C,P,1N,P,2D,P,2S,P,3S,P,4S,P,P,P~Dutch Premier League final 2025-2026", "s85h984daqtcaq954~sq7hakqdj65cjt872~s94hj6532dk982ck3~sakjt632ht7d743c6~n~b~45~1C,P,1H,3S,P,4S,P,P,P~Dutch Premier League final 2025-2026", "sakqjhk95d4ckt854~s732h43da82caj762~s986h8762dqj63c93~st54haqjtdkt975cq~e~n~46~1N,P,2D,X,P,P,P~Dutch Premier League final 2025-2026", "sa4hkt43daqj5c954~sj85hqj95dt3cat87~skt732ha862d984cq~sq96h7dk762ckj632~s~e~47~P,P,1N,P,2C,P,2H,P,4H,P,P,P~Dutch Premier League final 2025-2026", "sk6hj986542dq642c~s953h3dakj98cajt8~saq872haq7d753cq2~sjt4hktdtck976543~w~o~48~2C,3H,5C,P,P,P~Dutch Premier League final 2025-2026", "sqhjt9865djt7ckt2~s4h3dkq942caj6543~sa96hakq74d863cq8~skjt87532h2da5c97~n~e~21~2D,3S,P,4S,P,P,P~Lederer 26", "s2hqj75daqt93cq72~sjt93ht4dk762cakj~sakq7hk986d4c9865~s8654ha32dj85ct43~e~o~22~1D,X,P,P,1S,X,P,P,P~Lederer 26", "sqj62haq7dt42cqt7~sak83hk3dq9853ck3~st7hjt954daj6c982~s954h862dk7caj654~s~b~23~P,P,1C,1D,X,XX,1H,X,2H,P,P,2S,P,P,P~Lederer 26", "st8ha9764d86caq42~sa7hjtdaq975cjt65~sqj542hq85dt432c3~sk963hk32dkjck987~w~n~24~1C,1H,1S,2H,P,P,X,P,2N,P,3N,P,P,P~Lederer 26", "s76432hdk93caqj53~s9hakt7daj6542c94~sq5hqj853d8ckt876~sakjt8h9642dqt7c2~n~o~25~1S,2D,X,2S,3C,3H,5C,X,P,P,P~Lederer 26", "skjt8432hak83d4ct~sa965hj92dq3ck842~s7hqt54dj962caj75~sqh76dakt875cq963~e~b~26~P,P,1D,4S,P,P,P~Lederer 26", "sa6hk87dat832cj42~skj8h93dkj74cq953~st9753haqj52d9ck7~sq42ht64dq65cat86~s~n~27~1S,P,2D,P,2H,P,2N,P,3H,P,4H,P,P,P~Lederer 26", "sj97hkqdkqt832ckj~sak32h9853d65caq8~st54ha74d97ct9642~sq86hjt62daj4c753~w~e~28~P,1N,2C,P,2D,X,P,P,XX,P,2S,P,P,P~Lederer 26", "sak84hadj984ckj83~s75hkt876dk762ca2~sqt32hqj92da3cq65~sj96h543dqt5ct974~n~b~29~1D,1H,X,P,3S,P,4S,P,P,P~Lederer 26", "s987532h73daq72c2~sat4hkjtdj9ckj875~skqj6ha854dk6cq63~shq962dt8543cat94~e~n~30~1C,1N,P,4D,P,4S,P,P,P~Lederer 26", "sakq765hak73djct3~sjt8h62dk62caqj86~s94hqjtdqt95ck942~s32h9854da8743c75~w~o~32~1D,X,P,P,1S,X,P,P,P~Lederer 26", "sq985ht9743d75c73~sj6hajda82cakqt98~sak4hk86djt96cj54~st732hq52dkq43c62~n~n~33~P,P,1C,1D,X,XX,1H,X,2H,P,P,2S,P,P,P~Lederer 26", "s53hakj84d7ckjt82~sakq6h6d632cq9643~st92hqt2dakqt8ca7~sj874h9753dj954c5~e~e~34~1C,1H,1S,2H,P,P,X,P,2N,P,3N,P,P,P~Lederer 26", "s52hj4d9765cq8762~sk63ht7532dt432cj~sqj4hdaqj8ckt9543~sat987hakq986dkca~s~o~35~1S,2D,X,2S,3C,3H,5C,X,P,P,P~Lederer 26", "sk86hqt85dq64c753~sq5hk976dak75ckt2~sj73haj3djt83ca64~sat942h42d92cqj98~w~b~36~P,P,1D,4S,P,P,P~Lederer 26", "s7h853dj952ca9854~sk9hk62dkt874ck62~sj862haj74daqct73~saqt543hqt9d63cqj~n~e~37~1S,P,2D,P,2H,P,2N,P,3H,P,4H,P,P,P~Lederer 26", "sjhkt7dk43ckjt842~skqt86hj65daqt5c6~sa73ha83dj972ca53~s9542hq942d86cq97~e~o~38~P,1N,2C,P,2D,X,P,P,XX,P,2S,P,P,P~Lederer 26", "s652hkq65da74cj97~saqj94ht84d5c8542~st87hj32dkqcakqt6~sk3ha97djt98632c3~s~b~39~1D,1H,X,P,3S,P,4S,P,P,P~Lederer 26", "sa54hkqdaj8752cq4~sj72h98432dkcaj98~skq6haj76dq943c72~st983ht5dt6ckt653~w~n~40~1C,1N,P,4D,P,4S,P,P,P~Lederer 26" ]; // ========================================== // BRIDGE ENGINE v1.0 // Core engine, bidding, parsing, vugraph library // No React dependencies — pure JavaScript // // CHANGELOG: // v1.0 — Initial split from hand-viewer 2.04 // Play engine (heuristic + DD solver) // 2/1 Game Forcing bidding generator // 41-hand vugraph library // All parsers (LIN, PBN, BBS, URL) // Shared utilities (auction analysis, scoring) // ========================================== // Shared constants const BASE_URL = 'https://hand.learnbridgeonline.com'; const SUITS = { s: { symbol: '♠', name: 'Spades', color: '#000000' }, h: { symbol: '♥', name: 'Hearts', color: '#EE4B2B' }, d: { symbol: '♦', name: 'Diamonds', color: '#EE4B2B' }, c: { symbol: '♣', name: 'Clubs', color: '#000000' } }; const SUIT_ORDER = ['s', 'h', 'd', 'c']; const SUIT_DISPLAY_ORDER = ['s', 'h', 'c', 'd']; // Black-red alternating for display // Trump-aware display order: trump first, then alternating black/red const SUIT_DISPLAY_ORDER_TRUMP = { s: ['s', 'h', 'c', 'd'], // black, red, black, red h: ['h', 's', 'd', 'c'], // red, black, red, black c: ['c', 'h', 's', 'd'], // black, red, black, red d: ['d', 's', 'h', 'c'], // red, black, red, black }; function getSuitDisplayOrder(trumpSuit) { if (trumpSuit && SUIT_DISPLAY_ORDER_TRUMP[trumpSuit]) return SUIT_DISPLAY_ORDER_TRUMP[trumpSuit]; return SUIT_DISPLAY_ORDER; } const SUIT_RANK = { c: 1, d: 2, h: 3, s: 4, n: 5 }; const CARD_VALUES = { a: 'A', k: 'K', q: 'Q', j: 'J', t: '10', '9': '9', '8': '8', '7': '7', '6': '6', '5': '5', '4': '4', '3': '3', '2': '2' }; const CARD_RANK = { a: 14, k: 13, q: 12, j: 11, t: 10, '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3, '2': 2 }; const RANKS_ORDERED = ['a','k','q','j','t','9','8','7','6','5','4','3','2']; const ALL_RANKS = ['a', 'k', 'q', 'j', 't', '9', '8', '7', '6', '5', '4', '3', '2']; const POSITIONS = ['S', 'W', 'N', 'E']; const AUCTION_ORDER = ['W', 'N', 'E', 'S']; const VULNERABILITY = { n: 'None', b: 'Both', e: 'N-S', o: 'E-W' }; const VUL_TO_BBO = { n: 'o', e: 'n', o: 'e', b: 'b' }; // Internal → BBO URL format const DEALER_MAP = { n: 'N', e: 'E', s: 'S', w: 'W' }; // ========================================== // BRIDGE PLAY ENGINE (Heuristic-First, Single-Dummy) // The robot play engine (called via findRobotCard). Conventions: Reverse HELD / UDCA. // ========================================== const BridgeEngine = (() => { const POS = ['S', 'W', 'N', 'E']; const nextPos = p => POS[(POS.indexOf(p) + 1) % 4]; const isNS = p => p === 'N' || p === 'S'; const partnerOf = p => ({ N:'S', S:'N', E:'W', W:'E' }[p]); const nextOf = p => ({ S:'W', W:'N', N:'E', E:'S' }[p]); // ---- Core Helpers (unchanged) ---- function getRemaining(hand, played) { const rem = {}; SUIT_ORDER.forEach(s => { rem[s] = (hand[s] || []).filter(r => !played.some(c => c.suit === s && c.rank === r)); }); return rem; } function getLegalCards(hand, leadSuit) { const cards = []; SUIT_ORDER.forEach(s => (hand[s] || []).forEach(r => cards.push({ suit: s, rank: r }))); if (!leadSuit || cards.length === 0) return cards; const follow = cards.filter(c => c.suit === leadSuit); return follow.length > 0 ? follow : cards; } function totalCards(hands) { let n = 0; for (const p of POS) for (const s of SUIT_ORDER) n += (hands[p][s]?.length || 0); return n; } // Numeric trick value for a card: trumps score 100+rank, led suit scores rank, others -1 function cardVal(card, leadSuit, trumpSuit) { if (trumpSuit && card.suit === trumpSuit) return 100 + CARD_RANK[card.rank]; if (card.suit === leadSuit) return CARD_RANK[card.rank]; return -1; } // Cards in a suit not visible in any provided hand or played pile const ALL_RANKS_LIST = ['a','k','q','j','t','9','8','7','6','5','4','3','2']; function outstandingInSuit(suit, visibleHands, playedCards) { const seen = new Set(); for (const h of Object.values(visibleHands || {})) (h[suit] || []).forEach(r => seen.add(r)); for (const arr of Object.values(playedCards || {})) (arr || []).forEach(c => { if (c.suit === suit) seen.add(c.rank); }); return ALL_RANKS_LIST.filter(r => !seen.has(r)); } // Cards that are guaranteed winners (no outstanding card is higher) function findCashableWinners(hand, visibleHands, playedCards) { const winners = []; for (const s of SUIT_ORDER) { const ranks = hand[s] || []; if (!ranks.length) continue; const outstanding = outstandingInSuit(s, visibleHands, playedCards); const sorted = [...ranks].sort((a, b) => CARD_RANK[b] - CARD_RANK[a]); for (const r of sorted) { if (outstanding.every(o => CARD_RANK[o] < CARD_RANK[r])) { winners.push({ suit: s, rank: r }); } else break; // once a card isn't a winner, lower ones aren't either } } return winners; } function trickWinner(trick, trumpSuit) { let best = trick[0]; for (let i = 1; i < trick.length; i++) { const c = trick[i]; if (c.suit === trumpSuit && best.suit !== trumpSuit) best = c; else if (c.suit === best.suit && CARD_RANK[c.rank] > CARD_RANK[best.rank]) best = c; else if (c.suit === trumpSuit && best.suit === trumpSuit && CARD_RANK[c.rank] > CARD_RANK[best.rank]) best = c; } return best.position; } function removeCard(hands, pos, card) { const h = {}; for (const p of POS) { h[p] = {}; for (const s of SUIT_ORDER) { h[p][s] = (p === pos && s === card.suit) ? hands[p][s].filter(r => r !== card.rank) : hands[p][s]; } } return h; } function reduceEquiv(cards, allHands) { if (cards.length <= 1) return cards; const bySuit = {}; cards.forEach(c => { (bySuit[c.suit] ||= []).push(c); }); const result = []; for (const [suit, sc] of Object.entries(bySuit)) { const sorted = sc.sort((a, b) => CARD_RANK[b.rank] - CARD_RANK[a.rank]); result.push(sorted[0]); for (let i = 1; i < sorted.length; i++) { const hi = CARD_RANK[sorted[i - 1].rank], lo = CARD_RANK[sorted[i].rank]; if (hi - lo === 1) continue; let allGone = true; for (let r = lo + 1; r < hi && allGone; r++) { const rk = ALL_RANKS.find(x => CARD_RANK[x] === r); if (rk && POS.some(p => (allHands[p][suit] || []).includes(rk))) allGone = false; } if (!allGone) result.push(sorted[i]); } } return result; } // ---- Small Helpers ---- const isHonor = rank => CARD_RANK[rank] >= 10; const suitLen = (hands, pos, suit) => (hands[pos]?.[suit] || []).length; function findSequence(ranks) { const sorted = [...ranks].sort((a, b) => CARD_RANK[b] - CARD_RANK[a]); const seq = [sorted[0]]; for (let i = 1; i < sorted.length; i++) { if (CARD_RANK[seq[seq.length - 1]] - CARD_RANK[sorted[i]] === 1) { seq.push(sorted[i]); } else break; } return seq; } // Find internal sequence: cards like KJT → J is top of internal sequence function findInternalSequence(sortedRanks) { // sortedRanks sorted high to low if (sortedRanks.length < 3) return null; for (let i = 1; i < sortedRanks.length - 1; i++) { const seq = [sortedRanks[i]]; for (let j = i + 1; j < sortedRanks.length; j++) { if (CARD_RANK[seq[seq.length - 1]] - CARD_RANK[sortedRanks[j]] === 1) { seq.push(sortedRanks[j]); } else break; } if (seq.length >= 2 && isHonor(seq[0])) return seq; } return null; } function findCandIdx(candidates, suit, targetRank, mode) { let bestIdx = -1, bestDist = 999; for (let i = 0; i < candidates.length; i++) { if (candidates[i].suit !== suit) continue; const r = CARD_RANK[candidates[i].rank]; if (mode === 'exact' && r === targetRank) return i; if (mode === 'lowest' && (bestIdx < 0 || r < CARD_RANK[candidates[bestIdx].rank])) bestIdx = i; if (mode === 'highest' && (bestIdx < 0 || r > CARD_RANK[candidates[bestIdx].rank])) bestIdx = i; const d = Math.abs(r - targetRank); if (mode === 'near' && d < bestDist) { bestDist = d; bestIdx = i; } } return bestIdx; } // Alert flags for the CURRENT findBestCard call (index-keyed; truthy = the // call was artificial, so the suit it names was not actually shown — a 2D // transfer is hearts, Stayman is nothing). Set at findBestCard entry; // single-threaded so no reentrancy concern. let _auctionAlerts = null; function getSuitsBidBy(pos, auction, dealer) { const suits = []; if (!auction) return suits; const positions = ['N', 'E', 'S', 'W']; const dealerIdx = positions.indexOf(dealer); if (dealerIdx < 0) return suits; auction.forEach((bid, i) => { if (_auctionAlerts && _auctionAlerts[i]) return; // artificial call: skip const bidder = positions[(dealerIdx + i) % 4]; if (bid.type === 'bid' && bidder === pos && bid.suit !== 'n') { if (!suits.includes(bid.suit)) suits.push(bid.suit); } }); return suits; } // ---- Bidding Inference ---- function inferFromBidding(auction, dealer) { const info = {}; POS.forEach(p => { info[p] = { hcpMin: 0, hcpMax: 37, suitsBid: [], passed: false, opened: false, preempted: false }; }); if (!auction || !dealer) return info; const positions = ['N', 'E', 'S', 'W']; const dealerIdx = positions.indexOf(dealer); if (dealerIdx < 0) return info; let opened = false; auction.forEach((bid, i) => { const bidder = positions[(dealerIdx + i) % 4]; const inf = info[bidder]; if (bid.type === 'pass' && !opened) { inf.passed = true; inf.hcpMax = Math.min(inf.hcpMax, 12); } if (bid.type === 'bid') { if (!opened) { opened = true; inf.opened = true; if (bid.level === 1 && bid.suit === 'n') { inf.hcpMin = Math.max(inf.hcpMin, 15); inf.hcpMax = Math.min(inf.hcpMax, 17); } else if (bid.level === 2 && bid.suit === 'n') { inf.hcpMin = Math.max(inf.hcpMin, 20); inf.hcpMax = Math.min(inf.hcpMax, 21); } else if (bid.level >= 2 && bid.level <= 4 && bid.suit !== 'n' && bid.suit !== 'c') { // Preempt inf.preempted = true; inf.hcpMin = Math.max(inf.hcpMin, 5); inf.hcpMax = Math.min(inf.hcpMax, 11); } else if (bid.level === 1) { inf.hcpMin = Math.max(inf.hcpMin, 12); inf.hcpMax = Math.min(inf.hcpMax, 21); } } if (bid.suit !== 'n' && !inf.suitsBid.includes(bid.suit)) { inf.suitsBid.push(bid.suit); } } }); return info; } // ---- Card Tracking & Player Knowledge ---- // Builds a comprehensive knowledge state from observable information: // - Everything from old buildTracking (voids, signals, suits led) // - HCP played by each player, HCP remaining range // - Suit length bounds per player (from show-outs, bidding, 4th-suit rule) // - Honor locations (which honors played by whom, which still missing) const HCP_VALUES = { a: 4, k: 3, q: 2, j: 1 }; function cardHcp(rank) { return HCP_VALUES[rank] || 0; } function buildPlayerKnowledge(allHands, playedCards, hands, trickHistory, currentTrick, trumpSuit, auction, dealer, contractInfo) { // === 1. EXISTING SIGNAL TRACKING === const voids = {}; POS.forEach(p => voids[p] = new Set()); const suitsLedBy = {}; POS.forEach(p => suitsLedBy[p] = []); const discardSignals = {}; POS.forEach(p => discardSignals[p] = {}); const partnerSignals = {}; POS.forEach(p => partnerSignals[p] = {}); // === 2. CARDS PLAYED TRACKING === // Count cards played per player per suit, and track HCP played const suitPlayed = {}; // suitPlayed[p][s] = count of cards played in suit s const hcpPlayed = {}; // hcpPlayed[p] = total HCP from cards played so far const honorsPlayed = {}; // honorsPlayed[p] = [{suit, rank}, ...] honors played by p POS.forEach(p => { suitPlayed[p] = {}; SUIT_ORDER.forEach(s => suitPlayed[p][s] = 0); hcpPlayed[p] = 0; honorsPlayed[p] = []; }); // Process all played cards POS.forEach(p => { for (const c of (playedCards[p] || [])) { suitPlayed[p][c.suit]++; const hv = cardHcp(c.rank); if (hv > 0) { hcpPlayed[p] += hv; honorsPlayed[p].push({ suit: c.suit, rank: c.rank }); } } }); // === 3. TRICK-BY-TRICK SCANNING (signals + voids) === const allTricks = [...(trickHistory || []).map(t => t.trick), currentTrick].filter(Boolean); for (const trick of allTricks) { if (!trick || trick.length === 0) continue; const leadSuit = trick[0].suit; const leaderPos = trick[0].position; if (!suitsLedBy[leaderPos].includes(leadSuit)) { suitsLedBy[leaderPos].push(leadSuit); } for (let i = 1; i < trick.length; i++) { const play = trick[i]; if (play.suit !== leadSuit) { voids[play.position].add(leadSuit); if (play.suit !== trumpSuit) { if (!discardSignals[play.position][play.suit]) { const rank = CARD_RANK[play.rank]; if (rank <= 5) { discardSignals[play.position][play.suit] = 'encouraging'; } else if (rank >= 8) { discardSignals[play.position][play.suit] = 'discouraging'; } } } } } } // Attitude signals from following suit for (const th of (trickHistory || [])) { const trick = th.trick; if (!trick || trick.length < 2) continue; const leaderPos = trick[0].position; const leadSuit = trick[0].suit; if (trick.length >= 3) { const thirdHandPos = trick[2].position; if (partnerOf(thirdHandPos) === leaderPos && trick[2].suit === leadSuit) { const rank = CARD_RANK[trick[2].rank]; if (rank <= 5) partnerSignals[thirdHandPos][leadSuit] = 'encouraging'; else if (rank >= 8 && rank <= 10) partnerSignals[thirdHandPos][leadSuit] = 'discouraging'; } } if (trick.length >= 4) { const fourthHandPos = trick[3].position; if (partnerOf(fourthHandPos) === leaderPos && trick[3].suit === leadSuit) { const rank = CARD_RANK[trick[3].rank]; if (!partnerSignals[fourthHandPos][leadSuit]) { if (rank <= 5) partnerSignals[fourthHandPos][leadSuit] = 'encouraging'; else if (rank >= 8 && rank <= 10) partnerSignals[fourthHandPos][leadSuit] = 'discouraging'; } } } } // === 4. SUIT LENGTH BOUNDS === // For each player-suit: what original length can we deduce? // Known facts: played count + remaining count = original length // Show-out: void now, so original = played count (exact) // Bidding: bid suit = 4+ (or 5+ for major openings) // 4th suit rule: if 3 suits known exactly, 4th = 13 - sum const suitLength = {}; const biddingInfo = inferFromBidding(auction, dealer); POS.forEach(p => { suitLength[p] = {}; const remaining = {}; SUIT_ORDER.forEach(s => { remaining[s] = (hands[p][s] || []).length; }); SUIT_ORDER.forEach(s => { const played = suitPlayed[p][s]; const rem = remaining[s]; const original = played + rem; if (voids[p].has(s)) { // Show-out: currently void, original length = cards already played suitLength[p][s] = { min: original, max: original, exact: true }; } else { // Not void yet: original >= played + remaining (which we know) // but also influenced by bidding let min = original; let max = original; // if we can see this hand, exact // For hidden hands we'd need inference, but since we have allHands // in robot mode, all hands are visible. However, we still compute // inference-quality bounds for the knowledge system. suitLength[p][s] = { min, max, exact: true }; } }); // Apply bidding constraints (useful for Monte Carlo even if we see hands) const pBid = biddingInfo[p]; if (pBid) { for (const s of (pBid.suitsBid || [])) { if (suitLength[p][s]) { suitLength[p][s].bidMin = 4; // bid suit implies 4+ } } if (pBid.preempted && pBid.suitsBid.length > 0) { const s = pBid.suitsBid[0]; if (suitLength[p][s]) { suitLength[p][s].bidMin = 6; // preempt implies 6+ } } } }); // 4th-suit inference: when 3 suits have exact counts, 4th is determined POS.forEach(p => { const exactSuits = SUIT_ORDER.filter(s => suitLength[p][s]?.exact); if (exactSuits.length === 3) { const unknownSuit = SUIT_ORDER.find(s => !suitLength[p][s]?.exact); if (unknownSuit) { const knownTotal = exactSuits.reduce((sum, s) => sum + suitLength[p][s].min, 0); const fourthLen = 13 - knownTotal; suitLength[p][unknownSuit] = { min: fourthLen, max: fourthLen, exact: true, inferred: true }; } } }); // === 5. HCP RANGES === // From bidding: initial range. Narrow by subtracting HCP already played. const hcpRange = {}; POS.forEach(p => { const bid = biddingInfo[p] || {}; const bidMin = bid.hcpMin || 0; const bidMax = bid.hcpMax || 37; // HCP remaining in hand = original HCP - HCP played // Original HCP is in [bidMin, bidMax] // So remaining HCP is in [bidMin - hcpPlayed, bidMax - hcpPlayed] // But remaining HCP can't be negative or more than what's still in hand const remCards = SUIT_ORDER.reduce((n, s) => n + (hands[p][s] || []).length, 0); const maxPossibleHcp = Math.min(remCards * 4, 37); // theoretical max hcpRange[p] = { min: Math.max(0, bidMin - hcpPlayed[p]), max: Math.min(maxPossibleHcp, bidMax - hcpPlayed[p]), played: hcpPlayed[p], bidRange: [bidMin, bidMax], }; }); // === 6. HONOR LOCATION SUMMARY === // For each suit, which honors (AKQJ) are accounted for and where? const honorLocations = {}; SUIT_ORDER.forEach(s => { honorLocations[s] = { a: null, k: null, q: null, j: null }; // Check played honors POS.forEach(p => { for (const h of honorsPlayed[p]) { if (h.suit === s && honorLocations[s][h.rank] === null) { honorLocations[s][h.rank] = { player: p, status: 'played' }; } } }); // Check remaining hands for visible honors POS.forEach(p => { for (const rank of ['a', 'k', 'q', 'j']) { if (honorLocations[s][rank] === null && (hands[p][s] || []).includes(rank)) { honorLocations[s][rank] = { player: p, status: 'held' }; } } }); // Any still null are unlocated (in hidden hands, not yet played) }); // === 7. POSITIONAL STRENGTH SUMMARY === // Quick assessment: for each suit, who controls it? const suitControl = {}; SUIT_ORDER.forEach(s => { const nsRanks = [], ewRanks = []; POS.forEach(p => { for (const r of (hands[p][s] || [])) { if (isNS(p)) nsRanks.push(CARD_RANK[r]); else ewRanks.push(CARD_RANK[r]); } }); nsRanks.sort((a, b) => b - a); ewRanks.sort((a, b) => b - a); const nsTop = nsRanks[0] || 0; const ewTop = ewRanks[0] || 0; suitControl[s] = { nsTop, ewTop, nsLen: nsRanks.length, ewLen: ewRanks.length, controller: nsTop > ewTop ? 'NS' : ewTop > nsTop ? 'EW' : 'tied', }; }); return { // Original tracking (backward compatible) voids, partnerSignals, suitsLedBy, discardSignals, // New: counting suitPlayed, suitLength, hcpPlayed, hcpRange, // New: honor tracking honorsPlayed, honorLocations, // New: suit control suitControl, // Bidding info (passed through for convenience) biddingInfo, }; } // Backward-compat wrapper — old code that calls buildTracking still works function buildTracking(hands, trickHistory, currentTrick, trumpSuit) { // Lightweight version for opening lead (no allHands/playedCards available) const voids = {}; POS.forEach(p => voids[p] = new Set()); const suitsLedBy = {}; POS.forEach(p => suitsLedBy[p] = []); const discardSignals = {}; POS.forEach(p => discardSignals[p] = {}); const partnerSignals = {}; POS.forEach(p => partnerSignals[p] = {}); const allTricks = [...(trickHistory || []).map(t => t.trick), currentTrick].filter(Boolean); for (const trick of allTricks) { if (!trick || trick.length === 0) continue; const leadSuit = trick[0].suit; const leaderPos = trick[0].position; if (!suitsLedBy[leaderPos].includes(leadSuit)) suitsLedBy[leaderPos].push(leadSuit); for (let i = 1; i < trick.length; i++) { const play = trick[i]; if (play.suit !== leadSuit) { voids[play.position].add(leadSuit); if (play.suit !== trumpSuit && !discardSignals[play.position][play.suit]) { const rank = CARD_RANK[play.rank]; if (rank <= 5) discardSignals[play.position][play.suit] = 'encouraging'; else if (rank >= 8) discardSignals[play.position][play.suit] = 'discouraging'; } } } } for (const th of (trickHistory || [])) { const trick = th.trick; if (!trick || trick.length < 2) continue; const leaderPos = trick[0].position; const leadSuit = trick[0].suit; if (trick.length >= 3) { const thirdHandPos = trick[2].position; if (partnerOf(thirdHandPos) === leaderPos && trick[2].suit === leadSuit) { const rank = CARD_RANK[trick[2].rank]; if (rank <= 5) partnerSignals[thirdHandPos][leadSuit] = 'encouraging'; else if (rank >= 8 && rank <= 10) partnerSignals[thirdHandPos][leadSuit] = 'discouraging'; } } if (trick.length >= 4) { const fourthHandPos = trick[3].position; if (partnerOf(fourthHandPos) === leaderPos && trick[3].suit === leadSuit) { const rank = CARD_RANK[trick[3].rank]; if (!partnerSignals[fourthHandPos][leadSuit]) { if (rank <= 5) partnerSignals[fourthHandPos][leadSuit] = 'encouraging'; else if (rank >= 8 && rank <= 10) partnerSignals[fourthHandPos][leadSuit] = 'discouraging'; } } } } return { voids, partnerSignals, suitsLedBy, discardSignals }; } // ---- Current Trick Analysis ---- function currentWinner(trick, trumpSuit) { if (trick.length === 0) return null; let best = trick[0]; for (let i = 1; i < trick.length; i++) { const c = trick[i]; if (c.suit === trumpSuit && best.suit !== trumpSuit) best = c; else if (c.suit === best.suit && CARD_RANK[c.rank] > CARD_RANK[best.rank]) best = c; else if (c.suit === trumpSuit && best.suit === trumpSuit && CARD_RANK[c.rank] > CARD_RANK[best.rank]) best = c; } return best; } function wouldWin(card, trick, trumpSuit) { if (trick.length === 0) return true; const best = currentWinner(trick, trumpSuit); if (card.suit === trumpSuit && best.suit !== trumpSuit) return true; if (card.suit === trumpSuit && best.suit === trumpSuit) return CARD_RANK[card.rank] > CARD_RANK[best.rank]; if (card.suit === trick[0].suit && best.suit !== trumpSuit) return CARD_RANK[card.rank] > CARD_RANK[best.rank]; return false; } // Is this card the master (highest remaining) in its suit? function isMaster(card, hands, playerPos) { const r = CARD_RANK[card.rank]; for (const p of POS) { if (p === playerPos) continue; for (const rank of (hands[p][card.suit] || [])) { if (CARD_RANK[rank] > r) return false; } } return true; } // ====================================== // OPENING LEAD SELECTION // Pure heuristic, never consults search. // ====================================== function selectOpeningLead(hand, playerPos, trumpSuit, context) { // Unified lead logic: when the PlaySelector textbook engine is loaded, // delegate to it (one source of truth for textbook leads). // The scoring below remains only as the no-PlaySelector last resort. try { const PS = (typeof PlaySelector !== 'undefined') ? PlaySelector : (typeof window !== 'undefined' && window.PlaySelector) ? window.PlaySelector : null; if (PS && PS.pickDetailed && context && context.contractInfo) { const cands = []; SUIT_ORDER.forEach(s => (hand[s] || []).forEach(r => cands.push({ suit: s, rank: r }))); const allHands = { N: {s:[],h:[],d:[],c:[]}, E: {s:[],h:[],d:[],c:[]}, S: {s:[],h:[],d:[],c:[]}, W: {s:[],h:[],d:[],c:[]} }; allHands[playerPos] = hand; const d = PS.pickDetailed(cands, { allHands, playedCards: { N: [], E: [], S: [], W: [] }, currentTrick: [], trickHistory: [], trumpSuit: trumpSuit || null, playerPos, contractInfo: context.contractInfo, auction: context.auction || [], dealer: context.dealer || 'N', bidIsAlert: context.bidIsAlert || null, vulnerability: context.vulnerability || 'n' }); if (d && d.suit && d.rank) { console.log('[Lead] JS engine delegated to PlaySelector: ' + d.suit + d.rank + ' — ' + (d.reason || d.rule || '')); return { suit: d.suit, rank: d.rank }; } } } catch (e) { /* fall through to built-in scoring */ } const { contractInfo, auction, dealer } = context || {}; const pPos = partnerOf(playerPos); const partnerBidSuits = getSuitsBidBy(pPos, auction, dealer); const biddingInfo = inferFromBidding(auction, dealer); const declarerPos = contractInfo?.declarer; const dummyPos = contractInfo?.dummy; const declarerBidSuits = declarerPos ? getSuitsBidBy(declarerPos, auction, dealer) : []; const dummyBidSuits = dummyPos ? getSuitsBidBy(dummyPos, auction, dealer) : []; const oppBidSuits = [...new Set([...declarerBidSuits, ...dummyBidSuits])]; // === CONTRACT CONTEXT === const isSuit = !!trumpSuit; const isNT = !trumpSuit; const contractLevel = contractInfo?.level || 1; const isPartscore = contractLevel <= 2; const isGame = contractLevel >= 3 && contractLevel <= 5; const isSlam = contractLevel >= 6; // Score each suit const suitScores = {}; for (const suit of SUIT_ORDER) { const cards = (hand[suit] || []); if (cards.length === 0) { suitScores[suit] = -999; continue; } const sorted = [...cards].sort((a, b) => CARD_RANK[b] - CARD_RANK[a]); const len = cards.length; let score = 0; // Partner's bid suit: big bonus — near-automatic if (partnerBidSuits.includes(suit)) { score += 50; if (isNT) score += 10; // Even more important in NT (establishes partner's suit) } // Opponent's bid suits: penalty if (declarerBidSuits.includes(suit)) { score -= isSuit ? 20 : 15; // Slightly less bad in NT (may still have length) } if (dummyBidSuits.includes(suit)) score -= 15; // Unbid suit bonus (safer lead) if (!partnerBidSuits.includes(suit) && !oppBidSuits.includes(suit) && suit !== trumpSuit) { score += 8; } // Sequence analysis const seq = findSequence(sorted); const hasGoodSeq = seq.length >= 2 && isHonor(seq[0]); const intSeq = findInternalSequence(sorted); const hasIntSeq = intSeq && intSeq.length >= 2; const hasAK = sorted.includes('a') && sorted.includes('k'); if (isSuit) { // === SUIT CONTRACT === if (suit === trumpSuit) { score -= 20; // Avoid trump leads generally // Exception: trump lead is OK from 3+ small when dummy showed balanced hand if (len >= 3 && CARD_RANK[sorted[0]] <= 10) score += 5; } // AK: standard lead in suit contracts — cash Ace then decide if (hasAK && suit !== trumpSuit) score += 45; // Singleton: strong ruffing potential — one of the best suit-contract leads if (len === 1 && suit !== trumpSuit) { score += 42; if (isSlam) score += 10; // Even more valuable against slams } // Doubleton: moderate ruffing potential if (len === 2 && suit !== trumpSuit && !isHonor(sorted[0])) score += 12; // HARD BLOCK: Never underlead an ace in suit contracts if (sorted[0] === 'a' && len >= 2 && !sorted.includes('k') && suit !== trumpSuit) { if (!partnerBidSuits.includes(suit)) { score -= 999; } } // Kx doubleton without ace: very risky if (sorted[0] === 'k' && !sorted.includes('a') && len === 2 && !hasGoodSeq) { score -= 40; } // Kx or Qx without sequence: risky if ((sorted[0] === 'k' || sorted[0] === 'q') && len <= 3 && !hasGoodSeq && !hasIntSeq) { score -= 15; } // Against SLAM: aggressive required if (isSlam) { if (hasAK) score += 15; // Cash AK even more urgently // Don't lead trumps against slam (they control trumps) if (suit === trumpSuit) score -= 15; } // Against PARTSCORE: passive is fine if (isPartscore) { // Safe passive leads get a bonus if (!isHonor(sorted[0]) && len >= 3) score += 5; } } else { // === NO-TRUMP === // Fourth-from-longest-and-strongest is the standard score += len * 8; // Honors in a long suit help establish it, but a BARE ace at the top of // a long suit is a poor lead in NT (leading low into it can cost a trick, // and cashing the ace helps declarer). Favour the king-headed suit. const topR = CARD_RANK[sorted[0]]; const hasAceTop = topR === 14, hasKingTop = topR === 13; if (hasKingTop) score += 6; // K-high long suit: good if (hasAceTop && !sorted.includes('k')) score -= 6; // A-high (no K): leading away from the ace if (sorted.some(r => CARD_RANK[r] >= 12) && len >= 4) score += 4; // Q+ gives a real trick source // Long suit with honors: ideal NT lead if (len >= 5 && sorted.some(r => CARD_RANK[r] >= 12)) score += 12; // Qxx, Jxx without sequence: terrible in NT — likely gives away a trick if (!hasGoodSeq && !hasIntSeq && len >= 3 && len <= 4) { if (sorted[0] === 'q' && !sorted.includes('j')) score -= 18; if (sorted[0] === 'j' && !sorted.includes('t')) score -= 15; } // Against NT SLAM: need an attacking lead if (isSlam) { if (hasGoodSeq) score += 15; // A running suit is ideal if (len >= 5 && hasGoodSeq) score += 20; } // Against 1NT: passive is OK, don't give away tricks if (isPartscore) { if (isHonor(sorted[0]) && !hasGoodSeq && !hasIntSeq) score -= 8; if (!isHonor(sorted[0]) && len >= 3) score += 5; // top of nothing } } // Sequence bonus (both suit and NT). Scaled DOWN for short suits: a QJ // doubleton is a fine card but must not outrank a good 5-card suit as the // OPENING salvo — length is king, especially in NT. A 3+ card sequence // keeps the full premium. if (hasGoodSeq) { const seqTopRank = CARD_RANK[seq[0]]; const lenFactor = len >= 4 ? 1 : (len === 3 ? 0.7 : 0.35); // doubleton seq heavily discounted if (seqTopRank >= 11) { score += (25 + len * 5) * lenFactor; if (seq.length >= 3) score += 15; } else { score += (15 + len * 3) * lenFactor; } } if (hasIntSeq && !hasGoodSeq) { score += 20 + len * 3; } // Broken honor penalty if (!hasGoodSeq && !hasIntSeq) { const hasA = sorted.includes('a'), hasK = sorted.includes('k'), hasQ = sorted.includes('q'), hasJ = sorted.includes('j'); if ((hasK && hasJ && !hasQ) || (hasA && hasQ && !hasK)) score -= 10; if (len <= 2 && (hasQ || hasJ) && !hasK && !hasA) score -= 10; const honorCount = sorted.filter(r => CARD_RANK[r] >= 11).length; if (honorCount === 1 && len >= 3) score -= 5; } suitScores[suit] = score; } // Pick best suit let bestSuit = null, bestScore = -9999; for (const suit of SUIT_ORDER) { if (suitScores[suit] > bestScore) { bestScore = suitScores[suit]; bestSuit = suit; } } if (!bestSuit) return null; // Pick the card from best suit const cards = [...(hand[bestSuit] || [])].sort((a, b) => CARD_RANK[b] - CARD_RANK[a]); if (cards.length === 0) return null; // AK: lead Ace (then partner signals, we decide whether to continue K) if (isSuit && cards.includes('a') && cards.includes('k')) { return { suit: bestSuit, rank: 'a' }; } // Top of sequence const seq = findSequence(cards); if (seq.length >= 2 && isHonor(seq[0])) { return { suit: bestSuit, rank: seq[0] }; } // Top of internal sequence const intSeq = findInternalSequence(cards); if (intSeq && intSeq.length >= 2) { return { suit: bestSuit, rank: intSeq[0] }; } // Singleton if (cards.length === 1) return { suit: bestSuit, rank: cards[0] }; // Doubleton: top if (cards.length === 2) return { suit: bestSuit, rank: cards[0] }; // 4+ cards: fourth highest if (cards.length >= 4) { return { suit: bestSuit, rank: cards[3] }; } // 3 cards: low from honor heading, MUD from small if (CARD_RANK[cards[0]] >= 10) { return { suit: bestSuit, rank: cards[2] }; // low from honor } return { suit: bestSuit, rank: cards[1] }; // MUD: middle card } // ====================================== // DUMMY CONTEXT HELPER // Analyzes dummy's position & cards relative to the current trick. // ====================================== function getDummyContext(trick, playerPos, hands, trumpSuit, state) { const dummyPos = state.contractInfo?.dummy; if (!dummyPos || !state.isDefender) return null; const leadSuit = trick[0]?.suit; if (!leadSuit) return null; // Has dummy already played in this trick? const dummyPlayed = trick.some(c => c.position === dummyPos); // Dummy's remaining cards in the led suit const dummyInSuit = (hands[dummyPos]?.[leadSuit] || []) .map(r => CARD_RANK[r]).sort((a, b) => b - a); // Who plays AFTER the current player in this trick? const afterMe = []; let pos = nextPos(playerPos); for (let i = trick.length + 1; i < 4; i++) { afterMe.push(pos); pos = nextPos(pos); } const dummyPlaysAfterMe = !dummyPlayed && afterMe.includes(dummyPos); const dummyBest = dummyInSuit.length > 0 ? dummyInSuit[0] : 0; const dummyWorst = dummyInSuit.length > 0 ? dummyInSuit[dummyInSuit.length - 1] : 0; // Declarer info const declarerPos = state.contractInfo?.declarer; const declarerPlaysAfterMe = !trick.some(c => c.position === declarerPos) && afterMe.includes(declarerPos); return { dummyPos, declarerPos, dummyPlayed, dummyPlaysAfterMe, declarerPlaysAfterMe, dummyInSuit, dummyBest, dummyWorst, dummyLen: dummyInSuit.length, dummyVoid: dummyInSuit.length === 0, dummyCanRuff: dummyInSuit.length === 0 && trumpSuit && (hands[dummyPos]?.[trumpSuit] || []).length > 0, }; } // ====================================== // SECOND HAND PLAY // Now dummy-aware: considers dummy's visible cards when deciding to play low or rise. // ====================================== function selectSecondHand(legal, hand, trick, trumpSuit, playerPos, hands, state) { const leadSuit = trick[0].suit; const leadRank = CARD_RANK[trick[0].rank]; const following = legal.filter(c => c.suit === leadSuit); const isDefender = state.isDefender; if (following.length === 0) { return null; // handled by discard/ruff logic } const sorted = [...following].sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); const lowest = sorted[0]; const highest = sorted[sorted.length - 1]; const dc = isDefender ? getDummyContext(trick, playerPos, hands, trumpSuit, state) : null; // DEFAULT: play low let pick = lowest; if (isDefender && dc) { // ---- DUMMY-AWARE SECOND HAND DEFENSE ---- // 1) Dummy plays AFTER us (3rd or 4th to play) — we can see their cards if (dc.dummyPlaysAfterMe && dc.dummyLen > 0) { // a) Dummy has singleton honor → capture it if we can if (dc.dummyLen === 1 && dc.dummyBest >= 11) { const captureCards = following.filter(c => CARD_RANK[c.rank] > dc.dummyBest); if (captureCards.length > 0) { captureCards.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); pick = captureCards[0]; // cheapest card that beats dummy's singleton honor } } // b) Dummy's best card beats our lowest — consider rising // But only if our higher card actually beats dummy's best // (otherwise, second hand low is still correct) else if (dc.dummyBest > CARD_RANK[lowest.rank] && CARD_RANK[highest.rank] > dc.dummyBest) { // We CAN beat dummy. But should we? // Rise if: dummy's best beats our low AND lead was a small card (declarer leading toward dummy) if (leadRank <= 10) { // Declarer leading small toward dummy's strength — // Only rise if dummy has a single threatening card we can capture // Otherwise, second hand low is usually still best (partner may win) // Exception: if dummy has a sure winner (Ace/King) and we have nothing above it, // don't waste our honor — play low if (dc.dummyBest <= 12) { // Dummy has Q or lower as best — if we have K+, consider rising // but only if dummy's card is the ONLY threat (short suit) if (dc.dummyLen <= 2) { const cheapWin = following.filter(c => CARD_RANK[c.rank] > dc.dummyBest); cheapWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); if (cheapWin.length > 0) pick = cheapWin[0]; } } } } } // 2) Dummy already played (is behind us or already in trick) // Standard second-hand logic applies, but we know dummy's card if (dc.dummyPlayed) { const dummyCard = trick.find(c => c.position === dc.dummyPos); if (dummyCard) { const dummyRank = CARD_RANK[dummyCard.rank]; // If dummy played high and is currently winning, try to beat it cheaply const best = currentWinner(trick, trumpSuit); if (best.position === dc.dummyPos) { const cheapWin = following.filter(c => CARD_RANK[c.rank] > dummyRank); cheapWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); if (cheapWin.length > 0) { pick = cheapWin[0]; } } } } // 3) Cover an honor with an honor // Standard bridge: ALWAYS cover an honor with an honor. // Covering collapses declarer's honors and may promote partner's cards. // Only exception: don't cover first of touching honors from dummy (wait for last). if (leadRank >= 11 && pick === lowest) { const coverCards = following.filter(c => CARD_RANK[c.rank] > leadRank); if (coverCards.length > 0) { let shouldCover = true; // Don't cover the first of touching honors FROM DUMMY — wait for the last // e.g. dummy leads Q from QJ: don't cover Q with K, wait and cover the J if (dc && dc.dummyPlayed === false) { const leaderPos = trick[0].position; if (leaderPos === dc.dummyPos) { // Dummy led this honor. Does dummy have the next lower honor too? const dummySuit = (hands[dc.dummyPos]?.[leadSuit] || []).map(r => CARD_RANK[r]); if (dummySuit.includes(leadRank - 1)) { shouldCover = false; // wait for the last of touching honors } } } if (shouldCover) { coverCards.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); pick = coverCards[0]; } } } } else if (isDefender) { // No dummy context available — fallback to original logic if (leadRank >= 11) { const coverCard = following.find(c => CARD_RANK[c.rank] === leadRank + 1); if (coverCard) pick = coverCard; } } else { // ---- DECLARER SECOND HAND PLAY ---- const leaderPos = trick[0].position; const myPartner = partnerOf(playerPos); const isOppLead = (leaderPos !== playerPos && leaderPos !== myPartner); if (isOppLead) { // Opponent led — decide whether to win or duck const canWin = following.filter(c => CARD_RANK[c.rank] > leadRank); if (canWin.length > 0 && leadRank >= 11) { // Opponent led an honor (J+) — win as cheaply as possible // Don't let their honor win when we have higher cards canWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); pick = canWin[0]; } else if (canWin.length > 0 && leadRank <= 10) { // Opponent led small — second hand low usually applies // But check if partner's hand (behind us) can contribute const partnerCards = (hands[myPartner]?.[leadSuit] || []).map(r => CARD_RANK[r]); const partnerBest = partnerCards.length > 0 ? Math.max(...partnerCards) : 0; if (partnerBest <= leadRank) { // Partner can't beat the lead — we should win cheaply canWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); pick = canWin[0]; } // Otherwise, play low and let partner handle it (second hand low) } } } // EXCEPTION: Don't play ace in second seat on small card // In suit contracts: almost never right (trumps may make ace the only winner) // In NT: also usually wrong — hold ace to control the suit later // UNLESS dummy awareness says we should (e.g. capturing singleton honor) if (CARD_RANK[pick.rank] === 14 && leadRank <= 10 && isDefender) { if (trumpSuit) { // Suit contract: revert unless capturing dummy's singleton honor if (!dc || !dc.dummyPlaysAfterMe || dc.dummyBest < 11 || dc.dummyLen > 1) { pick = lowest; } } else { // NT: hold up ace unless dummy has a singleton honor we can capture if (!dc || !dc.dummyPlaysAfterMe || dc.dummyBest < 12 || dc.dummyLen > 1) { pick = lowest; } } } // NT HOLDUP PLAY (declarer): Duck in NT when opponents lead their long suit // to break communications (exhaust the shorter defender's cards in this suit). // Generalized: not just Ace — duck with any winning card if we retain a stopper. if (!isDefender && !trumpSuit && trick.length >= 1) { const leaderPos = trick[0].position; const myPartner = partnerOf(playerPos); const isOppLead = (leaderPos !== playerPos && leaderPos !== myPartner); if (isOppLead) { const trickNum = state.trickHistory ? state.trickHistory.length : 0; const mySuitLen = (hand[leadSuit] || []).length; const partHand2 = hands[myPartner]; const partLen = (partHand2?.[leadSuit] || []).length; const combinedLen = mySuitLen + partLen; const myRanks = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); // Would our pick win the current trick? const pickRank = CARD_RANK[pick.rank]; const trickHigh = Math.max(...trick.map(c => c.suit === leadSuit ? CARD_RANK[c.rank] : 0)); const wouldWinTrick = pick.suit === leadSuit && pickRank > trickHigh; if (wouldWinTrick && mySuitLen >= 2 && combinedLen <= 5 && trickNum <= 1) { // After ducking (playing lowest), do we retain a stopper? // Our lowest card goes away; remaining cards must still beat what opponents have const lowestRank = myRanks[myRanks.length - 1]; const remainAfterDuck = myRanks.filter(r => r !== lowestRank || myRanks.indexOf(r) !== myRanks.length - 1); // We retain a stopper if at least one remaining card is high (K+) // or we have 2+ cards remaining (can duck again) const retainsStopper = remainAfterDuck.some(r => r >= 13) || (remainAfterDuck.length >= 2 && remainAfterDuck[0] >= 11); // QJ or better // Don't holdup if partner already has a stopper (double-stopped = no need) const partHasStopper = (partHand2?.[leadSuit] || []).some(r => CARD_RANK[r] >= 13); if (retainsStopper && !partHasStopper) { // Duck! Play low to exhaust shorter defender pick = lowest; } } } } // A4: ATTITUDE SIGNAL when playing low as defender (reverse attitude) // ONLY signal when our pick is the default lowest — don't override tactical choices // ONLY signal on PARTNER'S lead — when declarer/dummy leads, just follow low if (isDefender && pick === lowest && CARD_RANK[pick.rank] <= 10 && sorted.length >= 2) { // Check who led: only signal on partner's lead const leaderPos = trick[0].position; const partnerPos = state.partnerPos; const isPartnerLead = leaderPos === partnerPos; if (isPartnerLead) { // Signal cards: only use cards ≤ 9 to avoid wasting 10s/Jacks // that could have trick-taking potential const signalCards = sorted.filter(c => CARD_RANK[c.rank] <= 9); if (signalCards.length >= 2) { const suitCards = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const hasHonors = suitCards.some(r => r >= 12); const hasLength = suitCards.length >= 4; const wantSuit = hasHonors || hasLength; if (wantSuit) { pick = signalCards[0]; // Encouraging: play lowest signal card (reverse attitude) } else { pick = signalCards[signalCards.length - 1]; // Discouraging: play highest signal card } } } } return pick; } // ====================================== // THIRD HAND PLAY // Now dummy-aware: when dummy plays after us, plays high enough to beat dummy's best. // Also includes unblocking and refined signaling. // ====================================== function selectThirdHand(legal, hand, trick, trumpSuit, playerPos, hands, state) { const leadSuit = trick[0].suit; const partnerPos = partnerOf(playerPos); const partnerLed = trick[0].position === partnerPos; const following = legal.filter(c => c.suit === leadSuit); if (following.length === 0) return null; // ruff/discard handled elsewhere const sorted = [...following].sort((a, b) => CARD_RANK[b.rank] - CARD_RANK[a.rank]); const highest = sorted[0]; const lowest = sorted[sorted.length - 1]; const dc = state.isDefender ? getDummyContext(trick, playerPos, hands, trumpSuit, state) : null; if (!partnerLed) { // Opponent led — we're third hand after an opponent. // Play cheaply to win, or duck const canWin = following.filter(c => wouldWin(c, trick, trumpSuit)); if (canWin.length > 0) { canWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return canWin[0]; } return lowest; // can't win, play low } // ---- PARTNER LED — third hand high with dummy awareness ---- const best = currentWinner(trick, trumpSuit); const partnerWinning = best.position === partnerPos; // CRITICAL: If someone has RUFFED (won with a trump when a non-trump was led), // no card in the led suit can beat the trump. Just play low. // This prevents absurd plays like throwing CQ when the trick is already lost to a ruff. const trickRuffed = trumpSuit && best.suit === trumpSuit && best.suit !== leadSuit; if (trickRuffed) { // Can't beat a trump by following suit. Play low, save our honors. // Exception: if PARTNER ruffed, signal attitude if (partnerWinning && state.isDefender && following.length >= 2) { const smallCards = following.filter(c => CARD_RANK[c.rank] <= 9); if (smallCards.length >= 2) { const suitCards = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const hasHonors = suitCards.some(r => r >= 12); const hasLength = suitCards.length >= 4; if (hasHonors || hasLength) { return smallCards[0]; // Encouraging (reverse attitude) } else { return smallCards[smallCards.length - 1]; // Discouraging } } } return lowest; } // Determine the minimum rank we need to beat // This is the CRITICAL dummy-aware logic: // If dummy plays AFTER us, we must beat dummy's best card, not just the current trick winner let targetRank = CARD_RANK[best.rank]; // default: beat current winner if (dc && dc.dummyPlaysAfterMe && dc.dummyLen > 0) { // Dummy hasn't played yet and will play after us // We MUST beat dummy's best card in the suit, otherwise dummy wins cheaply targetRank = Math.max(targetRank, dc.dummyBest); } // THIRD HAND HIGH: When declarer plays AFTER us, we need to play high enough // to force declarer's best card, not let them win cheaply with an intermediate. // E.g., partner leads D4, we have DJ853, declarer has DAT. // Playing D5 lets declarer win with DT (cheap). Playing DJ forces DA. // Only when: (a) partner led low (not cashing), (b) declarer is 4th to play if (state.isDefender && partnerLed && CARD_RANK[best.rank] <= 10) { const declarerPos = state.contractInfo?.declarer; const fourthPlayer = POS[(POS.indexOf(playerPos) + 1) % 4]; if (fourthPlayer === declarerPos) { const decInSuit = (hands[declarerPos]?.[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (decInSuit.length >= 2) { // Force declarer to use their best: beat their second-best const secondBest = decInSuit[1]; targetRank = Math.max(targetRank, secondBest); } } } // Is partner currently winning AND safe from being beaten? if (partnerWinning) { const partnerRank = CARD_RANK[best.rank]; // Check: can the remaining player(s) beat partner? let partnerSafe = true; let threatIsDummy = false; // visible threat (can use targetRank logic) let threatIsDeclarer = false; // invisible threat (must play high) if (dc && dc.dummyPlaysAfterMe) { // Dummy plays after us — can dummy beat partner? if (dc.dummyBest > partnerRank) { partnerSafe = false; threatIsDummy = true; } if (dc.dummyVoid && dc.dummyCanRuff) { partnerSafe = false; threatIsDummy = true; } } // Declarer plays after us? if (dc && dc.declarerPlaysAfterMe) { // We can't see declarer's hand, so only trust partner's high cards if (partnerRank >= 14) { /* Ace is always safe */ } else if (partnerRank >= 13) { /* King is very likely safe */ } else { partnerSafe = false; threatIsDeclarer = true; } } // CORRECTION: If we hold ALL outstanding cards higher than partner's, // partner is safe regardless — declarer can't beat partner. // E.g., partner leads Q, we hold AK → Q is effectively master. if (threatIsDeclarer && following.length > 0) { const myRanks = following.map(c => CARD_RANK[c.rank]); const outstandingHigher = outstandingInSuit(leadSuit, { [playerPos]: hand, ...(dc?.dummyPos ? { [dc.dummyPos]: hands[dc.dummyPos] } : {}) }, state.playedCards || {} ).filter(r => CARD_RANK[r] > partnerRank); // Check if every outstanding higher card is in our hand const weHoldAll = outstandingHigher.every(r => myRanks.includes(CARD_RANK[r])); if (weHoldAll) { partnerSafe = true; threatIsDeclarer = false; } } // DECLARER SIDE: check if 4th-seat opponent can beat partner if (!state.isDefender) { const fourthPos = POS[(POS.indexOf(playerPos) + 1) % 4]; // 4th player is an opponent if (fourthPos !== partnerPos) { const oppCards = (hands[fourthPos]?.[leadSuit] || []).map(r => CARD_RANK[r]); const oppBest = oppCards.length > 0 ? Math.max(...oppCards) : 0; if (oppBest > partnerRank) { partnerSafe = false; targetRank = Math.max(targetRank, oppBest); // must beat opponent's card } // Opponent might ruff if void in led suit if (oppCards.length === 0 && trumpSuit && leadSuit !== trumpSuit) { const oppTrumps = (hands[fourthPos]?.[trumpSuit] || []).length; if (oppTrumps > 0) partnerSafe = false; } } } if (partnerSafe) { // Partner's card will hold — signal attitude (reverse: low = encouraging) if (state.isDefender && following.length >= 2) { const smallCards = following.filter(c => CARD_RANK[c.rank] <= 9); if (smallCards.length >= 2) { smallCards.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); const suitCards = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const hasHonors = suitCards.some(r => r >= 12); const hasLength = suitCards.length >= 4; if (hasHonors || hasLength) { return smallCards[0]; // Encouraging: play lowest (reverse attitude) } else { return smallCards[smallCards.length - 1]; // Discouraging: play highest small } } } // DECLARER SIDE in NT: when partner (declarer) leads LOW toward our honors, // win with cheapest honor to get to this hand / establish the suit. // Only in NT: suit contracts have complex ruff/duck/timing considerations // where dummy staying low may be correct (e.g. ducking to set up a ruff). if (!state.isDefender && !trumpSuit && partnerRank <= 10) { const canWinHere = following.filter(c => CARD_RANK[c.rank] > CARD_RANK[best.rank]); if (canWinHere.length > 0) { canWinHere.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return canWinHere[0]; // Win cheaply with honor } } // Unblock: if partner leads Ace and we have King doubleton, play King if (partnerRank >= 14 && following.length === 2) { const highCard = sorted[0]; if (CARD_RANK[highCard.rank] >= 13) { return highCard; // Unblock the King (or Queen) under partner's Ace } } return lowest; } // Partner NOT safe — need to play high // DEFENDER 3rd hand high: when the UNSEEN DECLARER is the threat (not visible dummy), // play our HIGHEST card (or lowest of a top sequence) to maximize chance of winning. // When DUMMY is the threat, use standard targetRank logic below (we can see what to beat). if (state.isDefender && partnerLed && threatIsDeclarer && !threatIsDummy) { // Play highest of our following cards, with sequence refinement if (sorted.length > 0) { const topCard = sorted[0]; // Find bottom of touching sequence from our top card (e.g., KQ → Q, AKQ → Q) const seq = [topCard]; for (let i = 1; i < sorted.length; i++) { if (CARD_RANK[sorted[i].rank] === CARD_RANK[seq[seq.length - 1].rank] - 1 && sorted[i].suit === topCard.suit) { seq.push(sorted[i]); } else break; } return seq[seq.length - 1]; // Lowest of top sequence } } // Fall through to standard "need to win" logic (uses targetRank for visible threats) } // Need to win the trick — find cheapest card that beats the target const winners = following.filter(c => CARD_RANK[c.rank] > targetRank); if (winners.length > 0) { winners.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); const cheapestWinner = winners[0]; // Refinement: from a sequence (QJT), play the BOTTOM of the sequence // This signals to partner what we DON'T have const winnerRank = CARD_RANK[cheapestWinner.rank]; const seq = [cheapestWinner]; for (let i = 1; i < sorted.length; i++) { if (CARD_RANK[sorted[i].rank] === CARD_RANK[seq[seq.length - 1].rank] - 1 && CARD_RANK[sorted[i].rank] > targetRank) { seq.push(sorted[i]); } else break; } // Play bottom of touching sequence that all beat the target return seq[seq.length - 1]; } // THIRD HAND HIGH FALLBACK: Can't beat the raised target (e.g. declarer's CQ), // but our highest card still forces declarer to spend more than their cheapest. // E.g., partner leads C8, we have CJ74, declarer has CKQT. // CJ can't beat CQ, but forces CK. C4 only forces CT — wastes nothing. // Play highest when: defender, partner led, declarer is 4th, and our highest // beats at least declarer's cheapest card in the suit. if (state.isDefender && partnerLed) { const declarerPos2 = state.contractInfo?.declarer; const fourthPlayer2 = POS[(POS.indexOf(playerPos) + 1) % 4]; if (fourthPlayer2 === declarerPos2) { const decCards = (hands[declarerPos2]?.[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const myBestRank = sorted.length > 0 ? CARD_RANK[sorted[0].rank] : 0; // Only play high if our best actually forces declarer above their cheapest if (decCards.length >= 2 && myBestRank > decCards[decCards.length - 1]) { return sorted[0]; // Third hand high — force declarer to spend a winner } } } // Can't beat dummy's BEST card — but can we beat dummy's INTERMEDIATE cards? // This forces dummy to spend their top card instead of winning cheaply with a low one. // Example: dummy has K,8 — we have 9,7 — play 9 to force the K (don't let 8 win!) if (dc && dc.dummyPlaysAfterMe && dc.dummyLen >= 2) { // Find dummy's second-best card (the cheap winner we want to deny) const dummySecond = dc.dummyInSuit[1]; // 2nd highest dummy card in suit const intermediateWinners = following.filter(c => CARD_RANK[c.rank] > dummySecond); if (intermediateWinners.length > 0) { // We can beat dummy's intermediate card — play cheapest card that does intermediateWinners.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return intermediateWinners[0]; } } // Also check: can we at least beat the current trick winner, even if not dummy's best? // This matters when partner's card is losing to the lead but we can still contribute if (!partnerWinning) { const beatCurrent = following.filter(c => CARD_RANK[c.rank] > CARD_RANK[best.rank]); if (beatCurrent.length > 0) { beatCurrent.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return beatCurrent[0]; } } // Truly can't help — play low return lowest; } // ====================================== // FOURTH HAND PLAY // Now dummy-aware: checks partner's position, avoids overtaking partner's winners, // wins cheaply, and signals when can't win. // ====================================== function selectFourthHand(legal, trick, trumpSuit, playerPos, hands, hand, state) { const leadSuit = trick[0].suit; const following = legal.filter(c => c.suit === leadSuit); if (following.length === 0) return null; // ruff/discard const best = currentWinner(trick, trumpSuit); const partnerPos = partnerOf(playerPos); const partnerWinning = best.position === partnerPos; const isDefender = state.isDefender; const sorted = [...following].sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); const lowest = sorted[0]; const highest = sorted[sorted.length - 1]; // Can we win? const canWin = following.filter(c => wouldWin(c, trick, trumpSuit)); if (partnerWinning) { // Partner is winning — don't overtake unless our card is equivalent // Just play low (signal if defender) if (isDefender && sorted.length >= 2) { const smallCards = sorted.filter(c => CARD_RANK[c.rank] <= 9); if (smallCards.length >= 2) { const suitCards = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const hasHonors = suitCards.some(r => r >= 12); const hasLength = suitCards.length >= 4; if (hasHonors || hasLength) { return smallCards[0]; // Encouraging: lowest (reverse attitude) } else { return smallCards[smallCards.length - 1]; // Discouraging: highest small } } } return lowest; } // Partner NOT winning if (canWin.length > 0) { // NT HOLDUP in 4th seat: declarer may want to duck to cut communications if (!isDefender && !trumpSuit) { const trickNum = state.trickHistory ? state.trickHistory.length : 0; const leaderPos = trick[0].position; const isOppLead = (leaderPos !== playerPos && leaderPos !== partnerPos); if (isOppLead && trickNum <= 1) { const mySuitLen = (hand[leadSuit] || []).length; const partHand4 = hands[partnerPos]; const partLen = (partHand4?.[leadSuit] || []).length; const combinedLen = mySuitLen + partLen; if (mySuitLen >= 2 && combinedLen <= 5) { const myRanks = (hand[leadSuit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const lowestRank = myRanks[myRanks.length - 1]; const remainAfterDuck = myRanks.slice(0, -1); // remove lowest const retainsStopper = remainAfterDuck.some(r => r >= 13) || (remainAfterDuck.length >= 2 && remainAfterDuck[0] >= 11); const partHasStopper = (partHand4?.[leadSuit] || []).some(r => CARD_RANK[r] >= 13); if (retainsStopper && !partHasStopper) { return lowest; // Duck to exhaust shorter defender } } } } // Win as cheaply as possible canWin.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return canWin[0]; } // Can't win — play lowest return lowest; } // ====================================== // RUFF OR DISCARD (when void in led suit) // ====================================== function selectRuffOrDiscard(legal, hand, trick, trumpSuit, playerPos, hands, state) { const leadSuit = trick[0].suit; const myCards = legal; // already filtered to non-follow cards // Can we ruff? if (trumpSuit) { const trumpCards = myCards.filter(c => c.suit === trumpSuit); if (trumpCards.length > 0) { const best = currentWinner(trick, trumpSuit); const partnerWinning = best.position === partnerOf(playerPos); if (!partnerWinning || state.isDeclarer) { // Check: can we actually OVERRUFF the current winner? const winnerRank = best.suit === trumpSuit ? CARD_RANK[best.rank] : 0; const overruffs = trumpCards.filter(c => CARD_RANK[c.rank] > winnerRank); if (overruffs.length > 0) { overruffs.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); let trumpToUse = overruffs[0]; // default: lowest overruff // OVERRUFF PROTECTION: if a player behind us might have trumps, // ruff high enough to prevent the overruff. const fourthPos = POS[(POS.indexOf(playerPos) + 1) % 4]; if (trick.length === 2) { // we're 3rd, 4th player is behind us if (state.isDeclarer || fourthPos === state.contractInfo?.dummy) { // We can see 4th player's hand (it's our partner/dummy or visible dummy) const fourthTrumps = (hands[fourthPos]?.[trumpSuit] || []).map(r => CARD_RANK[r]); const fourthBestTrump = fourthTrumps.length > 0 ? Math.max(...fourthTrumps) : 0; if (fourthBestTrump > CARD_RANK[trumpToUse.rank]) { // 4th player can overruff our lowest — find cheapest that beats them const safeRuffs = overruffs.filter(c => CARD_RANK[c.rank] > fourthBestTrump); if (safeRuffs.length > 0) { trumpToUse = safeRuffs[0]; // cheapest trump that prevents overruff } else { // Can't prevent overruff — ruff with highest anyway (might promote partner's trump) trumpToUse = overruffs[overruffs.length - 1]; } } } else { // Can't see 4th player (declarer is behind us) — ruff as high as we can afford. // "Afford" = use highest trump below J (don't waste natural trump tricks). // With S93, play S9. With SQ3, play S3 (Q is a natural trick). const cheapTrumps = overruffs.filter(c => CARD_RANK[c.rank] < 11); if (cheapTrumps.length > 0) { trumpToUse = cheapTrumps[cheapTrumps.length - 1]; // highest cheap trump } // If all trumps are honors (J+), keep lowest to preserve trump tricks } } // SMART RUFF: As defender, don't ruff with a "natural" trump trick // A high trump (K, Q, or protected J) would likely win a trick on its own. // Ruffing wastes it — same as cashing it, but we lose the timing advantage. // Exception: always ruff as declarer (different calculation). if (state.isDefender && CARD_RANK[trumpToUse.rank] >= 12 && trumpCards.length >= 2) { // This trump is likely a natural winner — prefer discarding // Unless it's our only trump that can overruff (forced) if (overruffs.length > 1) { // We have cheaper overruffs — use lowest // (already sorted, so trumpToUse IS the lowest — natural trick check still applies) } // Only skip ruffing if this specific trump is high enough to win on its own const myTrumpRanks = trumpCards.map(c => CARD_RANK[c.rank]).sort((a, b) => b - a); if (myTrumpRanks[0] >= 13) { // We hold K+ of trumps — this will likely win a natural trick // Discard instead (fall through to discard logic) } else { return trumpToUse; // Q or J — borderline, ruff } } else { return trumpToUse; } } // Can't overruff — don't waste a trump, discard instead } // Partner is winning — don't overruff partner, discard instead } } // Discard: knowledge-enhanced reverse attitude (low = encouraging, high = discouraging) const knowledge = state.tracking; const dummyPos = state.contractInfo?.dummy; const dummyHand = dummyPos ? hands[dummyPos] : null; const isDefender = state.isDefender; let bestCard = null, bestScore = -999; for (const card of myCards) { if (card.suit === trumpSuit) continue; // don't discard trumps for signaling const suitCards = (hand[card.suit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const rankVal = CARD_RANK[card.rank]; let score = 0; const hasHonors = suitCards.length >= 1 && suitCards[0] >= 12; const hasLength = suitCards.length >= 4; const wantSuit = hasHonors || hasLength; if (wantSuit) { // Discard LOW from suits we want (reverse attitude = low is encouraging) score = (15 - rankVal) + 10; } else { // Discard HIGH from suits we don't want score = rankVal; } // Protect honors — never signal with J, Q, K, A if (rankVal >= 11) score -= 25; // Don't bare a king or queen if (rankVal >= 12 && suitCards.length <= 2) score -= 15; // Don't unguard a jack if (rankVal >= 11 && suitCards.length <= 2) score -= 10; // === KNOWLEDGE-BASED DISCARD PROTECTION === if (isDefender && dummyHand) { const dummyInSuit = (dummyHand[card.suit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); // CRITICAL: Don't discard from a suit where we're the ONLY guard against dummy's winners // e.g. dummy has KQJ93, we have AT7 — if we discard, dummy runs the suit if (dummyInSuit.length >= 4) { const dummyTop = dummyInSuit[0]; if (suitCards[0] > dummyTop) { // We hold the top card — we're guarding this suit! score -= 30; } else if (suitCards.length >= dummyInSuit.length - 1) { // We have enough length to prevent dummy from running the suit score -= 15; } } // Don't discard from a suit where dummy has a lone high card we might capture if (dummyInSuit.length === 1 && dummyInSuit[0] >= 12 && suitCards[0] > dummyInSuit[0]) { score -= 20; } } // Use honor locations if available if (knowledge.honorLocations) { const hl = knowledge.honorLocations[card.suit]; if (hl) { // Don't discard from suits where partner holds honors (partner needs support) const partnerPos = partnerOf(playerPos); const partnerHoldsHonor = ['a','k','q','j'].some(r => hl[r]?.player === partnerPos && hl[r]?.status === 'held'); if (partnerHoldsHonor && suitCards.length >= 2) score -= 10; } } if (score > bestScore) { bestScore = score; bestCard = card; } } return bestCard || myCards[0]; } // ====================================== // DEFENDER LEAD SELECTION (non-opening) // ====================================== function selectDefenderLead(legal, hand, trumpSuit, playerPos, hands, state) { const partnerPos = partnerOf(playerPos); const { trickHistory, contractInfo, tracking, auction, dealer } = state; const declarerPos = contractInfo?.declarer; const dummyPos = contractInfo?.dummy; const declarerBidSuits = declarerPos ? getSuitsBidBy(declarerPos, auction, dealer) : []; const dummyBidSuits = dummyPos ? getSuitsBidBy(dummyPos, auction, dealer) : []; const dummyHand = dummyPos ? hands[dummyPos] : null; const knowledge = tracking; const honorLoc = knowledge.honorLocations || {}; const suitCtrl = knowledge.suitControl || {}; // === CONTRACT CONTEXT === const isSuit = !!trumpSuit; const isNT = !trumpSuit; const contractLevel = contractInfo?.level || 1; const isPartscore = contractLevel <= 2; const isGame = contractLevel >= 3 && contractLevel <= 5; const isSlam = contractLevel >= 6; // === TRICK COUNTING === const tricksMade = trickHistory ? trickHistory.length : 0; const tricksNeededByDeclarer = contractLevel + 6; const tricksNeededToSet = 14 - tricksNeededByDeclarer; const nsIsDefending = isNS(playerPos); const defenseTricks = nsIsDefending ? trickHistory?.filter(t => t.winner === 'N' || t.winner === 'S').length || 0 : trickHistory?.filter(t => t.winner === 'E' || t.winner === 'W').length || 0; const tricksStillNeeded = tricksNeededToSet - defenseTricks; const cardsLeft = SUIT_ORDER.reduce((n, s) => n + (hand[s] || []).length, 0); const isUrgent = tricksStillNeeded >= cardsLeft; const declarerTricks = tricksMade - defenseTricks; const declarerNearlyHome = declarerTricks >= tricksNeededByDeclarer - 2; // === PRE-SCAN: Build suit-level knowledge === const partnerLedSuits = tracking.suitsLedBy?.[partnerPos] || []; const declarerVoids = tracking.voids?.[declarerPos] || new Set(); const dummyVoids = tracking.voids?.[dummyPos] || new Set(); // Partner signal preferences const partnerEncouraged = new Set(); const partnerDiscouraged = new Set(); if (tracking.discardSignals?.[partnerPos]) { for (const [s, sig] of Object.entries(tracking.discardSignals[partnerPos])) { if (sig === 'encouraging') partnerEncouraged.add(s); if (sig === 'discouraging') partnerDiscouraged.add(s); } } if (tracking.partnerSignals?.[partnerPos]) { for (const [s, sig] of Object.entries(tracking.partnerSignals[partnerPos])) { if (sig === 'encouraging') partnerEncouraged.add(s); if (sig === 'discouraging') partnerDiscouraged.add(s); } } // Improved dummy-threatens: count actual running tricks (AKQJ... sequence) let dummyRunSuit = null; let dummyRunCount = 0; if (dummyHand) { for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const dc = (dummyHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (dc.length < 3) continue; let running = 0; for (let i = 0; i < dc.length; i++) { if (dc[i] >= 14 - i) running++; else break; } if (running >= 3 && running > dummyRunCount) { dummyRunCount = running; dummyRunSuit = s; } } } // === PRIORITY: Cash known winners first === // Before complex scoring, check for guaranteed winners (cards higher than all outstanding) const visibleHands = { [playerPos]: hand }; if (dummyPos) visibleHands[dummyPos] = hands[dummyPos]; const cashable = findCashableWinners(hand, visibleHands, state.playedCards || {}); const nonTrumpCashable = cashable.filter(c => c.suit !== trumpSuit); if (nonTrumpCashable.length > 0 && (isUrgent || declarerNearlyHome)) { // When urgent or declarer is close, cash winners immediately // Pick highest winner from shortest suit (unblock) nonTrumpCashable.sort((a, b) => { const lenA = (hand[a.suit] || []).length, lenB = (hand[b.suit] || []).length; if (lenA !== lenB) return lenA - lenB; // shorter suit first return CARD_RANK[b.rank] - CARD_RANK[a.rank]; // then highest card }); if (legal.some(c => c.suit === nonTrumpCashable[0].suit && c.rank === nonTrumpCashable[0].rank)) { return nonTrumpCashable[0]; } } // === UNIFIED SCORING: Score each SUIT, then pick best card from best suit === const suitScores = {}; for (const suit of SUIT_ORDER) { const myCards = (hand[suit] || []); const inSuit = legal.filter(c => c.suit === suit); if (inSuit.length === 0) { suitScores[suit] = -999; continue; } const sorted = [...myCards].sort((a, b) => CARD_RANK[b] - CARD_RANK[a]); const len = myCards.length; const myBest = sorted.length > 0 ? CARD_RANK[sorted[0]] : 0; let score = 0; const seq = findSequence(sorted); const hasGoodSeq = seq.length >= 2 && isHonor(seq[0]); const intSeq = findInternalSequence(sorted); const hasIntSeq = intSeq && intSeq.length >= 2; const hasMaster = inSuit.some(c => isMaster(c, hands, playerPos)); // ------ A. CASH AK: Very strong when we hold both ------ const hasAK = sorted.includes('a') && sorted.includes('k'); if (hasAK && suit !== trumpSuit) { score += 55; // Near-automatic in suit contracts if (isNT && len >= 5) score += 15; // In NT with length, even better — establishes suit } // ------ B. SEQUENCE LEADS: Safe and attacking ------ if (hasGoodSeq) { const seqTopRank = CARD_RANK[seq[0]]; if (seqTopRank >= 11) { score += 30; if (seq.length >= 3) score += 15; } else { score += 18; // Ten-high: adequate but weaker } if (isNT) score += len * 3; // Length bonus in NT for sequences } if (hasIntSeq && !hasGoodSeq) { score += 18; } // ------ C. PARTNER'S SUIT: Very strong default ------ if (partnerLedSuits.includes(suit)) { // Check if partner's suit was discouraged const mySignal = tracking.partnerSignals?.[playerPos]?.[suit]; const partSig = tracking.partnerSignals?.[partnerPos]?.[suit]; const discSig = tracking.discardSignals?.[partnerPos]?.[suit]; const discouraged = mySignal === 'discouraging' || partSig === 'discouraging' || discSig === 'discouraging'; if (!discouraged) { score += isNT ? 35 : 25; // Partner's suit is MORE important in NT (communication) if (len === 1) score += 5; // Singleton return — may give partner ruff } else { score -= 5; // Discouraged — mild penalty } } // ------ D. PARTNER ENCOURAGED via discard ------ if (partnerEncouraged.has(suit)) score += 20; if (partnerDiscouraged.has(suit)) score -= 10; // ------ E. TAP DEFENSE (suit contracts only) ------ if (isSuit && declarerVoids.has(suit) && !dummyVoids.has(suit) && suit !== trumpSuit) { const dummyLen = (hands[dummyPos]?.[suit] || []).length; const declarerTrumps = (hands[declarerPos]?.[trumpSuit] || []).length; if (dummyLen > 0 && declarerTrumps > 0) { score += 40; // Force declarer to ruff — shortens their trump length } } // ------ F. TRUMP LEAD TO CUT RUFFS (suit contracts only) ------ if (isSuit && suit === trumpSuit && dummyHand) { const dummyTrumps = (dummyHand[trumpSuit] || []).length; const dummyHasShort = SUIT_ORDER.some(s => { if (s === trumpSuit) return false; return (dummyHand[s] || []).length <= 1; }); if (dummyTrumps > 0 && dummyHasShort) { score += 30; // Cut dummy's ruffs } // General trump lead penalty otherwise if (!dummyHasShort || dummyTrumps === 0) score -= 10; } else if (isSuit && suit === trumpSuit) { score -= 10; // Don't lead trumps without reason } // ------ G. DUMMY-THREATENS URGENCY ------ // When dummy has a running suit, cash our winners in OTHER suits before they're discarded if (dummyRunCount >= 3 && suit !== dummyRunSuit && suit !== trumpSuit) { if (hasMaster && myBest >= 12) { score += 20; // Cash winners before dummy discards our suit if (isUrgent) score += 10; } // But DON'T cash a master that guards dummy's honor in this suit const dummySuit = dummyHand ? (dummyHand[suit] || []).map(r => CARD_RANK[r]) : []; const dummyBestInSuit = dummySuit.length > 0 ? Math.max(...dummySuit) : 0; if (dummyBestInSuit >= 11 && myBest > dummyBestInSuit && myBest < 14) { score -= 25; // Our card guards dummy's honor — don't cash it away } } // Penalize leading dummy's running suit if (suit === dummyRunSuit) score -= 25; // ------ H. MASTER CARDS ------ if (hasMaster) { score += 15; // In NT, cashing masters is less urgent (no ruffing danger) if (isNT && !isUrgent) score -= 5; } // ------ I. HONOR SAFETY: Don't lead unsupported honors ------ if (isHonor(sorted[0]) && !hasGoodSeq && !hasIntSeq && len >= 2) { score -= 12; // Risky lead if (isNT && (sorted[0] === 'q' || sorted[0] === 'j') && len <= 3) { score -= 10; // Qxx or Jxx is terrible in NT } } // Don't underlead AQ or KJ tenaces const holdAQ = sorted.includes('a') && sorted.includes('q') && !sorted.includes('k'); const holdKJ = sorted.includes('k') && sorted.includes('j') && !sorted.includes('q'); if (holdAQ || holdKJ) score -= 15; // ------ J. DUMMY AWARENESS ------ if (dummyHand) { const dummyCards = (dummyHand[suit] || []); const dummyRanks = dummyCards.map(r => CARD_RANK[r]); const dummyBestRank = dummyRanks.length > 0 ? Math.max(...dummyRanks) : 0; // POSITIONAL CHECK: Does partner sit behind dummy? // When I lead, play order is me → next → next → next. // If dummy is immediately after me, partner plays AFTER dummy // and can see dummy's card before committing → positional advantage. const partnerBehindDummy = dummyPos === nextOf(playerPos); // Penalize leading into dummy's long strong suits. // In NT, when partner sits behind dummy, positional advantage reduces threat. // In suit contracts, keep full penalties (dummy has trump entries to cash winners). const dummyPenFactor = (isNT && partnerBehindDummy) ? 0.5 : 1.0; if (dummyCards.length >= 4 && dummyRanks.some(r => r >= 12)) { score -= Math.round(12 * dummyPenFactor); } if (dummyCards.length >= 5 && dummyRanks.some(r => r >= 14)) { score -= Math.round(20 * dummyPenFactor); } // TENACE OVER DUMMY: Don't lead suits where we sit over dummy's honor // Only applies when dummy plays AFTER us (we're leading into our own tenace) // When partner is behind dummy, WE don't have the tenace problem if (myBest > dummyBestRank && dummyBestRank >= 11 && !partnerBehindDummy) { if (myBest >= 14 && dummyBestRank >= 13) score -= 35; // A over K else if (myBest >= 14 && dummyBestRank >= 12) score -= 25; // A over Q else if (myBest >= 13 && dummyBestRank >= 12) score -= 25; // K over Q else if (myBest >= 13 && dummyBestRank >= 11) score -= 18; // K over J else score -= 12; } // When declarer is VOID (tap defense), tenace against dummy is irrelevant // — declarer will ruff, not finesse if (myBest > dummyBestRank && dummyBestRank >= 11 && declarerVoids.has(suit)) { // Undo any tenace penalty that was applied score += 0; // Already handled by !partnerBehindDummy above in most cases } // THROUGH STRENGTH: Lead through dummy's honors toward partner // Partner behind dummy means partner's honors trap dummy's. // Key: the advantage is positional — only matters for FINESSABLE honors // (K, Q, J) that partner might beat. Ace always wins regardless of position. if (partnerBehindDummy && dummyCards.length >= 1 && myBest <= dummyBestRank) { const dummyFinessable = dummyRanks.filter(r => r >= 11 && r <= 13); // K, Q, J const dummyHasAce = dummyRanks.some(r => r >= 14); if (dummyFinessable.length > 0) { // Dummy has K/Q/J that partner might sit over — lead through! let throughBonus = isNT ? 18 : 12; // If dummy also has the Ace, slightly less valuable (Ace is safe) // but still good — partner's honors trap the lower ones (e.g., AQ: K traps Q) if (dummyHasAce) throughBonus = isNT ? 14 : 8; score += throughBonus; // Extra bonus if partner is known to hold honors in this suit if (honorLoc[suit]) { const partnerHoldsHere = ['a','k','q','j'].some(r => honorLoc[suit][r]?.player === partnerPos && honorLoc[suit][r]?.status === 'held'); if (partnerHoldsHere) score += 12; } } } // BIDDING INFERENCE: If declarer didn't bid this suit in NT, // missing honors are more likely with the defenders. // A suit dummy has length in but declarer didn't support is attackable. if (isNT && partnerBehindDummy && dummyCards.length >= 4) { if (!declarerBidSuits.includes(suit) && !dummyBidSuits.includes(suit)) { // Unbid suit with dummy length — partner likely holds missing honors score += 8; } } // Dummy void — safe in NT, may mean ruff in suit contracts if (dummyCards.length === 0) { if (isNT) score += 8; // Safe lead else if ((dummyHand[trumpSuit] || []).length > 0) score -= 15; // Dummy can ruff! } } // ------ K. OPPONENT BID SUITS ------ if (declarerBidSuits.includes(suit)) score -= 15; if (dummyBidSuits.includes(suit)) score -= 10; // ------ L. KNOWLEDGE-BASED SCORING ------ if (honorLoc[suit]) { const partnerHoldsHonor = ['a','k','q','j'].some(r => honorLoc[suit][r]?.player === partnerPos && honorLoc[suit][r]?.status === 'held'); if (partnerHoldsHonor) score += 8; } if (suitCtrl[suit]) { const ourSide = nsIsDefending ? 'NS' : 'EW'; if (suitCtrl[suit].controller === ourSide) score += 5; } // ------ M. CONTRACT LEVEL MODIFIERS ------ if (isSlam) { // Against slams: attack — need to find tricks NOW if (hasMaster) score += 15; if (hasGoodSeq) score += 10; // Don't lead passively against a slam if (!hasMaster && !hasGoodSeq && !hasIntSeq && !hasAK) score -= 10; } if (isPartscore) { // Against partscores: passive defense, don't give away tricks if (isHonor(sorted[0]) && !hasGoodSeq && len >= 2) score -= 8; // Safe passive leads get a bonus if (!isHonor(sorted[0]) && len >= 3) score += 5; } // ------ N. SUIT VS NT SPECIFIC ------ if (isNT) { // In NT: length matters — establish your long suit if (len >= 5) score += 15; if (len >= 4) score += 8; // Top of nothing from worthless suit is passive but safe if (!isHonor(sorted[0]) && len >= 3 && !hasMaster) { if (isPartscore) score += 8; // passive lead bonus } } else { // In suit contracts: shortness has ruff value if (suit !== trumpSuit && len === 1) score += 15; if (suit !== trumpSuit && len === 2 && !isHonor(sorted[0])) score += 5; } // ------ O. ACTIVE / PASSIVE MODIFIERS ------ if (isUrgent) { if (hasMaster) score += 10; if (hasGoodSeq) score += 5; } if (!isUrgent && tricksStillNeeded <= 1) { // We almost have enough tricks — be passive, don't give anything away if (isHonor(sorted[0]) && !hasGoodSeq) score -= 10; } // Own signal preferences if (tracking.discardSignals?.[playerPos]?.[suit] === 'encouraging') score += 5; if (tracking.discardSignals?.[playerPos]?.[suit] === 'discouraging') score -= 5; suitScores[suit] = score; } // === PICK BEST SUIT === let bestSuit = null, bestScore = -9999; for (const suit of SUIT_ORDER) { if (suitScores[suit] > bestScore) { bestScore = suitScores[suit]; bestSuit = suit; } } if (!bestSuit) return legal[0]; // === PICK BEST CARD FROM BEST SUIT === const inSuit = legal.filter(c => c.suit === bestSuit); return selectCardInSuit(inSuit, hand, bestSuit, hands, playerPos); } // Helper: select the right card when returning partner's suit // Now master-aware: cashes winners (Ace, master) before returning low function selectCardInSuit(inSuit, hand, suit, hands, playerPos) { if (inSuit.length === 1) return inSuit[0]; const sorted = [...inSuit].sort((a, b) => CARD_RANK[b.rank] - CARD_RANK[a.rank]); // CRITICAL: If our top card is the Ace or a master, CASH IT first // Don't underlead an Ace when returning partner's suit — it gives declarer free tricks if (hands && playerPos) { const topCard = sorted[0]; if (CARD_RANK[topCard.rank] === 14) { return topCard; // Always cash the Ace } if (isMaster(topCard, hands, playerPos) && CARD_RANK[topCard.rank] >= 12) { return topCard; // Cash any master Q+ } } const ranks = sorted.map(c => c.rank); const seq = findSequence(ranks); if (seq.length >= 2 && isHonor(seq[0])) { return sorted.find(c => c.rank === seq[0]); } // Honor doubleton (Kx, Qx, Jx) where the honor is NOT a master: // lead LOW to preserve the honor. Partner likely has the boss cards. // "Top of doubleton" only applies to spot cards (73, 84, etc.) if (sorted.length === 2) { const topRank = CARD_RANK[sorted[0].rank]; if (topRank >= 11) { return sorted[1]; // Lead low from Kx/Qx/Jx — save the honor } return sorted[0]; // Top of doubleton for spot cards } if (sorted.length >= 4) return sorted[3]; // 4th best return sorted[sorted.length - 1]; // 3 cards: lowest } // ====================================== // DECLARER LEAD SELECTION // ====================================== function selectDeclarerLead(legal, hand, trumpSuit, playerPos, hands, state) { const { contractInfo } = state; const declarerPos = contractInfo.declarer; const dummyPos = contractInfo.dummy; const decHand = hands[declarerPos]; const dumHand = hands[dummyPos]; const myHand = hands[playerPos]; const partPos = playerPos === declarerPos ? dummyPos : declarerPos; const partHand = hands[partPos]; // ============================================================ // A6: DECLARER PLANNING — Pre-scan for strategic opportunities // ============================================================ // --- Plan 1: Discard setup --- // Detect suits where cashing our top cards creates a void, // enabling discards on partner's remaining winners in that suit. // E.g., I have SAK (2 cards), partner has SQJ2 (3 cards). // Cash SAK -> I'm void -> cross to partner -> SQ = discard. const discardSetupSuits = {}; for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const myCards = (myHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const partCards = (partHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (myCards.length === 0 || myCards.length > 3 || partCards.length <= myCards.length) continue; // Get opponent cards sorted descending let oppCards = []; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) { for (const r of (hands[p][s] || [])) oppCards.push(CARD_RANK[r]); } } oppCards.sort((a, b) => b - a); // Check: all my cards beat all opponent cards (my lowest > their highest) const allMyWin = oppCards.length === 0 || myCards[myCards.length - 1] > oppCards[0]; if (!allMyWin) { // Fallback: check combined top sequence (AKQJ...) const combined = [...myCards, ...partCards].sort((a, b) => b - a); let topSeq = 0; for (let i = 0; i < combined.length; i++) { if (combined[i] >= 14 - i) topSeq++; else break; } if (myCards[myCards.length - 1] < 14 - topSeq + 1) continue; if (topSeq < myCards.length + 1) continue; } // After cashing myLen rounds, do partner's remaining cards beat opponents' remaining? // Each round removes ~2 opponent cards (one from each defender) const oppAfterRounds = oppCards.slice(Math.min(myCards.length * 2, oppCards.length)); const oppBestAfter = oppAfterRounds.length > 0 ? oppAfterRounds[0] : 0; // Partner keeps their highest cards (plays lowest to follow our leads) const partTopAfter = partCards[0]; // partner's best (they keep it) if (partTopAfter > oppBestAfter) { const partRemaining = partCards.length - myCards.length; if (partRemaining > 0) { discardSetupSuits[s] = 20 + partRemaining * 12; } } } // --- Plan 2: Long suit runner in partner's hand --- // If partner has 5+ cards headed by honors, we need entries to get there. const entryBoostSuits = {}; for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const partCards = (partHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (partCards.length < 5 || partCards[0] < 12) continue; let oppInSuit = 0; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) oppInSuit += (hands[p][s] || []).length; } const myInSuit = (myHand[s] || []).length; const roundsToExhaust = Math.ceil(oppInSuit / 2); const extraWinners = Math.max(0, partCards.length - Math.max(roundsToExhaust, myInSuit)); if (extraWinners > 0) { for (const es of SUIT_ORDER) { if (es === s || es === trumpSuit) continue; const partInEs = (partHand[es] || []).map(r => CARD_RANK[r]); if (partInEs.some(r => r >= 13)) { if (!entryBoostSuits[es]) entryBoostSuits[es] = 0; entryBoostSuits[es] += extraWinners * 5; } } } } // ============================================================ // A7: DECLARER PLANNING — Phase 4+5 Enhancements // ============================================================ // --- Plan 3: SHORT HAND FIRST (trumps) --- // When drawing trumps, lead from the shorter trump hand to avoid blocking. // e.g. dummy has xx, declarer has AKQxx → lead trump from dummy's side let shortTrumpHand = null; // which hand (playerPos) has fewer trumps let longTrumpHand = null; if (trumpSuit) { const myTrumps = (myHand[trumpSuit] || []).length; const partTrumps = (partHand[trumpSuit] || []).length; if (myTrumps < partTrumps) { shortTrumpHand = playerPos; longTrumpHand = partPos; } else if (partTrumps < myTrumps) { shortTrumpHand = partPos; longTrumpHand = playerPos; } // If equal, no preference } // --- Plan 4: ENTRY TRACKING --- // Count entries to each hand (Aces, Kings, and masters in side suits) const entries = { [playerPos]: 0, [partPos]: 0 }; for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const myCards = (myHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const partCards = (partHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); // Count sure entries (cards that will definitely win) if (myCards.length > 0 && myCards[0] >= 14) entries[playerPos]++; else if (myCards.length > 0 && isMaster({ suit: s, rank: (myHand[s] || [])[0] }, hands, playerPos)) entries[playerPos]++; if (partCards.length > 0 && partCards[0] >= 14) entries[partPos]++; else if (partCards.length > 0 && isMaster({ suit: s, rank: (partHand[s] || [])[0] }, hands, partPos)) entries[partPos]++; } // --- Plan 5: NT HOLDUP detection --- // In NT: if opponents have led a suit and we hold Ace or King stopper, // consider ducking early rounds to exhaust one defender's holding let holdupSuit = null; if (!trumpSuit && state.trickHistory && state.trickHistory.length >= 1) { const firstTrick = state.trickHistory[0]; if (firstTrick && firstTrick.trick && firstTrick.trick.length >= 1) { const openingLeadSuit = firstTrick.trick[0].suit; const myInSuit = (myHand[openingLeadSuit] || []).map(r => CARD_RANK[r]); const partInSuit = (partHand[openingLeadSuit] || []).map(r => CARD_RANK[r]); const allInSuit = [...myInSuit, ...partInSuit]; const haveStopper = allInSuit.some(r => r >= 13); // K+ const combinedLen = allInSuit.length; if (haveStopper && combinedLen <= 5) { holdupSuit = openingLeadSuit; } } } // --- Plan 5b: NT WINNER COUNT and DEVELOPMENT ANALYSIS --- // Count top tricks (cashable now) and development potential per suit. // "Count your winners in NT" — the fundamental declarer planning principle. // // Top trick = a round we can win without losing the lead. // Development = extra tricks available after giving up N losers. // Deficit = tricks needed for contract minus top tricks = how many we must develop. // Best development suit = most extra tricks for fewest losers. const ntPlan = { topTotal: 0, deficit: 0, suits: {}, bestDevSuit: null, bestDevNet: 0 }; if (!trumpSuit) { const tricksNeeded = (contractInfo?.level || 1) + 6; // e.g. 3NT = 9 for (const s of SUIT_ORDER) { const decCards = (decHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const dumCards = (dumHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const ourCards = [...decCards, ...dumCards].sort((a, b) => b - a); // Track each defender's cards separately (critical for accurate trick counting) const defenders = POS.filter(p => p !== declarerPos && p !== dummyPos); let defA = (hands[defenders[0]][s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); let defB = (hands[defenders[1]][s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (ourCards.length === 0) { ntPlan.suits[s] = { topTricks: 0, totalTricks: 0, losers: 0, devNet: 0, ourLen: 0 }; continue; } // Count top tricks: rounds we win from the top against best defense // Each round: each defender who has cards follows with their lowest (holds back highs) let topTricks = 0; let ourWork = [...ourCards]; let dA = [...defA], dB = [...defB]; // mutable copies while (ourWork.length > 0) { const aTop = dA.length > 0 ? dA[0] : -1; const bTop = dB.length > 0 ? dB[0] : -1; const oppTop = Math.max(aTop, bTop); if (oppTop < 0) { // Both defenders exhausted — remaining cards all win topTricks += ourWork.length; ourWork = []; break; } if (ourWork[0] > oppTop) { topTricks++; ourWork.shift(); // Each defender follows with lowest card (optimal defense: hold back highs) if (dA.length > 0) dA.pop(); if (dB.length > 0) dB.pop(); } else { break; // Our top card doesn't beat their best — must lose to develop } } // Count development: after losing to blocking honors, how many more can we win? let totalTricks = topTricks; let losers = 0; while (ourWork.length > 0 && (dA.length > 0 || dB.length > 0)) { const aTop = dA.length > 0 ? dA[0] : -1; const bTop = dB.length > 0 ? dB[0] : -1; const oppTop = Math.max(aTop, bTop); if (oppTop < 0) break; if (ourWork[0] > oppTop) { // We can win again after previous losses cleared blockers totalTricks++; ourWork.shift(); if (dA.length > 0) dA.pop(); if (dB.length > 0) dB.pop(); } else { // Must lose this round — their top card takes the trick losers++; // Remove the winning defender's top card if (aTop >= bTop && dA.length > 0) dA.shift(); else if (dB.length > 0) dB.shift(); // Partner of winner follows with lowest if able if (aTop >= bTop) { if (dB.length > 0) dB.pop(); } else { if (dA.length > 0) dA.pop(); } // Our side also loses a card from the shorter hand ourWork.pop(); } } // If opponents ran out during development if (dA.length === 0 && dB.length === 0 && ourWork.length > 0) { totalTricks += ourWork.length; } const devNet = totalTricks - topTricks; ntPlan.suits[s] = { topTricks, totalTricks, losers, devNet, ourLen: ourCards.length }; ntPlan.topTotal += topTricks; // Track best development suit: most net tricks per loser // Prefer suits where we get the most extra tricks for the fewest losers if (devNet > 0 && losers >= 0) { // Efficiency = extra tricks gained. Prefer more tricks; break ties by fewer losers. const isBetter = devNet > ntPlan.bestDevNet || (devNet === ntPlan.bestDevNet && losers < (ntPlan.suits[ntPlan.bestDevSuit]?.losers ?? 99)); if (isBetter) { ntPlan.bestDevSuit = s; ntPlan.bestDevNet = devNet; } } } ntPlan.deficit = tricksNeeded - ntPlan.topTotal; // If best dev suit needs entries to partner, check if we have them if (ntPlan.bestDevSuit) { const ds = ntPlan.bestDevSuit; const myLen = (myHand[ds] || []).length; const partLen = (partHand[ds] || []).length; // Mark which hand holds the long end of the development suit ntPlan.devInPartner = partLen > myLen; ntPlan.devInMe = myLen > partLen; } } // --- Plan 6: LOSER-DRIVEN PLANNING (suit contracts) --- // "Count your losers in suit contracts" — the fundamental planning principle. // // Step 1: Count losers per suit (max 3 per suit, use shorter holding). // Step 2: Compute excess = totalLosers - affordable losers. // Step 3: Identify elimination methods: // a) Ruff in dummy (dummy is short in a side suit + has trumps) // b) Discard on extra winners (long suit with more tops than the other hand) // Step 4: Determine trump-drawing urgency: // - Need ruffs → DELAY drawing trumps (preserve dummy's trumps) // - No ruffs needed → DRAW trumps early (prevent opponent ruffs) const suitPlan = { totalLosers: 0, excessLosers: 0, affordable: 0, suitLosers: {}, // suit → number of losers in that suit ruffSuits: [], // suits where we can ruff in the short-trump hand discardSuits: [], // suits providing extra winners for discards discardCount: 0, // total discards available ruffCount: 0, // total ruffs available delayTrumps: false, // true when we need ruffs before drawing trumps drawTrumps: false, // true when we should draw trumps promptly }; if (trumpSuit) { const contractLevel = contractInfo?.level || 1; suitPlan.affordable = 13 - (contractLevel + 6); // e.g. 4H: can afford 3 losers const decTrumps = (decHand[trumpSuit] || []).length; const dumTrumps = (dumHand[trumpSuit] || []).length; let oppTrumps = 0; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) oppTrumps += (hands[p][trumpSuit] || []).length; } // --- Count losers per suit --- for (const s of SUIT_ORDER) { const decCards = (decHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const dumCards = (dumHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (decCards.length === 0 && dumCards.length === 0) { suitPlan.suitLosers[s] = 0; continue; } const shortLen = Math.min(decCards.length, dumCards.length, 3); const combined = [...decCards, ...dumCards].sort((a, b) => b - a); let sLosers = 0; for (let i = 0; i < shortLen; i++) { if (combined[i] < 14 - i) sLosers++; } suitPlan.suitLosers[s] = sLosers; suitPlan.totalLosers += sLosers; } suitPlan.excessLosers = Math.max(0, suitPlan.totalLosers - suitPlan.affordable); // --- Identify ruff opportunities --- // A ruff eliminates a loser when one hand is short in a side suit and has trumps. // Typically "ruff in dummy" (shorter trump hand) is most valuable because it // creates an extra trick (long-hand trumps still draw opponents' trumps). for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const decLen = (decHand[s] || []).length; const dumLen = (dumHand[s] || []).length; // Ruff in dummy: declarer has length, dummy is short, dummy has trumps // Note: don't require suitLosers > 0 — when dummy is void, suit losers = 0 // by definition, but the ruff still gains a trick (dummy trump becomes productive). if (decLen >= 2 && dumLen <= 1 && dumTrumps > 0) { const ruffsAvail = dumLen === 0 ? Math.min(dumTrumps, decLen) : Math.min(dumTrumps, 1); suitPlan.ruffSuits.push({ suit: s, hand: 'dummy', ruffs: ruffsAvail, dumLen }); suitPlan.ruffCount += ruffsAvail; } // Ruff in declarer: dummy has length, declarer is short // (less common — usually only if declarer has the shorter trumps, i.e. dummy has more) if (dumLen >= 2 && decLen <= 1 && decTrumps > 0 && dumTrumps > decTrumps) { const ruffsAvail = decLen === 0 ? Math.min(decTrumps, 1) : Math.min(decTrumps, 1); suitPlan.ruffSuits.push({ suit: s, hand: 'declarer', ruffs: ruffsAvail, decLen }); suitPlan.ruffCount += ruffsAvail; } } // --- Identify discard opportunities --- // Extra winners = suits where one hand has more tops than the other has cards. // After cashing, the extra winners let the other hand discard losers. // (Already computed in discardSetupSuits, but let's count the actual discards) for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const decCards = (decHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const dumCards = (dumHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); // Extra winners in declarer's hand (dummy discards) if (decCards.length > dumCards.length) { let oppBest = 0; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) { const oCards = (hands[p][s] || []).map(r => CARD_RANK[r]); if (oCards.length > 0) oppBest = Math.max(oppBest, Math.max(...oCards)); } } // Count how many extra winners after exhausting the short hand let extraWins = 0; const sorted = [...decCards].sort((a, b) => b - a); for (let i = dumCards.length; i < sorted.length; i++) { if (sorted[i] > oppBest) extraWins++; else break; } if (extraWins > 0) { suitPlan.discardSuits.push({ suit: s, from: 'declarer', discards: extraWins }); suitPlan.discardCount += extraWins; } } // Extra winners in dummy's hand (declarer discards) if (dumCards.length > decCards.length) { let oppBest = 0; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) { const oCards = (hands[p][s] || []).map(r => CARD_RANK[r]); if (oCards.length > 0) oppBest = Math.max(oppBest, Math.max(...oCards)); } } let extraWins = 0; const sorted = [...dumCards].sort((a, b) => b - a); for (let i = decCards.length; i < sorted.length; i++) { if (sorted[i] > oppBest) extraWins++; else break; } if (extraWins > 0) { suitPlan.discardSuits.push({ suit: s, from: 'dummy', discards: extraWins }); suitPlan.discardCount += extraWins; } } } // --- Trump drawing urgency --- if (suitPlan.excessLosers > 0 && suitPlan.ruffCount > 0) { // Need ruffs to eliminate losers → DELAY drawing trumps suitPlan.delayTrumps = true; } else if (oppTrumps > 0 && suitPlan.ruffCount === 0) { // No ruffs needed, opponents have trumps → DRAW them suitPlan.drawTrumps = true; } else if (suitPlan.excessLosers > 0 && suitPlan.discardCount > 0 && suitPlan.ruffCount === 0) { // Need discards, not ruffs → draw trumps first (safe), then cash discard suit suitPlan.drawTrumps = true; } // If excess=0: moderate — draw trumps when convenient } // --- Plan 7: ENDPLAY / THROW-IN DETECTION --- // Detect positions where we can throw a defender in so they must: // a) Lead into our tenace (e.g. lead away from Kx into our AQ), or // b) Give a ruff-and-discard (lead a suit where both we and dummy are void) // // Requirements for a throw-in: // 1. We have a tenace in some suit (AQ, KJ, etc.) or can get a ruff-discard // 2. A defender can be given the lead // 3. That defender has no "safe" exit (every suit they lead helps us) // 4. We've stripped their safe exits by cashing/ruffing those suits first let endplaySuit = null; // suit to lead for the throw-in let endplayScore = 0; // bonus score for the throw-in lead let eliminationSuits = []; // suits to strip before the endplay const cardsLeft = SUIT_ORDER.reduce((n, s) => n + (myHand[s] || []).length, 0); if (cardsLeft <= 8) { // Only look for endplays in the later play // Identify our tenace suits (suits where a defender leading helps us) const tenaceSuits = []; for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const decCards = (decHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const dumCards = (dumHand[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const allCards = [...decCards, ...dumCards].sort((a, b) => b - a); if (allCards.length < 2) continue; // AQ tenace (missing K) if (allCards.includes(14) && allCards.includes(12) && !allCards.includes(13)) { tenaceSuits.push(s); } // KJ tenace (missing Q) if (allCards.includes(13) && allCards.includes(11) && !allCards.includes(12)) { tenaceSuits.push(s); } // Qx tenace (if led into, Q wins) if (allCards[0] === 12 && allCards.length >= 2) { tenaceSuits.push(s); } } // Check for ruff-and-discard possibility (both hands void in a side suit) const ruffDiscardPossible = trumpSuit && SUIT_ORDER.some(s => { if (s === trumpSuit) return false; return (myHand[s] || []).length === 0 && (partHand[s] || []).length === 0; }); if (tenaceSuits.length > 0 || ruffDiscardPossible) { // For each defender, check if they have no safe exit for (const defPos of POS) { if (defPos === declarerPos || defPos === dummyPos) continue; const defHand = hands[defPos]; let unsafeExits = 0; let safeExits = 0; let throwInCards = []; // suits we can lead to give them the lead for (const s of SUIT_ORDER) { const defLen = (defHand[s] || []).length; if (defLen === 0) continue; if (s === trumpSuit) { // Trump exit is usually safe for them safeExits++; continue; } const isTenace = tenaceSuits.includes(s); const weVoid = (myHand[s] || []).length === 0 && (partHand[s] || []).length === 0; if (isTenace || weVoid) { unsafeExits++; // leading this suit helps us } else { safeExits++; } } // Can we give this defender the lead? for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const defLen = (defHand[s] || []).length; const myLen = (myHand[s] || []).length; if (defLen > 0 && myLen > 0) { // Check if they'd win: we lead low, they have a higher card const myLow = Math.min(...(myHand[s] || []).map(r => CARD_RANK[r])); const defHigh = Math.max(...(defHand[s] || []).map(r => CARD_RANK[r])); if (defHigh > myLow) { throwInCards.push(s); } } } if (unsafeExits > 0 && safeExits === 0 && throwInCards.length > 0) { // This defender is endplayable! endplaySuit = throwInCards[0]; endplayScore = 40; // strong bonus // Mark suits to strip: any suit where defender still has safe cards // (already stripped if safeExits === 0, but help identify order) } else if (unsafeExits > 0 && safeExits <= 1 && throwInCards.length > 0) { // Almost endplayable — strip the remaining safe exit first for (const s of SUIT_ORDER) { if (s === trumpSuit) continue; const defLen = (defHand[s] || []).length; if (defLen > 0 && !tenaceSuits.includes(s)) { const weVoid = (myHand[s] || []).length === 0 && (partHand[s] || []).length === 0; if (!weVoid) { eliminationSuits.push(s); } } } if (eliminationSuits.length > 0) { endplayScore = 20; // moderate bonus for elimination leads } } } } } // ============================================================ // SCORING LOOP // ============================================================ let bestCard = null, bestScore = -999; for (const card of legal) { const suit = card.suit; const rankVal = CARD_RANK[card.rank]; const decLen = (decHand[suit] || []).length; const dumLen = (dumHand[suit] || []).length; const combinedLen = decLen + dumLen; const decRanks = (decHand[suit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const dumRanks = (dumHand[suit] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const allRanks = [...decRanks, ...dumRanks].sort((a, b) => b - a); let score = 0; // Count opponents' cards let oppCount = 0; for (const p of POS) { if (p !== declarerPos && p !== dummyPos) oppCount += (hands[p][suit] || []).length; } if (trumpSuit) { // === SUIT CONTRACT: Loser-driven planning === // Core: "Count your losers." excessLosers drives urgency. // delayTrumps → preserve dummy trumps for ruffs // drawTrumps → pull opponents' trumps before they ruff our winners const isRuffSuit = suitPlan.ruffSuits.some(r => r.suit === suit); const isDiscardSuit = suitPlan.discardSuits.some(d => d.suit === suit); if (suit === trumpSuit) { if (oppCount === 0) { // No opposing trumps — drawing trumps is pointless score -= 15; } else if (suitPlan.delayTrumps) { // DELAY: We need dummy's trumps for ruffs. // Drawing trumps removes dummy's ruffs — penalize heavily. score -= 12; // Exception: if opponents have LOTS of trumps (4+), we may still need // to draw some to avoid overruffs if (oppCount >= 4) score += 8; } else if (suitPlan.drawTrumps) { // DRAW: No ruffs needed, pull their trumps before they ruff us. // Scale bonus with how many opposing trumps remain — more = more urgent. const drawBase = 18 + oppCount * 3; // 6 opp trumps → 36 score += drawBase; if (rankVal >= 13) score += 3; } else { // Moderate: draw trumps at a reasonable pace if (oppCount >= 3) score += 18; else if (oppCount >= 2) score += 14; else score += 8; if (rankVal >= 13) score += 3; } // SHORT HAND FIRST still applies when drawing trumps if (!suitPlan.delayTrumps && oppCount > 0) { if (shortTrumpHand === playerPos) { score += 8; } if (longTrumpHand === playerPos && shortTrumpHand) { const partTrumpRanks = (partHand[trumpSuit] || []).map(r => CARD_RANK[r]); if (partTrumpRanks.some(r => r >= 12) && rankVal <= 10) { score += 6; } } } } else { // ---- SIDE SUIT ---- const myLen = (hands[playerPos][suit] || []).length; const partHd = playerPos === declarerPos ? dummyPos : declarerPos; const partLen = (hands[partHd][suit] || []).length; const myTrumps = (hands[playerPos][trumpSuit] || []).length; const partTrumps = (hands[partHd][trumpSuit] || []).length; const iAmShortTrumpHand = myTrumps <= partTrumps; const partIsShortTrumpHand = partTrumps <= myTrumps; const partRanks = playerPos === declarerPos ? dumRanks : decRanks; const myRanks = playerPos === declarerPos ? decRanks : dumRanks; // TEMPO COST: When drawTrumps is urgent, penalize side-suit leads // (every side-suit lead is a lost opportunity to pull an opposing trump) if (suitPlan.drawTrumps && !isRuffSuit && !isDiscardSuit) { score -= 8; } // ---- RUFF SUITS: Lead this suit to get a ruff ---- if (isRuffSuit && suitPlan.excessLosers > 0) { const ruffInfo = suitPlan.ruffSuits.find(r => r.suit === suit); // Big bonus — this directly eliminates a loser score += 30 + suitPlan.excessLosers * 5; // If dummy is already void, lead ANY card in this suit for an immediate ruff if (ruffInfo && ruffInfo.hand === 'dummy' && ruffInfo.dumLen === 0) { score += 10; // immediate ruff available } } // ---- DISCARD SUITS: Cash winners to discard losers ---- if (isDiscardSuit && suitPlan.excessLosers > 0) { const discInfo = suitPlan.discardSuits.find(d => d.suit === suit); if (discInfo) { if (discInfo.from === 'dummy' && playerPos === declarerPos) { // Winners are in DUMMY — lead toward them (even low cards cross to dummy) score += 25 + discInfo.discards * 6; } else if (discInfo.from === 'declarer' && playerPos === dummyPos) { // Winners are in DECLARER — lead toward them from dummy side score += 25 + discInfo.discards * 6; } else if (isMaster(card, hands, playerPos)) { // We hold the winners — cash them score += 25 + discInfo.discards * 6; } else if (rankVal >= 12) { score += 15; // honor in discard suit — still useful } } } // ---- GENERIC SHORTNESS (when not already a ruff suit) ---- if (!isRuffSuit) { if (iAmShortTrumpHand && myLen === 1 && myTrumps > 0) { const singletonCard = (hands[playerPos][suit] || [])[0]; const isSingletonMaster = singletonCard && isMaster({ suit, rank: singletonCard }, hands, playerPos); if (!isSingletonMaster) score += 25; } else if (iAmShortTrumpHand && myLen === 2 && myTrumps > 0) { score += 12; } if (partIsShortTrumpHand && partLen === 1 && partTrumps > 0) { score += 25; } else if (partIsShortTrumpHand && partLen === 2 && partTrumps > 0) { score += 12; } if (partIsShortTrumpHand && partLen === 0 && partTrumps > 0 && myLen > 0) { score += 30; } } // ---- LONG SUIT DEVELOPMENT (side suits with combined length) ---- // Suppress when Plan 6 already scores this suit as a discard suit const combinedHighCards = allRanks.filter(r => r >= 12).length; if (combinedLen >= 5 && combinedHighCards >= 1 && !isDiscardSuit) { score += (combinedLen - 4) * 4; if (oppCount <= 2) score += 8; } // ---- MASTERS ---- if (isMaster(card, hands, playerPos)) { score += 15; if (allRanks.length >= 2 && allRanks[0] >= 13 && allRanks[1] >= 12) score += 5; } // ---- LOSER URGENCY: excess losers drive aggressive play ---- if (suitPlan.excessLosers > 0) { // Cash masters in non-ruff suits quickly before opponents establish theirs if (isMaster(card, hands, playerPos) && !isRuffSuit) { score += 8 + suitPlan.excessLosers * 3; } } else if (suitPlan.excessLosers === 0 && suitPlan.totalLosers <= suitPlan.affordable) { // No excess — we can afford our losers. Play more cautiously. // Avoid leading unsupported honors that might create extra losers. if (isHonor(card.rank) && !isMaster(card, hands, playerPos) && myLen >= 2) { score -= 5; } } // ---- TENACE HANDLING ---- const hasAQ = allRanks.includes(14) && allRanks.includes(12) && !allRanks.includes(13); const hasKJ = allRanks.includes(13) && allRanks.includes(11) && !allRanks.includes(12); if (hasAQ || hasKJ) { const tenaceInDec = decRanks.includes(14) && decRanks.includes(12) || decRanks.includes(13) && decRanks.includes(11); const tenaceInDum = dumRanks.includes(14) && dumRanks.includes(12) || dumRanks.includes(13) && dumRanks.includes(11); if ((tenaceInDec && playerPos === dummyPos) || (tenaceInDum && playerPos === declarerPos)) { score += 10; } else if ((tenaceInDec && playerPos === declarerPos) || (tenaceInDum && playerPos === dummyPos)) { score -= 12; } } // ---- AQ/KJ CARD PREFERENCE: lead the lower honor, not the top ---- // When we hold AQ in our hand and dummy has supporting honors (J/T), // prefer leading Q over A. The Q forces a cover or wins; A is our safety net. // Same for KJ: lead J, keep K. if (myRanks.includes(14) && myRanks.includes(12) && !myRanks.includes(13)) { // We hold AQ (missing K) in our hand const dummyHasSupport = partRanks.some(r => r >= 10 && r <= 11); // J or T in dummy if (dummyHasSupport || partRanks.length >= 3) { if (rankVal === 14) score -= 18; // Don't lead A — save it if (rankVal === 12) score += 12; // Lead Q — forces the issue } } if (myRanks.includes(13) && myRanks.includes(11) && !myRanks.includes(12)) { // We hold KJ (missing Q) in our hand const dummyHasSupport = partRanks.some(r => r >= 10); if (dummyHasSupport || partRanks.length >= 3) { if (rankVal === 13) score -= 18; // Don't lead K — save it if (rankVal === 11) score += 12; // Lead J — finesse } } // ---- LEAD TOWARD PARTNER'S HONORS ---- if (partRanks.length > 0 && partRanks[0] >= 12 && myRanks.length > 0 && myRanks[0] <= 10) { if (rankVal <= 10) score += 6; } // ---- EXISTING PLAN BONUSES ---- // A6: Discard setup (cash tops in short holding) // Suppress when Plan 6 already handles this suit as a discard suit (avoid double-dip) if (discardSetupSuits[suit] && rankVal >= 13 && !isDiscardSuit) { const dsBonus = discardSetupSuits[suit]; if (suitPlan.excessLosers > 0) { score += dsBonus; } else if (suitPlan.drawTrumps) { score += Math.floor(dsBonus * 0.3); } else { score += Math.floor(dsBonus * 0.6); } } // A6: Entry boost — lead low to partner's entry when they have a long runner if (entryBoostSuits[suit] && rankVal <= 10 && !isMaster(card, hands, playerPos)) { score += entryBoostSuits[suit]; } // Entry management — lead toward entryless partner who has winners if (entries[partPos] === 0 && entries[playerPos] > 0) { if (partRanks.length > 0 && partRanks[0] >= 12 && rankVal <= 10) { score += 12; // meaningful bonus to compete with other options } } } } else { // === NO-TRUMP: Winner-count driven planning === // Core principle: "Count your winners in NT." // deficit > 0 → must develop extra tricks → prioritize development suit // deficit <= 0 → just cash winners → avoid risky development const sp = ntPlan.suits[suit] || {}; const isBestDev = suit === ntPlan.bestDevSuit; const myLen = (myHand[suit] || []).length; const partLen = (partHand[suit] || []).length; if (ntPlan.deficit <= 0) { // ---- ENOUGH TOP TRICKS: Just cash winners, don't develop ---- // Cash masters — free tricks if (isMaster(card, hands, playerPos)) { score += 30; // Lone masters (short suits): cash first — no blockage risk if (combinedLen <= 2) score += 15; } // Mild penalty for leading non-masters in suits we don't need to develop if (!isMaster(card, hands, playerPos) && sp.topTricks === 0) { score -= 8; // don't waste tempo on suits with no tops } } else { // ---- NEED TO DEVELOP: Find tricks to close the deficit ---- if (isBestDev) { // THIS is the suit we should be developing. // Lead it early — the sooner we lose our losers, the sooner we cash winners. score += 25 + sp.devNet * 8; // big bonus scaled by how many tricks we gain // Within the dev suit: lead low to develop, don't cash the top prematurely // (unless the top IS the only trick — e.g. Ax opposite xxx, cash A then duck) if (sp.topTricks > 0 && sp.losers > 0) { // We have both tops and losers — lead low first to knock out their stoppers if (!isMaster(card, hands, playerPos) && rankVal <= 10) { score += 10; // development lead — give up the loser early } // Only cash the top if it's a short holding and we need to unblock if (isMaster(card, hands, playerPos) && myLen <= 2 && partLen > myLen) { score += 12; // unblock: cash our short honor then lead to partner's length } } else if (sp.topTricks === 0 && sp.losers > 0) { // No tops at all — lead low to start developing if (rankVal <= 10) score += 8; } } else if (sp.topTricks > 0 && sp.devNet === 0) { // Non-development suit WITH top tricks: cash these first // (they're free tricks that bring us closer without risk) if (isMaster(card, hands, playerPos)) { score += 20; // Cash short-suit masters FIRST to avoid blockage if (combinedLen <= 2) score += 12; } } else if (sp.topTricks === 0 && sp.devNet === 0) { // Worthless suit — no tricks here, don't lead it score -= 10; } // Penalty: don't develop a NON-best suit when a better one exists // (wasting tempo giving up losers in the wrong suit) if (!isBestDev && sp.devNet > 0 && sp.losers > 0 && ntPlan.bestDevSuit) { score -= 10; // wrong suit to develop } } // ---- ENTRY MANAGEMENT (applies regardless of deficit) ---- if (partLen > myLen && partLen >= 4) { // Partner holds the length — lead low to preserve communication if (rankVal <= 10 && !isMaster(card, hands, playerPos)) { score += 6; } // Unreachable suit: partner has length but no entries anywhere if (entries[partPos] === 0 && entries[playerPos] === 0) { score -= 12; } } // Development suit is in partner's hand — preserve entries to partner if (ntPlan.devInPartner && suit !== ntPlan.bestDevSuit) { // Don't cash partner's entry card in a side suit if we need it to reach dev suit if (isMaster(card, hands, playerPos) && entries[partPos] <= 1) { const partHasEntry = (partHand[suit] || []).some(r => CARD_RANK[r] >= 13); if (partHasEntry) { score -= 8; // preserve partner's entry for the development suit } } } // ---- HOLDUP AWARENESS ---- if (holdupSuit && suit === holdupSuit && !isMaster(card, hands, playerPos)) { score -= 15; // don't lead their suit back to them } // ---- TENACE HANDLING ---- const hasAQ = allRanks.includes(14) && allRanks.includes(12) && !allRanks.includes(13); const hasKJ = allRanks.includes(13) && allRanks.includes(11) && !allRanks.includes(12); if (hasAQ || hasKJ) { const tenaceInDec = decRanks.includes(14) && decRanks.includes(12) || decRanks.includes(13) && decRanks.includes(11); const tenaceInDum = dumRanks.includes(14) && dumRanks.includes(12) || dumRanks.includes(13) && dumRanks.includes(11); // Lead TOWARD the tenace (from the other hand) if ((tenaceInDec && playerPos === dummyPos) || (tenaceInDum && playerPos === declarerPos)) { score += 10; // DON'T lead away from our tenace } else if ((tenaceInDec && playerPos === declarerPos) || (tenaceInDum && playerPos === dummyPos)) { score -= 12; } } // ---- EXISTING PLAN BONUSES ---- // A6: Discard setup — cash tops in short holding to create void // Reduce when deficit > 0 — ntPlan already handles suit selection for development if (discardSetupSuits[suit] && rankVal >= 13) { if (ntPlan.deficit <= 0) { score += discardSetupSuits[suit]; // full bonus — just cashing winners } else { // When developing, Plan 1 bonus could overwhelm development suit choice. // Only give partial credit — ntPlan is the primary driver. score += Math.floor(discardSetupSuits[suit] * 0.4); } } // A6: Entry boost — lead low to partner's entry when they have a runner if (entryBoostSuits[suit] && rankVal <= 10 && !isMaster(card, hands, playerPos)) { score += entryBoostSuits[suit]; } } // A7: ENDPLAY / THROW-IN scoring if (endplaySuit && suit === endplaySuit) { // This is the throw-in suit — lead low to give defender the lead if (rankVal <= 10) score += endplayScore; } if (eliminationSuits.length > 0 && eliminationSuits.includes(suit)) { // This suit needs to be stripped before the endplay // Cash our winners or ruff to eliminate defender's safe exit if (isMaster(card, hands, playerPos)) score += 18; else if (rankVal <= 10) score += 12; // lead low to strip } if (score > bestScore) { bestScore = score; bestCard = card; } } return bestCard || legal[0]; } // ====================================== // FINESSE DETECTION (Eight Ever, Nine Never) // ====================================== // ====================================== // FINESSE DETECTION (Eight Ever, Nine Never) // ====================================== function detectFinesse(legal, hand, trick, trumpSuit, playerPos, hands, state) { if (!state.isDeclarer || trick.length === 0) return null; const { contractInfo } = state; const declarerPos = contractInfo.declarer; const dummyPos = contractInfo.dummy; const leadSuit = trick[0].suit; const following = legal.filter(c => c.suit === leadSuit); if (following.length < 2) return null; const decCards = (hands[declarerPos][leadSuit] || []).map(r => CARD_RANK[r]); const dumCards = (hands[dummyPos][leadSuit] || []).map(r => CARD_RANK[r]); const combined = [...decCards, ...dumCards].sort((a, b) => b - a); const totalInSuit = combined.length; const hasQ = combined.includes(12); const hasA = combined.includes(14); const hasK = combined.includes(13); const hasJ = combined.includes(11); const hasT = combined.includes(10); // Eight Ever: AKJ vs missing Q, 8 cards → finesse (play J) if (!hasQ && hasA && hasK && hasJ && totalInSuit === 8) { const myCards = following.map(c => CARD_RANK[c.rank]); if (myCards.includes(11)) { // We have the J — play it (finesse) return following.find(c => CARD_RANK[c.rank] === 11); } if (myCards.includes(14) && !myCards.includes(11)) { // We have A but not J — play low to let partner's J win the finesse following.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); return following[0]; } } // Nine Never: AK vs missing Q, 9+ cards → play for the drop if (!hasQ && hasA && hasK && totalInSuit >= 9) { // Cash the top card const myCards = following.map(c => CARD_RANK[c.rank]); if (myCards.includes(14)) return following.find(c => CARD_RANK[c.rank] === 14); if (myCards.includes(13)) return following.find(c => CARD_RANK[c.rank] === 13); } // Simple finesse: we have AQ (missing K), lead was toward us // If we're in second seat with AQ and a low card was led, finesse with Q if (trick.length === 1) { const myCards = following.map(c => CARD_RANK[c.rank]).sort((a, b) => b - a); if (myCards.includes(14) && myCards.includes(12) && !myCards.includes(13)) { const leadRank = CARD_RANK[trick[0].rank]; if (leadRank <= 10 && state.isDeclarer) { // Low card led toward our AQ — finesse with Q return following.find(c => CARD_RANK[c.rank] === 12); } } // KJ finesse: play J when low card led toward KJ if (myCards.includes(13) && myCards.includes(11) && !myCards.includes(12)) { const leadRank = CARD_RANK[trick[0].rank]; if (leadRank <= 10 && state.isDeclarer) { return following.find(c => CARD_RANK[c.rank] === 11); } } } return null; } // ====================================== // ENDGAME SEARCH (bounded, for tiebreaking only) // ====================================== let nodeCount = 0; let startTime = 0; let timeLimit = 0; let timedOut = false; // ====================================== // TRANSPOSITION TABLE // ====================================== // Key = compact position hash. Value = { value, depth, flag }. // flag: 'exact' | 'lower' (alpha cutoff) | 'upper' (beta cutoff) let ttable = new Map(); const TT_MAX = 100000; // max entries before clearing function posHash(hands, trick, next) { // Build a compact string key from the position // Format: cards-per-hand + trick-state + next-player let key = next; for (const p of POS) { for (const s of SUIT_ORDER) { const cards = hands[p][s]; if (cards && cards.length > 0) { key += p + s + cards.join(''); } } } if (trick.length > 0) { key += 'T'; for (const c of trick) key += c.suit + c.rank + c.position; } return key; } // ====================================== // QUICK TRICKS COUNTING // ====================================== // Count guaranteed tricks for a side (NS or EW) without losing the lead. // Used for pruning: if wonTricks + quickTricks >= target, position is proven. function countQuickTricks(hands, trumpSuit) { let nsQT = 0, ewQT = 0; for (const s of SUIT_ORDER) { // Gather all cards for each side, sorted descending const nsCards = [ ...(hands.N[s] || []).map(r => CARD_RANK[r]), ...(hands.S[s] || []).map(r => CARD_RANK[r]) ].sort((a, b) => b - a); const ewCards = [ ...(hands.E[s] || []).map(r => CARD_RANK[r]), ...(hands.W[s] || []).map(r => CARD_RANK[r]) ].sort((a, b) => b - a); if (nsCards.length === 0 && ewCards.length === 0) continue; // In trump suit: quick tricks are limited by ruffs (opponent void + trumps) // For simplicity, count top tricks only when neither opponent is void if (s === trumpSuit) { // Just count cascading tops: each top NS card beats corresponding EW card let qt = 0, nsW = [...nsCards], ewW = [...ewCards]; while (nsW.length > 0 && ewW.length > 0) { if (nsW[0] > ewW[0]) { qt++; nsW.shift(); ewW.shift(); } else break; } nsQT += qt; qt = 0; nsW = [...nsCards]; ewW = [...ewCards]; while (ewW.length > 0 && nsW.length > 0) { if (ewW[0] > nsW[0]) { qt++; ewW.shift(); nsW.shift(); } else break; } ewQT += qt; } else { // Side suit: quick tricks are capped by opponent ability to ruff const nsHasTrumps = trumpSuit && ( (hands.N[trumpSuit] || []).length > 0 || (hands.S[trumpSuit] || []).length > 0 ); const ewHasTrumps = trumpSuit && ( (hands.E[trumpSuit] || []).length > 0 || (hands.W[trumpSuit] || []).length > 0 ); // If opponent can ruff (one of them is void + has trumps), cap at 1 quick trick const ewCanRuff = trumpSuit && ( ((hands.E[s] || []).length === 0 && (hands.E[trumpSuit] || []).length > 0) || ((hands.W[s] || []).length === 0 && (hands.W[trumpSuit] || []).length > 0) ); const nsCanRuff = trumpSuit && ( ((hands.N[s] || []).length === 0 && (hands.N[trumpSuit] || []).length > 0) || ((hands.S[s] || []).length === 0 && (hands.S[trumpSuit] || []).length > 0) ); // Count cascading top tricks for NS let qt = 0, nsW = [...nsCards], ewW = [...ewCards]; while (nsW.length > 0) { if (ewW.length === 0) { qt += nsW.length; break; } if (nsW[0] > ewW[0]) { qt++; nsW.shift(); ewW.shift(); } else break; } nsQT += ewCanRuff ? Math.min(qt, 1) : qt; // Count for EW qt = 0; nsW = [...nsCards]; ewW = [...ewCards]; while (ewW.length > 0) { if (nsW.length === 0) { qt += ewW.length; break; } if (ewW[0] > nsW[0]) { qt++; ewW.shift(); nsW.shift(); } else break; } ewQT += nsCanRuff ? Math.min(qt, 1) : qt; } } return { nsQT, ewQT }; } function estimateSuitTricks(hands, s) { // Track each player's cards separately for accurate trick estimation const n = (hands.N[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const south = (hands.S[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const e = (hands.E[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); const w = (hands.W[s] || []).map(r => CARD_RANK[r]).sort((a, b) => b - a); if (n.length + south.length === 0 && e.length + w.length === 0) return { ns: 0, ew: 0 }; if (e.length + w.length === 0) return { ns: Math.max(n.length, south.length), ew: 0 }; if (n.length + south.length === 0) return { ns: 0, ew: Math.max(e.length, w.length) }; // Simulate trick play: each round, highest card from each hand that has cards // Side with the highest card wins the round let nW = [...n], sW = [...south], eW = [...e], wW = [...w]; let nsWins = 0, ewWins = 0; while ((nW.length + sW.length > 0) && (eW.length + wW.length > 0)) { const nsTop = Math.max(nW.length ? nW[0] : -1, sW.length ? sW[0] : -1); const ewTop = Math.max(eW.length ? eW[0] : -1, wW.length ? wW[0] : -1); if (nsTop > ewTop) { nsWins++; // NS plays the winning top; opponents play lowest if (nW.length && nW[0] === nsTop) nW.shift(); else sW.shift(); if (eW.length) eW.pop(); if (wW.length) wW.pop(); } else { ewWins++; if (eW.length && eW[0] === ewTop) eW.shift(); else wW.shift(); if (nW.length) nW.pop(); if (sW.length) sW.pop(); } } // Remaining cards win if opponents are out nsWins += nW.length + sW.length; ewWins += eW.length + wW.length; return { ns: nsWins, ew: ewWins }; } function evaluate(hands, trumpSuit, nsTricks, ewTricks) { const tc = totalCards(hands); if (tc === 0) return nsTricks; let nsEst = 0, ewEst = 0; for (const s of SUIT_ORDER) { const est = estimateSuitTricks(hands, s); nsEst += est.ns; ewEst += est.ew; if (s !== trumpSuit && trumpSuit) { for (const side of [['N','S'], ['E','W']]) { for (const p of side) { if ((hands[p][s] || []).length === 0 && (hands[p][trumpSuit] || []).length > 0) { // Check if the other side has cards in this suit to ruff const otherPlayers = side[0] === 'N' ? ['E','W'] : ['N','S']; const otherLen = (hands[otherPlayers[0]][s] || []).length + (hands[otherPlayers[1]][s] || []).length; if (otherLen > 0) { if (isNS(p)) nsEst += 0.4; else ewEst += 0.4; } break; } } } } } const tricksLeft = Math.ceil(tc / 4); nsEst = Math.min(nsEst, tricksLeft); ewEst = Math.min(ewEst, tricksLeft); const unclaimed = Math.max(0, tricksLeft - nsEst - ewEst); let nsCtrl = 0, ewCtrl = 0; for (const s of SUIT_ORDER) { for (const r of (hands.N[s] || [])) { if (CARD_RANK[r] >= 14) nsCtrl += 0.04; else if (CARD_RANK[r] >= 13) nsCtrl += 0.02; } for (const r of (hands.S[s] || [])) { if (CARD_RANK[r] >= 14) nsCtrl += 0.04; else if (CARD_RANK[r] >= 13) nsCtrl += 0.02; } for (const r of (hands.E[s] || [])) { if (CARD_RANK[r] >= 14) ewCtrl += 0.04; else if (CARD_RANK[r] >= 13) ewCtrl += 0.02; } for (const r of (hands.W[s] || [])) { if (CARD_RANK[r] >= 14) ewCtrl += 0.04; else if (CARD_RANK[r] >= 13) ewCtrl += 0.02; } } return nsTricks + nsEst + unclaimed * 0.5 + (nsCtrl - ewCtrl); } function orderMoves(cards, hands, trick, pos, trumpSuit) { if (cards.length <= 1) return cards; const leadSuit = trick.length > 0 ? trick[0].suit : null; if (trick.length === 0) { // Leading: try masters first (high value), then others by rank return cards.map(card => { let score = CARD_RANK[card.rank]; if (isMaster(card, hands, pos)) score += 2000; return { card, score }; }).sort((a, b) => b.score - a.score).map(x => x.card); } // Following: winners cheapest-first (cheapest sufficient win prunes best), // then losers cheapest-first (preserve high cards) const winVal = trick.length > 0 ? (() => { let best = cardVal(trick[0], leadSuit, trumpSuit); for (let i = 1; i < trick.length; i++) { const v = cardVal(trick[i], leadSuit, trumpSuit); if (v > best) best = v; } return best; })() : -1; const winners = [], losers = []; for (const c of cards) { if (cardVal(c, leadSuit, trumpSuit) > winVal) winners.push(c); else losers.push(c); } winners.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); // cheapest winner first losers.sort((a, b) => CARD_RANK[a.rank] - CARD_RANK[b.rank]); // cheapest loser first return [...winners, ...losers]; } function search(hands, trick, next, trump, nsT, ewT, alpha, beta, maxD, depth, nodeLimit) { nodeCount++; if ((nodeCount & 4095) === 0 && Date.now() - startTime > timeLimit) { timedOut = true; return nsT; } if (timedOut) return nsT; const tc = totalCards(hands); if (tc === 0) return nsT; if (maxD !== null && depth >= maxD) return evaluate(hands, trump, nsT, ewT); const leadSuit = trick.length === 0 ? null : trick[0].suit; let legal = getLegalCards(hands[next], leadSuit); if (legal.length === 0) return evaluate(hands, trump, nsT, ewT); // --- Quick tricks pruning --- // Only at trick boundaries (trick.length === 0) to avoid partial-trick confusion if (trick.length === 0 && tc >= 8) { const tricksLeft = Math.ceil(tc / 4); const { nsQT, ewQT } = countQuickTricks(hands, trump); // NS can guarantee at least nsT + nsQT tricks if (nsT + nsQT >= beta) return beta; // NS proven to reach beta → prune if (ewT + ewQT >= 13 - alpha + 1) return alpha; // EW proven → NS can't reach alpha // Tighten alpha/beta with quick trick bounds if (nsT + nsQT > alpha) alpha = Math.min(nsT + nsQT, 13); const ewMax = 13 - (ewT + ewQT); if (ewMax < beta) beta = Math.max(ewMax, 0); if (alpha >= beta) return alpha; } if (legal.length === 1) { const card = legal[0]; const nh = removeCard(hands, next, card); const nt = [...trick, { ...card, position: next }]; if (nt.length === 4) { const w = trickWinner(nt, trump); return search(nh, [], w, trump, nsT+(isNS(w)?1:0), ewT+(isNS(w)?0:1), alpha, beta, maxD, depth+1, nodeLimit); } return search(nh, nt, nextPos(next), trump, nsT, ewT, alpha, beta, maxD, depth+1, nodeLimit); } legal = reduceEquiv(legal, hands); legal = orderMoves(legal, hands, trick, next, trump); const tricksLeft = Math.ceil(tc / 4); if (nsT + tricksLeft <= alpha) return alpha; if (ewT + tricksLeft <= (13 - beta)) return beta; // --- Transposition table lookup --- const ttKey = maxD === null ? posHash(hands, trick, next) : null; // only TT for exact search if (ttKey) { const ttEntry = ttable.get(ttKey); if (ttEntry) { if (ttEntry.flag === 'exact') return ttEntry.value; if (ttEntry.flag === 'lower' && ttEntry.value >= beta) return ttEntry.value; if (ttEntry.flag === 'upper' && ttEntry.value <= alpha) return ttEntry.value; // Narrow window if (ttEntry.flag === 'lower' && ttEntry.value > alpha) alpha = ttEntry.value; if (ttEntry.flag === 'upper' && ttEntry.value < beta) beta = ttEntry.value; if (alpha >= beta) return ttEntry.value; } } const nsPlay = isNS(next); let bestVal = nsPlay ? -Infinity : Infinity; const origAlpha = alpha; for (const card of legal) { if (nodeCount > nodeLimit || timedOut) break; const nh = removeCard(hands, next, card); const nt = [...trick, { ...card, position: next }]; let val; if (nt.length === 4) { const w = trickWinner(nt, trump); val = search(nh, [], w, trump, nsT+(isNS(w)?1:0), ewT+(isNS(w)?0:1), alpha, beta, maxD, depth+1, nodeLimit); } else val = search(nh, nt, nextPos(next), trump, nsT, ewT, alpha, beta, maxD, depth+1, nodeLimit); if (nsPlay) { if (val > bestVal) bestVal = val; if (bestVal > alpha) alpha = bestVal; } else { if (val < bestVal) bestVal = val; if (bestVal < beta) beta = bestVal; } if (alpha >= beta) break; } // --- Transposition table store --- if (ttKey && !timedOut && bestVal > -Infinity && bestVal < Infinity) { let flag; if (bestVal <= origAlpha) flag = 'upper'; else if (bestVal >= beta) flag = 'lower'; else flag = 'exact'; ttable.set(ttKey, { value: bestVal, flag }); if (ttable.size > TT_MAX) ttable.clear(); // simple eviction } return bestVal; } function evalCard(hands, card, playerPos, currentTrick, trumpSuit, nsTricks, ewTricks, maxDepth, nodeLimit) { const nh = removeCard(hands, playerPos, card); const nt = [...currentTrick, { ...card, position: playerPos }]; if (nt.length === 4) { const w = trickWinner(nt, trumpSuit); return search(nh, [], w, trumpSuit, nsTricks + (isNS(w)?1:0), ewTricks + (isNS(w)?0:1), 0, 13, maxDepth, 1, nodeLimit); } return search(nh, nt, nextPos(playerPos), trumpSuit, nsTricks, ewTricks, 0, 13, maxDepth, 1, nodeLimit); } // ====================================== // MONTE CARLO SAMPLING (Single-Dummy) // B1: Deal generator, B2: Search per sample, B3: Aggregation // ====================================== function generateSamples(hands, playerPos, trumpSuit, knowledge, numSamples) { const contractInfo = knowledge.contractInfo || {}; const declarerPos = contractInfo?.declarer; const dummyPos = contractInfo?.dummy; const visible = [playerPos]; if (dummyPos) visible.push(dummyPos); const hidden = POS.filter(p => !visible.includes(p)); const unseenCards = []; for (const p of hidden) { for (const s of SUIT_ORDER) { for (const r of (hands[p][s] || [])) { unseenCards.push({ suit: s, rank: r }); } } } if (unseenCards.length === 0 || hidden.length === 0) return []; const handSizes = {}; for (const p of hidden) { let count = 0; for (const s of SUIT_ORDER) count += (hands[p][s] || []).length; handSizes[p] = count; } const knownVoids = knowledge.voids || {}; const bidInfo = knowledge.biddingInfo || {}; const hcpRanges = knowledge.hcpRange || {}; const suitLengths = knowledge.suitLength || {}; const samples = []; let attempts = 0; const maxAttempts = numSamples * 10; while (samples.length < numSamples && attempts < maxAttempts) { attempts++; const shuffled = [...unseenCards]; for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; } const deal = {}; for (const p of POS) { deal[p] = {}; for (const s of SUIT_ORDER) deal[p][s] = []; } for (const p of visible) { for (const s of SUIT_ORDER) { deal[p][s] = [...(hands[p][s] || [])]; } } let idx = 0; let valid = true; for (const p of hidden) { const needed = handSizes[p]; const assigned = shuffled.slice(idx, idx + needed); idx += needed; for (const c of assigned) { deal[p][c.suit].push(c.rank); } // Check known voids if (knownVoids[p]) { for (const voidSuit of knownVoids[p]) { if (deal[p][voidSuit].length > 0) { valid = false; break; } } } if (!valid) break; // Check suit length bounds from bidding const pBid = bidInfo[p]; if (pBid) { if (pBid.suitsBid) { for (const s of pBid.suitsBid) { // Bid suit implies 4+ cards originally; remaining in deal must be consistent const origLen = deal[p][s].length + (knowledge.suitPlayed?.[p]?.[s] || 0); const minLen = pBid.preempted && s === pBid.suitsBid[0] ? 6 : 4; if (origLen < minLen) { valid = false; break; } } } if (!valid) break; } // Check HCP range (uses full bidding-derived range, not just "passed") const pHcpRange = hcpRanges[p]; if (pHcpRange) { let dealHcp = 0; for (const s of SUIT_ORDER) { for (const r of deal[p][s]) { dealHcp += cardHcp(r); } } // Total HCP for this player = dealHcp (remaining) + hcpPlayed const totalHcp = dealHcp + (pHcpRange.played || 0); const [bidMin, bidMax] = pHcpRange.bidRange || [0, 37]; if (totalHcp < bidMin || totalHcp > bidMax) { valid = false; break; } } // Check known suit lengths from 4th-suit inference or show-outs if (suitLengths[p]) { for (const s of SUIT_ORDER) { const sl = suitLengths[p][s]; if (sl && sl.exact) { const origLen = deal[p][s].length + (knowledge.suitPlayed?.[p]?.[s] || 0); if (origLen !== sl.min) { valid = false; break; } } } } if (!valid) break; } if (valid) samples.push(deal); } return samples; } function monteCarloEval(legal, hands, playerPos, currentTrick, trumpSuit, nsTricks, ewTricks, knowledge, deadline) { const numSamples = 20; const samples = generateSamples(hands, playerPos, trumpSuit, knowledge, numSamples); if (samples.length < 3) return null; const candidates = reduceEquiv(legal, hands); const nsToPlay = isNS(playerPos); const cardScores = new Map(); for (const card of candidates) { const key = card.suit + card.rank; cardScores.set(key, { card, total: 0, count: 0 }); } const timePerSample = Math.min(10, Math.max(2, (deadline - Date.now()) / (samples.length + 1))); for (const sampleDeal of samples) { if (Date.now() >= deadline - 20) break; const tc = totalCards(sampleDeal); const isEndgame = tc <= 16; const maxDepth = isEndgame ? null : Math.min(8, tc); const nodeLimit = isEndgame ? 100000 : 20000; for (const card of candidates) { if (Date.now() >= deadline - 10) break; startTime = Date.now(); timeLimit = timePerSample; nodeCount = 0; timedOut = false; const val = evalCard(sampleDeal, card, playerPos, currentTrick, trumpSuit, nsTricks, ewTricks, maxDepth, nodeLimit); if (!timedOut) { const key = card.suit + card.rank; const entry = cardScores.get(key); if (entry) { entry.total += val; entry.count++; } } } } let bestCard = null, bestAvg = nsToPlay ? -Infinity : Infinity; for (const [key, entry] of cardScores) { if (entry.count < 2) continue; const avg = entry.total / entry.count; if ((nsToPlay && avg > bestAvg) || (!nsToPlay && avg < bestAvg)) { bestAvg = avg; bestCard = entry.card; } } return bestCard ? { card: bestCard, avgScore: bestAvg, cardScores } : null; } // ====================================== // MAIN API: findBestCard // Heuristics-first, MC for mid-game, search as endgame tiebreaker. // Hard timeout safety: NEVER stalls. // ====================================== function findBestCard(allHands, playedCards, currentTrick, _tl, trumpSuit, playerPos, nsTricks, ewTricks, context) { const deadline = Date.now() + 300; // HARD 300ms deadline // Build remaining hands const hands = {}; POS.forEach(p => { hands[p] = getRemaining(allHands[p], playedCards[p]); }); const leadSuit = currentTrick.length > 0 ? currentTrick[0].suit : null; const legal = getLegalCards(hands[playerPos], leadSuit); if (legal.length === 0) return null; if (legal.length === 1) return legal[0]; // Build context const { contractInfo, trickHistory, auction, dealer } = context || {}; _auctionAlerts = (context && context.bidIsAlert) || null; // alert-aware auction reading const isFirstTrick = !trickHistory || trickHistory.length === 0; const partnerPos = partnerOf(playerPos); const isDeclarer = contractInfo && (playerPos === contractInfo.declarer || playerPos === contractInfo.dummy); const isDefender = contractInfo && !isDeclarer; // Build knowledge — use full PlayerKnowledge, fallback to lightweight tracking on error let tracking; try { tracking = buildPlayerKnowledge(allHands, playedCards, hands, trickHistory, currentTrick, trumpSuit, auction, dealer, contractInfo); } catch (knErr) { console.warn('PlayerKnowledge failed, using lightweight tracking:', knErr.message); tracking = buildTracking(hands, trickHistory, currentTrick, trumpSuit); } const state = { contractInfo, trickHistory, auction, dealer, isFirstTrick, isDeclarer, isDefender, partnerPos, tracking, playedCards, }; try { // ---- LAYER 1: Opening Lead ---- if (currentTrick.length === 0 && isFirstTrick && isDefender) { const lead = selectOpeningLead(hands[playerPos], playerPos, trumpSuit, context); if (lead && legal.some(c => c.suit === lead.suit && c.rank === lead.rank)) { return lead; } } // ---- LAYER 1.5: unified textbook heuristic (shared PlaySelector) ---- // When the shared PlaySelector is loaded, it is the primary heuristic for // every phase — subsequent leads (return partner's suit, cash-outs), // following (2nd-hand-low / 3rd-hand-high, ducking under partner), // signalling with memory, and context-aware discards. The Monte Carlo and // endgame layers below can still override it tactically; the legacy // per-seat selectors remain as the no-PlaySelector last resort. const seatInTrick = currentTrick.length; // 0=lead, 1=2nd, 2=3rd, 3=4th let heuristicPick = null; try { const PS = (typeof PlaySelector !== 'undefined') ? PlaySelector : (typeof window !== 'undefined' && window.PlaySelector) ? window.PlaySelector : null; if (PS && PS.pickDetailed) { const d = PS.pickDetailed(legal, { allHands, playedCards, currentTrick, trumpSuit: trumpSuit || null, playerPos, contractInfo, trickHistory, auction: auction || [], dealer: dealer || 'N', bidIsAlert: (context && context.bidIsAlert) || null, vulnerability: (context && context.vulnerability) || 'n' }); if (d && legal.some(cd => cd.suit === d.suit && cd.rank === d.rank)) { heuristicPick = { suit: d.suit, rank: d.rank }; } } } catch (e) { /* legacy selectors below */ } // ---- LAYER 2: Position-based heuristic (last resort without PlaySelector) ---- // Check if we must ruff or discard (void in led suit) const isVoidInLed = leadSuit && (hands[playerPos][leadSuit] || []).length === 0; if (heuristicPick) { /* PlaySelector already chose */ } else if (isVoidInLed && seatInTrick > 0) { heuristicPick = selectRuffOrDiscard(legal, hands[playerPos], currentTrick, trumpSuit, playerPos, hands, state); } else if (seatInTrick === 0) { // Leading if (isDeclarer) { heuristicPick = selectDeclarerLead(legal, hands[playerPos], trumpSuit, playerPos, hands, state); } else { heuristicPick = selectDefenderLead(legal, hands[playerPos], trumpSuit, playerPos, hands, state); } } else if (seatInTrick === 1) { heuristicPick = selectSecondHand(legal, hands[playerPos], currentTrick, trumpSuit, playerPos, hands, state); } else if (seatInTrick === 2) { heuristicPick = selectThirdHand(legal, hands[playerPos], currentTrick, trumpSuit, playerPos, hands, state); } else if (seatInTrick === 3) { heuristicPick = selectFourthHand(legal, currentTrick, trumpSuit, playerPos, hands, hands[playerPos], state); } // ---- LAYER 3: Finesse detection (declarer) ---- if (isDeclarer && seatInTrick > 0 && !isVoidInLed) { const finessePick = detectFinesse(legal, hands[playerPos], currentTrick, trumpSuit, playerPos, hands, state); if (finessePick) heuristicPick = finessePick; } // ---- LAYER 4: Monte Carlo / Endgame Search ---- const tc = totalCards(hands); if (Date.now() < deadline && tc <= 32 && tc > 0) { if (tc > 16) { // === MID-GAME: Monte Carlo Sampling (single-dummy) === const mcResult = monteCarloEval( legal, hands, playerPos, currentTrick, trumpSuit, nsTricks, ewTricks, { ...tracking, contractInfo }, deadline ); if (mcResult) { const mcCard = mcResult.card; if (heuristicPick) { const hKey = heuristicPick.suit + heuristicPick.rank; const hEntry = mcResult.cardScores.get(hKey); const nsToPlay = isNS(playerPos); if (hEntry && hEntry.count >= 2) { const hAvg = hEntry.total / hEntry.count; const mcAvg = mcResult.avgScore; const diff = nsToPlay ? mcAvg - hAvg : hAvg - mcAvg; if (diff > 0.5) { return mcCard; } } else { const nsToPlay2 = isNS(playerPos); if (mcResult.cardScores.get(mcCard.suit + mcCard.rank)?.count >= 5) { return mcCard; } } } else { return mcCard; } } } else { // === ENDGAME (tc <= 16): Double-dummy search === const candidates = reduceEquiv(legal, hands); const ordered = orderMoves(candidates, hands, currentTrick, playerPos, trumpSuit); startTime = Date.now(); timeLimit = Math.min(150, deadline - Date.now()); const maxDepth = tc <= 16 ? null : Math.min(12, tc); const nodeLimit = tc <= 16 ? 200000 : 50000; nodeCount = 0; timedOut = false; let scores = []; let completed = true; for (let ci = 0; ci < ordered.length; ci++) { if (Date.now() - startTime > timeLimit || timedOut) { completed = false; break; } const val = evalCard(hands, ordered[ci], playerPos, currentTrick, trumpSuit, nsTricks, ewTricks, maxDepth, nodeLimit); if (timedOut) { completed = false; break; } scores.push(val); } if (scores.length >= 2) { const nsToPlay = isNS(playerPos); let bestSearchIdx = 0; for (let i = 1; i < scores.length; i++) { if ((nsToPlay && scores[i] > scores[bestSearchIdx]) || (!nsToPlay && scores[i] < scores[bestSearchIdx])) { bestSearchIdx = i; } } const bestSearchCard = ordered[bestSearchIdx]; const bestSearchScore = scores[bestSearchIdx]; if (heuristicPick && completed) { const heuIdx = ordered.findIndex(c => c.suit === heuristicPick.suit && c.rank === heuristicPick.rank); if (heuIdx >= 0 && heuIdx < scores.length) { const heuScore = scores[heuIdx]; const diff = nsToPlay ? bestSearchScore - heuScore : heuScore - bestSearchScore; if (diff >= 0.4) { return bestSearchCard; } } } if (!heuristicPick) return bestSearchCard; } } } // Return heuristic pick if (heuristicPick && legal.some(c => c.suit === heuristicPick.suit && c.rank === heuristicPick.rank)) { return heuristicPick; } // Final fallback: play first legal card return legal[0]; } catch (e) { console.error('BridgeEngine error:', e); return legal[0]; // Absolute safety fallback } } // ====================================== // CLAIM CHECK: Can user's side win ALL remaining tricks? // Conservative — only succeeds in clear positions. // ====================================== function canClaim(allHands, playedCards, currentTrick, trumpSuit, activePlayer, userIsNS) { return claimCheck(allHands, playedCards, currentTrick, trumpSuit, activePlayer, userIsNS).ok; } // Returns { ok, unverified } — unverified = search ran out of time (ok is false) function claimCheck(allHands, playedCards, currentTrick, trumpSuit, activePlayer, userIsNS) { // v2.25: exact check — can the claiming side win EVERY remaining trick // (including the trick in progress) against any defence? // Claims may be made mid-trick, whenever the claiming side is on play. // Search is exhaustive (with equivalent-card reduction, memoisation and a // fast "leader holds nothing but top winners" accept). If the node budget // runs out the claim is rejected (conservative). Never throws. try { const NO = { ok: false, unverified: false }; const SEATS = ['N', 'E', 'S', 'W']; const trump = trumpSuit && trumpSuit !== 'n' ? trumpSuit : null; const onSide = p => ((p === 'N' || p === 'S') === !!userIsNS); const nxt = p => SEATS[(SEATS.indexOf(p) + 1) % 4]; if (!activePlayer || !onSide(activePlayer)) return NO; // Remaining hands as descending numeric rank arrays const H = {}; let total = 0; SEATS.forEach(p => { const rem = getRemaining(allHands[p] || {}, playedCards[p] || []); H[p] = {}; SUIT_ORDER.forEach(su => { H[p][su] = (rem[su] || []).map(r => CARD_RANK[r]).sort((x, y) => y - x); total += H[p][su].length; }); }); const trick0 = (currentTrick || []).map(c => ({ p: c.position, s: c.suit, r: CARD_RANK[c.rank] })); if (trick0.length >= 4) return NO; if (trick0.length > 0 && nxt(trick0[trick0.length - 1].p) !== activePlayer) return NO; if ((total + trick0.length) % 4 !== 0) return NO; // inconsistent state if (total === 0) return { ok: trick0.length === 0, unverified: false }; let nodes = 0; const deadline = Date.now() + 500; // ms budget (UI thread) let aborted = false; const memo = new Map(); const handLen = p => SUIT_ORDER.reduce((n, su) => n + H[p][su].length, 0); const trickWinner = t => { let best = t[0]; for (let i = 1; i < t.length; i++) { const c = t[i]; if (c.s === best.s) { if (c.r > best.r) best = c; } else if (trump && c.s === trump) best = c; } return best.p; }; // Fast accept: every card the leader holds beats all other cards of its // suit; in a trump contract the leader can draw the opponents' trumps and // partner can never be forced to ruff (partner trumps <= leader trumps). const leaderAllTops = L => { const pa = nxt(nxt(L)); for (const su of SUIT_ORDER) { const mine = H[L][su]; if (!mine.length) continue; let otherMax = 0; SEATS.forEach(q => { if (q !== L && H[q][su].length) otherMax = Math.max(otherMax, H[q][su][0]); }); if (mine[mine.length - 1] < otherMax) return false; } if (trump) { const tl = H[L][trump].length; let oppMax = 0; SEATS.forEach(q => { if (!onSide(q)) oppMax = Math.max(oppMax, H[q][trump].length); }); if (oppMax > 0 && tl < oppMax) return false; if (H[pa][trump].length > tl) return false; } return true; }; // Fast reject: a defender holding the highest outstanding trump always // scores it (by following to a trump lead or by ruffing / last trick). const oppHoldsTopTrump = () => { if (!trump) return false; let sideMax = 0, oppMax = 0; SEATS.forEach(q => { const a = H[q][trump]; if (a.length) { if (onSide(q)) sideMax = Math.max(sideMax, a[0]); else oppMax = Math.max(oppMax, a[0]); } }); return oppMax > sideMax; }; // Legal plays for p, one representative per run of equivalent cards const moves = (p, t) => { const lead = t.length ? t[0].s : null; const suits = lead && H[p][lead].length ? [lead] : SUIT_ORDER; const out = []; for (const su of suits) { const mine = H[p][su]; if (!mine.length) continue; // Claimer's cards split on any other card (who wins decides the next // lead); a defender's cards only split on the claiming side's cards // (either defender winning a trick refutes the claim). const def = !onSide(p); const present = []; SEATS.forEach(q => { if (q !== p && (!def || onSide(q))) H[q][su].forEach(r => present.push(r)); }); t.forEach(c => { if (c.s === su && (!def || onSide(c.p))) present.push(c.r); }); let prevKept = null; for (const r of mine) { if (prevKept !== null && !present.some(x => x < prevKept && x > r)) continue; out.push({ s: su, r }); prevKept = r; } } return out; }; const remove = (p, c) => { const a = H[p][c.s]; a.splice(a.indexOf(c.r), 1); }; const restore = (p, c) => { const a = H[p][c.s]; a.push(c.r); a.sort((x, y) => y - x); }; let horizon = 99; // tricks still to verify in this pass const startTrick = (L, depth) => { if (handLen(L) === 0) return true; if (depth >= horizon) return true; const key = (horizon >= 99 ? 'F' : (horizon - depth)) + ':' + L + '|' + SEATS.map(q => SUIT_ORDER.map(su => H[q][su].join(',')).join('/')).join(';'); if (memo.has(key)) return memo.get(key); let res; if (leaderAllTops(L)) res = true; else if (oppHoldsTopTrump()) res = false; else res = play([], L, depth); if (!aborted) memo.set(key, res); return res; }; const play = (t, p, depth) => { if (aborted) return false; if ((++nodes & 1023) === 0 && Date.now() > deadline) { aborted = true; return false; } if (t.length === 4) { const w = trickWinner(t); if (!onSide(w)) return false; return startTrick(w, depth + 1); } const ms = moves(p, t); const mySide = onSide(p); if (mySide) { // Try higher cards first (winning attempts) ms.sort((x, y) => (y.s === trump) - (x.s === trump) || y.r - x.r); for (const c of ms) { remove(p, c); const ok = play(t.concat([{ p, s: c.s, r: c.r }]), nxt(p), depth); restore(p, c); if (ok) return true; if (aborted) return false; } return false; } else { // Defenders: try the plays most likely to win the trick first const curW = t.length ? t.reduce((best, c) => (c.s === best.s ? (c.r > best.r ? c : best) : (trump && c.s === trump ? c : best)), t[0]) : null; const beats = c => !curW ? (trump && c.s === trump ? 30 : 0) + c.r : (c.s === curW.s ? (c.r > curW.r ? 100 + c.r : c.r) : (trump && c.s === trump ? 90 + c.r : -c.r)); ms.sort((x, y) => beats(y) - beats(x)); for (const c of ms) { remove(p, c); const ok = play(t.concat([{ p, s: c.s, r: c.r }]), nxt(p), depth); restore(p, c); if (!ok) return false; } return true; } }; // Iterative deepening: prove the side wins the next 1, 2, 3 ... tricks. // Each pass is a necessary condition, so most bad claims fail cheaply. const tricksLeft = (total + trick0.length) / 4; let result = true; const passes = []; for (let k = 1; k < tricksLeft; k++) passes.push(k); passes.push(99); for (const k of passes) { horizon = k; result = trick0.length === 0 ? startTrick(activePlayer, 0) : play(trick0, activePlayer, 0); if (!result || aborted) break; } if (aborted) { console.warn('[Claim] search budget exceeded — claim not verified'); return { ok: false, unverified: true }; } return { ok: !!result, unverified: false }; } catch (e) { console.warn('[Claim] canClaim error', e); return { ok: false, unverified: false }; } } return { findBestCard, canClaim, claimCheck }; })(); // ========================================== // END BRIDGE PLAY ENGINE // ========================================== // ========================================== // EXTERNAL ENGINE LOADERS // ========================================== // Dynamically load PlaySelector.js — the shared textbook play brain (opening // leads, follows, signals, discards). BridgeEngine.findBestCard delegates to it // when present; without it BridgeEngine uses its own legacy selectors. (function loadPlaySelector() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'PlaySelector.js?v=' + Date.now(), true); xhr.onload = function() { if (xhr.status === 200 && xhr.responseText.indexOf('PlaySelector') !== -1) { try { (0, eval)(xhr.responseText); if (typeof PlaySelector !== 'undefined') { if (typeof window !== 'undefined') window.PlaySelector = PlaySelector; console.log('PlaySelector ready'); } } catch (e) { console.warn('PlaySelector.js eval failed:', e); } } else { console.log('PlaySelector.js not available — using built-in play heuristics'); } }; xhr.onerror = function() { console.log('PlaySelector.js not found — using built-in play heuristics'); }; xhr.send(); })(); // Dynamically load BiddingEngine.js — runtime 2/1 + Acol bidding with // per-call explanations. Fails silently; random-hand series requires it. let biddingEngineReady = false; (function loadBiddingEngine() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'BiddingEngine.js?v=' + Date.now(), true); xhr.onload = function() { if (xhr.status === 200 && xhr.responseText.indexOf('BiddingEngine') !== -1) { try { (0, eval)(xhr.responseText); if (typeof BiddingEngine !== 'undefined') { if (typeof window !== 'undefined') window.BiddingEngine = BiddingEngine; biddingEngineReady = true; console.log('BiddingEngine ready:', BiddingEngine.VERSION); // v2.45: tell Play the engine has arrived — a robot whose turn came // first (a hand with no programmed auction) bids now. try { window.dispatchEvent(new Event('lbo-bidding-engine-ready')); } catch (e) { /* old browsers */ } } } catch (e) { console.warn('BiddingEngine.js eval failed:', e); } } else { console.log('BiddingEngine.js not available'); } }; xhr.onerror = function() { console.log('BiddingEngine.js not found'); }; xhr.send(); })(); // ---- Robot play engine entry point ------------------------------------- // Single call site for robot cardplay (Robot (Beta) badge). Uses an external // shared engine if one is loaded (window.PlayEngine, same findBestCard // contract: allHands, playedCards, currentTrick, trumpSuit, playerPos, // context -> {suit, rank, rule?, reason?}); otherwise the built-in // BridgeEngine (PlaySelector textbook layer + single-dummy Monte Carlo). // Never throws: returns null if no engine produced a card. function findRobotCard(allHands, playedCards, currentTrick, trumpSuit, playerPos, nsTricks, ewTricks, context) { try { var PE = (typeof window !== 'undefined' && window.PlayEngine) ? window.PlayEngine : null; if (PE && typeof PE.findBestCard === 'function') { var ext = PE.findBestCard(allHands, playedCards, currentTrick, trumpSuit || null, playerPos, context); if (ext && ext.suit && ext.rank) return ext; } } catch (e) { console.warn('PlayEngine failed, using built-in engine:', e); } try { return BridgeEngine.findBestCard(allHands, playedCards, currentTrick, null, trumpSuit, playerPos, nsTricks, ewTricks, context); } catch (e) { console.warn('BridgeEngine failed:', e); return null; } } // One-time startup report of which engine will play the robots' cards. // PlayEngine.js is loaded by a plain