1

I'm quite a beginner in Javascript and trying to make a blackjack game.

Arrays and objects:

card = {}, //every card is an object having 3 properties: suit, number and points
playerCards = [], //an array containing player cards (objects)
dealerCards = [], //an array containing dealer cards (objects)

I also created manually some cards for testing purposes, like this:

card = {
    suit : "spade",
    number : "queen",
    points : 10
};
playerCards.push(card);

Then i have functions to randomly create new cards and check if it's already in use:

function makeCard() {
    "use strict";
    var uK;
    for (;;) {
        createCard(card, suit, number, points); // creates a new card, code below
        checkCard(card, playerCards, dealerCards, uC); // checkes if card is already in use and returns uC = 1 if "yes" and uC = 0 if "not" (working)
        if (uK === 0) {
            break;
        }
    }
    return card;
}

Here's the code of createCard():

function createCard(card, suit, number, points) {
    "use strict";
    var i = Math.floor(Math.random() * 4);
    card.suit = suit[i];
    i = Math.floor(Math.random() * 13);
    card.number = number[i];
    card.points = points[i];
    return card;
}

It works, but when it creates a new card it replaces the last one manually added in playerCards/dealerCards array. I can prevent it with creating a pointless sample card and not adding it to array (then this one will be replaced), but it doesn't seem right. So what should i do?

Thanks in advance!

4
  • Where's the code that calls createCard and adds the result to the array? Commented Aug 27, 2013 at 14:37
  • 2
    You are probably just manipulating the existing card object, you should instead create a new object. Commented Aug 27, 2013 at 14:37
  • 1
    Blackjack doesn't use suits so you can simplify your code. Commented Aug 27, 2013 at 14:38
  • Thanks! Andrew Whitaker - added that part too; runspired - yes, that's the problem, will check your solution below; user814064 - i need suit to check if the card is already in use and to draw cards Commented Aug 27, 2013 at 14:58

2 Answers 2

2

Generate whole deck (push to array) and then pick a card (splice) randomly (Math.random) out of it.

Sign up to request clarification or add additional context in comments.

Comments

1

You should Create new Cards something like this (using your existing method of passing in arrays when creating a card:

function Card(suit,num,points) {
    var i = Math.floor(Math.random() * 13 )
    this.suit = suit[i];
    this.number = number[i];
    this.points = points[i];
}

Then when you want to create a card:

var myCard = new Card(suits,numbers,points);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.