Untitled

 avatar
unknown
plain_text
a month ago
1.7 kB
6
Indexable
// blackjackEngine.js
class BlackjackGame {
    constructor() {
        this.deck = this.createDeck();
        this.playerHand = [];
        this.dealerHand = [];
    }

    createDeck() {
        const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
        const values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
        let deck = [];
        // In production, use a Cryptographically Secure RNG (CSPRNG)
        for (let suit of suits) {
            for (let value of values) {
                deck.push({ suit, value });
            }
        }
        return this.shuffle(deck);
    }

    shuffle(deck) {
        // Fisher-Yates Shuffle Algorithm
        for (let i = deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [deck[i], deck[j]] = [deck[j], deck[i]];
        }
        return deck;
    }

    calculateScore(hand) {
        let score = 0;
        let aces = 0;
        for (let card of hand) {
            if (['J', 'Q', 'K'].includes(card.value)) score += 10;
            else if (card.value === 'A') {
                aces += 1;
                score += 11;
            } else score += parseInt(card.value);
        }
        while (score > 21 && aces > 0) {
            score -= 10;
            aces -= 1;
        }
        return score;
    }

    dealInitialCards() {
        this.playerHand = [this.deck.pop(), this.deck.pop()];
        this.dealerHand = [this.deck.pop(), this.deck.pop()];
        return {
            player: this.playerHand,
            dealerVisible: this.dealerHand[0] // Hide dealer's second card
        };
    }
}
Editor is loading...
Leave a Comment