Search code examples
javascriptif-statementblackjack

Need assistance with if statement in Blackjack game


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?


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".