Saya mencoba membuat beberapa game BlackJack di JavaScript tetapi saya memiliki masalah untuk menampilkan skor pemain saat ini.

    let blackjackGame = {
    'you': {'scoreSpan': "#your-blackjack-result", 'div': '#your-box', 'score': 0},
    'dealer': {'scoreSpan': "#dealer-blackjack-result", 'div': '#dealer-box', 'score': 0},
    'cards': ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'],
    'cardsMap': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': [1, 11]}
};

    function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap']['card'];
}

function showScore(activePlayer) {
    document.querySelector(activePlayer['scoreSpan']).textContent = activePlayer['score'];
}

HTML

<div  class="flex-box-blackjack-board">
                <div id="your-box">
                    <H2>You: <span id="your-blackjack-result">0</span></H2>
                </div>
                <div id="dealer-box">
                    <H2>Dealer: <span id="dealer-blackjack-result">0</span></H2>
                </div>
            </div>

Ketika saya mengklik tombol untuk menekan kartu, tampilan skor NAN tetapi jika saya mengubah baris ini:

    function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap']['card'];
}

Dengan ini:

    function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap']['k'];
}

Skor ditampilkan 10 dan kenaikan normal mengapa saya tidak dapat memilih kartu secara acak dan skor menunjukkan skor yang baik, bukan NaN? saya tidak melihat ada kesalahan.

Terima kasih atas bantuan Anda

0
Ganzo 19 Maret 2020, 19:40

1 menjawab

Jawaban Terbaik

Fungsi Anda tampaknya memiliki kesalahan:

function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap']['card'];
    // above blackjackGame['cardsMap']['card'] returns undefined,
    // that's why you get NaN when you do a sum with number
}

Bukankah maksudmu seperti di bawah ini?

function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap'][card];
    // in this form we refer to the card argument passed to function
}
3
Anastazy 19 Maret 2020, 16:50