neonite
neonite

Reputation: 5

BlackJack Project - Can't make aces change from 11 to 1's

I'm currently making a blackjack game for my project in school in Visual Basic.

In blackjack, when you have aces (value initially 11) their value turns to 1 when the total value of the cards is > 21. In code, this would just take away 10 for every ace

I'm stuck on this.

This is the code I have (that doesn't work):

Do While PlayerValue > 21 And counter <= noAcesPlayer
        counter += 1
        PlayerValue -= 10
Loop

In a senario, I have a: 2, 8, A, 8 (=29) But since there is an Ace, and the total value is > 21, the value should have 10 subtracted from it (=19) - the above code does not do this.

Another scenario would be 10, 8, A, A (=40) Again, the two Aces should turn into 1's, since the total value > 21, giving 20.

Any help would be greatly appreciated. :)

Upvotes: 0

Views: 1076

Answers (2)

dbasnett
dbasnett

Reputation: 11773

Here is an approach

Public Enum CardFace
    None
    Ace
    Two
    Three
    Four
    Five
    Six
    Seven
    Eight
    Nine
    Ten
    Jack
    Queen
    King
End Enum

This code should produce a value of twenty

    Dim cards As New List(Of CardFace) From {CardFace.Ten, CardFace.Eight, CardFace.Ace, CardFace.Ace}
    Dim total As Integer = 0
    Dim numofAces As Integer = 0
    For Each c As CardFace In cards
        Debug.WriteLine(c.ToString)
        If c = CardFace.Ace Then
            numofAces += 1
        Else
            total += c
        End If
    Next

    If numofAces > 0 Then
        If total + 11 + (numofAces - 1) > 21 Then
            total += numofAces
        Else
            total += 11 + (numofAces - 1)
        End If
    End If
    Debug.WriteLine(total)

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

The correct way to build a blackjack hand is the following (in pseudo-code):

Variables: total = 0, soft-flag = false

For each card in hand:
    Add card value to total. Faces are 10, aces are 1.
    If the card you added was an ace, set soft-flag = true

If total < 12 and soft-flag:
    Add 10 to total
Else:
    set soft-flag = false

That's it. Only one loop over the cards, no extraneous variables, and you're left with the total value and a flag indicating if the total is soft.

Upvotes: 0

Related Questions