I am, trying to make blackjack in python and whenever i go max bet (which is 5000) the game works perfectly but when i enter something other than 5000 it gives me this error.
Traceback (most recent call last):
File "c:UsersSufysam.DESKTOP-MTN757FDesktopProjectsblackjack.py", line 213, in <module>
main()
File "c:UsersSufysam.DESKTOP-MTN757FDesktopProjectsblackjack.py", line 55, in main
move = getMove(playerHand, money - bet)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:UsersSufysam.DESKTOP-MTN757FDesktopProjectsblackjack.py", line 201, in getMove
moves.append('(D)ouble down')
^^^^^^^^^^^^
AttributeError: 'set' object has no attribute 'append'
I tried cross checking with an answer key for this project and I couldn’t find anything wrong. I also check all my variables and functions and they checked out as well.
Here is my code:
import random, sys
HEARTS = chr(9829)
DIAMONDS = chr(9830)
SPADES = chr(9824)
CLUBS = chr(9827)
BACKSIDE = 'backside'
def main():
print('''Blackjack:
Rules:
Try to get as close to 21 without going over.
Kings, Queens, and Jacks are worth 10 points.
Aces are worth 1 or 11 points.
Cards 2 through 10 are worth their face value.
(H)it to take another card.
(S)tand to stop taking cards.
On your first play, you can (D)ouble down to increase your bet
but must hit exactly one more time before standing.
In case of a tie, the bet is returned to the player.
The dealer stops hitting at 17.''')
money = 5000
while True:
if money <= 0:
print('You're broke!')
print("Good thing you weren't playing with real money")
print('Thanks for playing!')
sys.exit()
print('Money:', money)
bet = getBet(money)
deck = getDeck()
dealerHand = [deck.pop(), deck.pop()]
playerHand = [deck.pop(), deck.pop()]
print('Bet:', bet)
while True:
displayHands(playerHand, dealerHand, False)
print()
if getHandValue(playerHand) > 21:
break
move = getMove(playerHand, money - bet)
if move == 'D':
additonalbet = getBet(min(bet, (money - bet)))
bet += additonalbet
print('Bet increased to {}.'.format(bet))
print('Bet:', bet)
if move in ('H', 'D'):
newCard = deck.pop()
rank, suit = newCard
print('You drew a {} of {}.'.format(rank, suit))
playerHand.append(newCard)
if getHandValue(playerHand) > 21:
continue
if move in ('S', 'D'):
break
if getHandValue(playerHand) <= 21:
while getHandValue(dealerHand) < 17:
print('Dealer hits...')
dealerHand.append(deck.pop())
displayHands(playerHand, dealerHand, False)
if getHandValue(dealerHand) > 21:
break
input('Press Enter to contiue...')
print('nn')
displayHands(playerHand, dealerHand, True)
playerValue = getHandValue(playerHand)
dealerValue = getHandValue(dealerHand)
if dealerValue > 21:
print('Dealer busts! You win ${}!'.format(bet))
money += bet
elif (playerValue > 21) or (playerValue < dealerValue):
print(' You lost!')
money -= bet
elif playerValue > dealerValue:
print('You won ${}!'.format(bet))
money += bet
elif playerValue == dealerValue:
print('Its a tie, the bet is returned to you')
input('Press Enter to continue...')
print('nn')
def getBet(maxBet):
while True:
print('How much do you bet? (1-{}, or QUIT)'.format(maxBet))
bet = input('> ').upper().strip()
if bet == 'QUIT':
print('Thanks for playing!')
sys.exit()
if not bet.isdecimal():
continue
bet = int(bet)
if 1 <= bet <= maxBet:
return bet
def getDeck():
deck = []
for suit in (HEARTS, DIAMONDS, SPADES, CLUBS):
for rank in range(2, 11):
deck.append((str(rank), suit))
for rank in ('J', 'Q', 'K', 'A'):
deck.append((rank, suit))
random.shuffle(deck)
return deck
def displayHands(playerHand, dealerHand, showDealerHand):
print()
if showDealerHand:
print('Dealer: ', getHandValue(dealerHand))
else:
print('Dealer : ???')
displayCards([BACKSIDE] + dealerHand[1:])
print('PLAYER:', getHandValue(playerHand))
displayCards(playerHand)
def getHandValue(cards):
value = 0
numberofAces = 0
for card in cards:
rank = card[0]
if rank =='A':
numberofAces += 1
elif rank in ('K', 'Q', 'J'):
value += 10
else:
value += int(rank)
value += numberofAces
for i in range(numberofAces):
if value + 10 <= 21:
value += 10
return value
def displayCards(cards):
rows = ['', '', '', '', '']
for i, card in enumerate(cards):
rows[0] += ' ___ '
if card == BACKSIDE:
rows[1] += '|## | '
rows[2] += '|###| '
rows[3] += '|_##| '
else:
rank, suit = card
rows[1] += '|{} | '.format(rank.ljust(2))
rows[2] += '| {} | '.format(suit)
rows[3] += '|_{}| '.format(rank.rjust(2, '_'))
for row in rows:
print(row)
def getMove(playerHand, money):
while True:
moves = {'(H)it', '(S)tand'}
if len(playerHand) == 2 and money > 0:
moves.append('(D)ouble down')
movePrompt = ', '.join(moves) + '> '
move = input(movePrompt).upper()
if move in ('H', 'S'):
return move
if move == 'D' and '(D)ouble Down' in moves:
return move
if __name__ == "__main__":
main()
Shayaan Khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The issue you’re having stems from moves
being a set, not a list. The append
method is for lists, not sets. If you want to add something to an existing set, use add
foo = {'a', 'b', 'c'}
foo.add('d')
print(foo)
# {'d', 'b', 'c', 'a'} notice that sets don't preserve insertion order!
Alternatively, in your specific case, you might just want to change the set
moves = {'(H)it', '(S)tand'} # this is a set
to a list
moves = ['(H)it', '(S)tand'] # this is a list
(notice the difference in brackets!)
You can also remove items from a list with the remove
or pop
methods.