2

Newbie here. Trying to create a blackjack game in javascript. I stored my cards in an array of objects(type, suit, and value) and have gotten it to work so that when I click 'New game' I get a random card on each div.

*I can't seem to get each card to show up a different random card. Whenever I reload the page, the same random card pops up on all 4 divs. Can someone help me out here? * My code below...After I store the array of objects here is what I have.

var randomNumber = Math.floor(Math.random() * 52)
var randomCard = deck[randomNumber];

var playerCardOne = document.querySelector('.playerCardOne');
var playerCardTwo = document.querySelector('.playerCardTwo');
var dealerCardOne = document.querySelector('.dealerCardOne');
var dealerCardTwo = document.querySelector('.dealerCardTwo');

document.querySelector("#newGame").addEventListener("click", function (){
    var cardHTML = '';

    cardHTML += '<h1>' + randomCard.cardType + '/h1>' + '<h2>' + randomCard.suitType + '</h2>'
    // cardHTML += ".playerCardTwo" + randomCard.cardType + ".playerCardTwo";
    // cardHTML += ".dealerCardOne" + randomCard.cardType + ".dealerCardTwo";
    // cardHTML += ".dealerCardTwo" + randomCard.cardType + ".dealerCardTwo";

    // cardHTML += '<h2>' + randomCard.suitType + '</h2>';

    cardHTML = '<h1>' + randomCard.cardType + '</h1>' + '<h2>' + randomCard.suitType + '</h2>'

    playerCardOne.innerHTML = cardHTML;
    playerCardTwo.innerHTML = cardHTML;
    dealerCardOne.innerHTML = cardHTML;
    dealerCardTwo.innerHTML = cardHTML;
})
console.log(randomCard);
Halcyon
  • 57,230
  • 10
  • 89
  • 128

3 Answers3

1

You draw 1 random number and apply that to all 4 cardslots. Consider drawing a random number for each cardslot.

var playerCardOne = document.querySelector('.playerCardOne');
var playerCardTwo = document.querySelector('.playerCardTwo');
var dealerCardOne = document.querySelector('.dealerCardOne');
var dealerCardTwo = document.querySelector('.dealerCardTwo');

var playerOneCards = [];
var playerTwoCards = [];

document.querySelector("#newGame").addEventListener("click", function (){
    playerOneCards.push(drawRandomCard());
    playerOneCards.push(drawRandomCard());
    playerTwoCards.push(drawRandomCard());
    playerTwoCards.push(drawRandomCard());

    playerCardOne.innerHTML = getCardHTML(playerOneCards[0]);
    playerCardTwo.innerHTML = getCardHTML(playerOneCards[1]);
    dealerCardOne.innerHTML = getCardHTML(playerTwoCards[0]);
    dealerCardTwo.innerHTML = getCardHTML(playerTwoCards[1]);
})

function drawRandomCard() {
    return deck[Math.floor(Math.random() * 52)];
}

function getCardHTML(card) {
    return '<h1>' + card.cardType + '</h1>' + '<h2>' + card.suitType + '</h2>';
}

document.querySelector("#hit").addEventListener("click", function () {
    var currentPlayerCards; // figure out which player 'hit'
    currentPlayerCards.push(drawRandomCard());
});

Instead of doing 'playerCardOne'/'playerCardTwo' you could do:

function drawPlayerHand(dom_element, hand) {
    var cardsHTML = "";
    hand.forEach(function (card) {
        cardsHTML += getCardHTML(card);
    });
    dom_element.innerHTML = "<div class='hand'>" + cardsHTML + "</div>";
}

drawPlayerHand(document.getElementById("player1hand"), playerOneCards);

Then you can go a step further and make players dynamic:

var players = [];

