Ganzo
Ganzo

Reputation: 250

JavaScript Number Won't display

I try to make some BlackJack game in JavaScript but i have a issue to display the score of the current player.

    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>

When i click on the button to hit the card the score display NAN but if i change this line:

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

by this:

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

The score display 10 and increment normaly why i can't choose a card randomly and the score show the good score instead of NaN? i don't see any error.

Thanks for your help

Upvotes: 0

Views: 70

Answers (1)

Anastazy
Anastazy

Reputation: 4766

Your function seem to have an error:

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
}

didn't you meant something like below?

function updateScore(card, activePlayer) {
    activePlayer['score'] += blackjackGame['cardsMap'][card];
    // in this form we refer to the card argument passed to function
}

Upvotes: 3

Related Questions