|
| 1 | +console.log('In blackjack console'); |
| 2 | + |
| 3 | +//Card variables |
| 4 | +let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'], |
| 5 | + values = ['Ace', 'King', 'Queeen','Jack', 'Ten', 'Nine', |
| 6 | + 'Eight', 'Seven','Six','Five','Four','Three', |
| 7 | + 'Two']; |
| 8 | + |
| 9 | +//DOM variables |
| 10 | +let textArea = document.getElementById('text-area'), |
| 11 | + newGameButton = document.getElementById('new-game-button'), |
| 12 | + hitButton = document.getElementById('hit-button'), |
| 13 | + stayButton = document.getElementById('stay-button'); |
| 14 | + |
| 15 | +//Game variables |
| 16 | +let gameStarted = false, |
| 17 | + gameOver = false, |
| 18 | + playerWon = false, |
| 19 | + dealerCards = [], |
| 20 | + playerCards =[], |
| 21 | + dealerScore =0, |
| 22 | + playerScore =0, |
| 23 | + deck =[]; |
| 24 | + |
| 25 | + hitButton.style.display = 'none'; |
| 26 | + stayButton.style.display = 'none'; |
| 27 | + showStatus(); |
| 28 | + |
| 29 | +newGameButton.addEventListener('click', function(){ |
| 30 | + gameStarted = true; |
| 31 | + gameOver = false; |
| 32 | + playerWon = false; |
| 33 | + |
| 34 | + deck = createDeck(); |
| 35 | + shuffleDeck(deck); |
| 36 | + dealerCards = [getNextCard(), getNextCard()]; |
| 37 | + playerCards = [getNextCard(), getNextCard()]; |
| 38 | + |
| 39 | + newGameButton.style.display = 'none'; |
| 40 | + hitButton.style.display = 'inline'; |
| 41 | + stayButton.style.display = 'inline'; |
| 42 | + |
| 43 | + showStatus(); |
| 44 | +}); |
| 45 | + |
| 46 | +function shuffleDeck(deck){ |
| 47 | + for(let i=0; i<deck.length; i++){ |
| 48 | + let swapIdx = Math.trunc(Math.random()*deck.length); |
| 49 | + let tmp = deck[swapIdx]; |
| 50 | + deck[swapIdx] = deck[i]; |
| 51 | + deck[i] = tmp; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +function getNextCard(){ |
| 56 | + return deck.shift(); |
| 57 | +} |
| 58 | +function createDeck(){ |
| 59 | + let deck = []; |
| 60 | + for(let suitIdx=0; suitIdx < suits.length; suitIdx++){ |
| 61 | + for(let valueIdx=0; valueIdx < values.length; valuesIdx++){ |
| 62 | + let card = { |
| 63 | + suit : suits[suitIdx], |
| 64 | + value: values[valueIdx] |
| 65 | + }; |
| 66 | + deck.push(card); |
| 67 | + } |
| 68 | + return deck; |
| 69 | + } |
| 70 | + |
| 71 | + function getCardString(card){ |
| 72 | + return card.value + ' of ' + card.suit; |
| 73 | + } |
| 74 | + |
| 75 | + function showStatus(){ |
| 76 | + if(!gameStarted){ |
| 77 | + textArea.innerText = "Welcome to Blackjack!"; |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + for(var i=0; i<deck.length; i++){ |
| 82 | + textArea.innerText += '\n' + getCardString(deck[i]); |
| 83 | + } |
| 84 | + |
| 85 | + } |
| 86 | + |
| 87 | +} |
| 88 | + |
| 89 | + |
0 commit comments