Question

I am working on my first black jack game and I keep getting confused by the simplest thing. The problem is in my if statement I say this :

if ( cardsinhand < 7 && newcard != firstcard && newcard != secondcard )

and when I press the hit me button it will deal me the same card over and over again. Here is my function. I need the info in the if statement to be true and then execute, otherwise just not execute.

cardsinhand = 2
firstcard = Math.floor(Math.random() * 1000 % 52)
secondcard = Math.floor(Math.random() * 1000 % 52)
newcard = Math.floor(Math.random() * 1000 % 52)

function hitCard()
{
  if ( cardsinhand < 7 && newcard != firstcard && newcard != secondcard )
  {
    document.images[cardsinhand].src = "http://www.biogow/images/cards/gbCard" + newcard + ".gif"

    cardsinhand++
  }
}

any idea why this isnt working right?

Was it helpful?

Solution

It's not actually a problem with your if statement itself. It appears that this:

newcard = Math.floor(Math.random() * 1000 % 52)

is being done once rather than every time you hit. That means you will get the same card over and over.

You should probably recalculate a new card every time you perform a hit operation.


You should probably also look into how you're generating cards. Normally, you would use a deck (containing one or more "real" decks) so that the probabilities change as cards are removed, just like in real life.

That would also fix any skewing problem from using * 1000 % 52 which would tend to prefer cards at one end of the "deck".

OTHER TIPS

This is because you are only ever generating newcard once, outside of the function body. What you want is for the new card to be generated each time you call the function, and so this line: newcard = Math.floor(Math.random() * 1000 % 52) should be inside the function, like so:

cardsinhand = 2
firstcard = Math.floor(Math.random() * 1000 % 52)
secondcard = Math.floor(Math.random() * 1000 % 52)


function hitCard()
{
    var newcard = Math.floor(Math.random() * 1000 % 52)
    if ( cardsinhand < 7 && newcard != firstcard && newcard != secondcard )
    {
        document.images[cardsinhand].src = "http://www.biogow/images/cards/gbCard"+newcard+".gif"

         cardsinhand++ 
    }
}

Also for what it's worth, if you're just starting out you might want to look into using an Array for storing the cards of your hand. What's going to happen to that if condition when your newcard could be the first card, the second card or the third card?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top