scrimba
Learn JavaScript
Blackjack
Use an object to store player data
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Use an object to store player data
AboutCommentsNotes
Use an object to store player data
Expand for more info
index.js
run
preview
console
// 2. Create the player object. Give it two keys, name and chips, and set their values
let cards = []
let sum = 0
let hasBlackJack = false
let isAlive = false
let message = ""
let messageEl = document.getElementById("message-el")
let sumEl = document.getElementById("sum-el")
let cardsEl = document.getElementById("cards-el")
// 3. Grab ahold of the player-el paragraph and store it in a variable called playerEl

// 4. Render the player's name and chips in playerEl

function getRandomCard() {
let randomNumber = Math.floor( Math.random()*13 ) + 1
if (randomNumber > 10) {
return 10
} else if (randomNumber === 1) {
return 11
} else {
return randomNumber
}
}

function startGame() {
isAlive = true
let firstCard = getRandomCard()
let secondCard = getRandomCard()
cards = [firstCard, secondCard]
sum = firstCard + secondCard
renderGame()
}

function renderGame() {
cardsEl.textContent = "Cards: "
for (let i = 0; i < cards.length; i++) {
cardsEl.textContent += cards[i] + " "
}

sumEl.textContent = "Sum: " + sum
if (sum <= 20) {
message = "Do you want to draw a new card?"
} else if (sum === 21) {
message = "You've got Blackjack!"
hasBlackJack = true
} else {
message = "You're out of the game!"
isAlive = false
}
messageEl.textContent = message
}


function newCard() {
if (isAlive === true && hasBlackJack === false) {
let card = getRandomCard()
sum += card
cards.push(card)
renderGame()
}
}
Console
/index.html
-2:37