-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (65 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
let deckId
let computerScore = 0
let myScore = 0
const cardsContainer = document.getElementById("cards")
const newDeckBtn = document.getElementById("new-deck")
const drawCardBtn = document.getElementById("draw-cards")
const header = document.getElementById("header")
const remainingText = document.getElementById("remaining")
const computerScoreEl = document.getElementById("computer-score")
const myScoreEl = document.getElementById("my-score")
function handleClick() {
fetch("https://apis.scrimba.com/deckofcards/api/deck/new/shuffle/")
.then(res => res.json())
.then(data => {
remainingText.textContent = `Remaining cards: ${data.remaining}`
deckId = data.deck_id
console.log(deckId)
})
}
newDeckBtn.addEventListener("click", handleClick)
drawCardBtn.addEventListener("click", () => {
fetch(`https://apis.scrimba.com/deckofcards/api/deck/${deckId}/draw/?count=2`)
.then(res => res.json())
.then(data => {
remainingText.textContent = `Remaining cards: ${data.remaining}`
cardsContainer.children[0].innerHTML = `
<img src=${data.cards[0].image} class="card" />
`
cardsContainer.children[1].innerHTML = `
<img src=${data.cards[1].image} class="card" />
`
const winnerText = determineCardWinner(data.cards[0], data.cards[1])
header.textContent = winnerText
if (data.remaining === 0) {
drawCardBtn.disabled = true
if (computerScore > myScore) {
// display "The computer won the game!"
header.textContent = "The computer won the game!"
} else if (myScore > computerScore) {
// display "You won the game!"
header.textContent = "You won the game!"
} else {
// display "It's a tie game!"
header.textContent = "It's a tie game!"
}
}
})
})
function determineCardWinner(card1, card2) {
const valueOptions = ["2", "3", "4", "5", "6", "7", "8", "9",
"10", "JACK", "QUEEN", "KING", "ACE"]
const card1ValueIndex = valueOptions.indexOf(card1.value)
const card2ValueIndex = valueOptions.indexOf(card2.value)
if (card1ValueIndex > card2ValueIndex) {
computerScore++
computerScoreEl.textContent = `Computer score: ${computerScore}`
return "Computer wins!"
} else if (card1ValueIndex < card2ValueIndex) {
myScore++
myScoreEl.textContent = `My score: ${myScore}`
return "You win!"
} else {
return "War!"
}
}