PythonBoy69
PythonBoy69

Reputation: 115

Python Blackjack Game how to carry a variable in a while loop

I'm still deep into the making of my Blackjack game in Python, my aim is to allow the computer to 'twist' (Take another card) until the total value is greater than 15. From then onwards I want it so that as the total of the cards gets higher, the chance of the computer taking another card gets smaller just like a human (taking a risk if the number isn't TOO big).The following code occurs after the computer has been dealt two values.

if (computerCardValueTotal < 15): print ("The computer has decided to twist") ranCompCard3 = random.choice(availableCards) computerCardValueTotal = ranCompCard + ranCompCard2 + ranCompCard3 if (computerCardValueTotal < 15): print ("The computer has chosen to twist again")

My aim is to have this piece of code loop if the total value is less than 15 so that the computer twists until it is over 15. I have considered using a while loop but I'm unsure on how to carry the current total to the start of the loop so that the next card value is added to the current total. Does anyone have a solution they could help me out with?

Also, secondly, it's not the biggest of the two issues in this question, but how would you recommend doing the computer so that the chance of it twisting again is smaller as the total value of cards get bigger? For example, for if the value of the cards totals at 17, there's a 1/10 chance of the computer twisting but if the total value of the cards is 19 the chance of the computer twisting is 1/20.

All valuable help will be voted up and as always, thanks in advance! :)

Upvotes: 0

Views: 253

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122106

You have hobbled yourself by making e.g. ranCompCard, ranCompCard2, ranCompCard3, ... when a list would make life much easier:

compCards = [ranCompCard, ranCompCard2]
while sum(compCards) < 15:
    compCards.append(random.choice(availableCards))

For adjusting the probability of picking another card, you could do something like:

while True:
    gap = 21 - sum(compCards)
    if gap > 0 and random.random() < (1 / (40 / float(gap))):
        compCards.append(random.choice(availableCards))
    else:
        break

Note that this is a linear relationship between gap and the probability of picking another card:

>>> for card_sum in range(15, 21):
    print card_sum, 1 / (40 / float(21 - card_sum))


15 0.15
16 0.125
17 0.1
18 0.075
19 0.05
20 0.025

but you can adjust the equation as needed.


While you're editing your code, take a look at (and consider following) the official style guide; variable names should be lowercase_with_underscores.

Upvotes: 3

g.d.d.c
g.d.d.c

Reputation: 48028

Simply reassign the value when it changes.

while computerCardValueTotal < 15:
  # other code
  computerCardValueTotal = <new value>

Upvotes: 0

Related Questions