This code is breaking really bad if i remove the bold line

Viewed 30
<!DOCTYPE html>
<html>
    <head>
     

    </head>
    <body>
    
<h1 id="message-el">Want to play?</h1>
<p id="cards-el"></p>
<p id="sum-el"></p>
<button onclick="startGame()">Start Game</button>
<button onclick="newCard()">New Card</button>
        <script  src="abc.js" defer></script>
    </body>
</html>
let firstCard  = 10
let secondCard = 4
let cards =  [firstCard,secondCard]
let sum = firstCard + secondCard
let isAlive = true;
let blackJack = false;
let msg = ''
let showMsg = document.getElementById('message-el')
let showCards = document.getElementById('cards-el')
let showSum  = document.getElementById('sum-el')

function startGame(){
    renderGame()
}

function renderGame(){

showCards.textContent = 'Cards: ' it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why

  for (let i  = 0; i<cards.length; i++){
    showCards.textContent += cards[i] + " "
  }

  showSum.innerText = "Sum:" + sum; 

    if(sum <= 20){
msg = 'Draw a new card?'
    }else if(sum ===  21){
msg = 'BlackJack!'
blackJack= true
    }else{
        msg='Lose'
        isAlive = false
    }

    showMsg.innerText = msg;

}
function newCard(){
let card = 1;
sum += card
cards.push(card)
console.log(cards)
renderGame()

}

sorry for this quantity of code,but i really want to make it clear and understand the logic

1 Answers

it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why

The initialisation of showCards.textContent = 'Cards: ' is important, as it removes the previously displayed cards.

This is needed because the loop that follows will iterate over all dealt cards and add them to the showCards.textContent output -- all of them. So if that textContent already had some cards from the previous turn, they will be duplicated.

Related