functin addPlayer() {
    var elem_id = "player" + players.length + "hand";
    document.getElementById("playerhands").innerHTML += '<div id="' + elem_id + '"></div>';
    players.push({ "hand": [], element: document.getElementById(elem_id) };
}

// add two players
addPlayer();
addPlayer();

function newGame() { // calll on click
    // give each player 2 cards
    players.forEach(function (player) {
        player.hand.push(drawRandomCard());
        player.hand.push(drawRandomCard());
        drawPlayerHand(player);
    });
}

function hit() {
    var currentPlayer; // determine current player somehow
    currentPlayer.push(drawRandomCard());
    drawPlayerHand(currentPlayer);
}

function drawPlayerHand(player) {
    var cardsHTML = "";
    player.hand.forEach(function (card) {
        cardsHTML += getCardHTML(card);
    });
    player.element.innerHTML = "<div class='hand'>" + cardsHTML + "</div>";
}

Draw each card only once:

var draw_deck = [];
for (i = 0; i < 52; i += 1) {
    draw_deck.push(i);
}

function drawRandomCard() {
    var index, card;
    index = Math.floor(Math.random() * draw_deck.length);
    card = draw_deck[index];
    draw_deck.splice(index, 1); // remove drawn card from draw_deck
    return card;
}
// remember to reinitialize the draw deck after a round
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Thank you. Still trying to understand all the bits and pieces ...especially with what's going on with concatenation. Now I need to add values and somehow get it to pop out another card if player 'hits' – BrianCodes33 Aug 25 '15 at 16:21
  • Oh btw, you should draw cards in such a way that each card can only be drawn once. Right now you could draw 4 times ♥A. I added some code for that too. – Halcyon Aug 25 '15 at 16:35
  • I'm having a lot of trouble. Screen share? – BrianCodes33 Aug 25 '15 at 19:00
0

You need to reroll the random number everytime. I modified your function and added some comments. If you have questions don't hesitate to leave a comment.

document.querySelector("#newGame").addEventListener("click", function (){
  var cardHTML = '';
  var randomNumber = 0;
  var randomCard = null;
  // Put the DOMElements within an array so we can access them easily within the loop.
  var cards = [playerCardOne,playerCardTwo,dealerCardOne,dealerCardTwo];

  //Looping so we don't repeat the code 4 times
  for(var i=0; i<4; i++) {
    //Every time you want to show a card, you "shuffle" the deck to pick a new one,
    //instead of picking the same one like you would do before.
    randomNumber = Math.floor(Math.random() * 52);
    randomCard = deck[randomNumber];
    //randomCard = deck[Math.floor(Math.random() * 52)];

    cards[i].innerHTML = '<h1>' + randomCard.cardType + '</h1>' + '<h2>' + randomCard.suitType + '</h2>'
  }
});
Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
  • Thanks jeff. I'm still a newbie to programming. And I got some help with this blackjack game to get me started. I'm trying to break down everything piece by piece and understand what's going on. I guess that is what you have to do being new to programming. – BrianCodes33 Aug 25 '15 at 16:27
0

You are asking the wrong questions. You CANNOT randomly pull a card from the deck. There is no logic to prevent you from pulling the same card twice. Instead, you must randomly shuffle the deck, then always pull the top card.

From: How to randomize (shuffle) a JavaScript array?

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

Then get rid of your drawRandomCard() function. Instead you simply pop elements off the array.

document.querySelector("#newGame").addEventListener("click", function () {
    deck = shuffle(deck);
    playerOneCards.push(deck.pop());
    playerOneCards.push(deck.pop());
    playerTwoCards.push(deck.pop());
    playerTwoCards.push(deck.pop());

    playerCardOne.innerHTML = getCardHTML(playerOneCards[0]);
    playerCardTwo.innerHTML = getCardHTML(playerOneCards[1]);
    dealerCardOne.innerHTML = getCardHTML(playerTwoCards[0]);
    dealerCardTwo.innerHTML = getCardHTML(playerTwoCards[1]);
});
Community
  • 1
  • 1
Mike
  • 335
  • 4
  • 20
  • thanks mike. remember i'm a beginner. so i need to clearly understand what each line of code is doing. – BrianCodes33 Aug 25 '15 at 18:53
  • Well, the first block of code is from the link I referenced, but basically if the array has 52 elements in it, then it goes through the while loop 52 times, and replaces the element at [currentIndex] with a random element in the array. Comments in that function are pretty good. The .pop() function on array is basically the opposite of the .push() function you are using. Push adds the item to the array - the player's cards. Pop removes the item from the array and returns it - the deck of cards. – Mike Aug 25 '15 at 19:57