I'm trying to do a blackjack in python - python

I am in the process of doing blackjack, but I have a problem.
I don't know how to do that if I want him to print for example the Q to print it as str, but when adding the player's hand I take it as a 10.
The error it gives me is: TypeError: unsupported operand type(s) for +: 'int' and 'str'
The code I have is:
jugador = []
dealer = []
deck = ['A' ,2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'K', 'Q']
for card in deck:
if card == 'J':
card = 10
elif card == 'K':
card = 10
elif card == 'Q':
card = 10
while len(jugador) != 2:
random.choice(deck)
card = random.choice(deck)
jugador.append(card)
if card == 'A':
card = 11
print(jugador)
if sum(jugador) > 11:
print("Hola")```

There are two values you want to track: Name and effective value. Your code currently tries to track them in one variable. Try using either different variables to track Name vs Value or try defining and using a class to capture these details.

You need to upgrade some things in your code for example the deck contains 4 cards of each number, so you should add that. You can also use a dictionary to represent the deck :
deck = {'A': 1, '2': 2, ..., 'K': 10}
Note that in the dictionary the keys are strings and their values are integers. You should also remove the first random.choice(deck) because you stored the random value in the card variable and dont forget to remove the card you picked for the player.

Related

How to update a counter from dictionary Python

I'm new to Python and coding in general and am trying to create a blackjack game in Python but I'm having trouble getting the point counter point_selection to update based on the card values in the player's hand:
deck_points = {2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
dealer_hand = []
player_hand = []
dealer_points = 0
player_points = 0
def deal_initial_cards(hand, point_selection):
for i in range(2):
i = random.choice(list(deck_points))
hand.append(i)
for card in hand:
point_selection += deck_points[card]
deal_initial_cards(dealer_hand, dealer_points)
print(dealer_points)
Using the above code, the counter never updates past '0' and I'm not sure what I'm doing wrong. Any help is appreciated.
Here's a more Pythonic solution that fixes your main bug about your function deal_initial_cards() operating on a copy of its (immutable) int argument point_selection then throwing away the result, since it doesn't have a return point_selection (or store the result in a class member self.points). (Also, I made all your dict keys strings: '2','3',.... It's usually customary to represent '10' as 'T' to make all cards a single letter).
But since you're essentially declaring a Hand class, then instantiating two objects of it (dealer_hand, player_hand). deal_initial_cards() is essentially a Hand._init__() in disguise, so we have a data member cards (best not to also call it hand). See how simple and clean ph = Hand() is; no need for globals. Moreover, we could statically compute points inside the __init__() function and return it (or, better, store it in self.points inside each hand object), but that would be a bad decomposition, since if we subsequently add cards to self.cards, points wouldn't get updated. So, much more Pythonic is to make points a property of the class. We then access it
without parentheses: dh.points, not dh.points(). Last, note the use of a list comprehension (instead of a for-loop-append) to generate self.hand. And inside points(), note the use of a generator expression deck_points[card] for card in self.cards, again more Pythonic than for-loop counter. So this small example is a great showcase of Python idiom and decomposition. We can add a __str__() method to Hand. (You could also have a Card class, but really that would be overkill.)
import random
deck_points = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
# No globals, so no need to initialize anything
class Hand:
def __init__(self):
self.cards = [random.choice(list(deck_points)) for _ in range(2)]
#property
def points(self):
return sum(deck_points[card] for card in self.cards)
def __str__(self, join_char=''):
return join_char.join(card for card in self.cards)
#deal_initial_cards(dealer_hand, dealer_points)
ph = Hand()
dh = Hand()
print('Dealer: ', end='')
print(dh.points)
print('Player: ', end='')
print(ph.points)
Python ints are immutable, this means dealer_points isn't updated. Initialy they have the same id(use id()), but when you change the variable inside the function it creates a new variable. To fix your code you need to do something like
deck_points = {2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
dealer_hand = []
player_hand = []
dealer_points = 0
player_points = 0
def deal_initial_cards(hand, point_selection):
for i in range(2):
i = random.choice(list(deck_points))
hand.append(i)
for card in hand:
point_selection += deck_points[card]
return point_selection
dealer_points = deal_initial_cards(dealer_hand, dealer_points)
print(dealer_points)
whereas a list, which you probably noticed, is mutable. This means the list inside the function stays the same(keeps its id) even when its edited.

How to get a function to run twice dynamically

This is a function.
def cut_dk():
a = []; b = []
random.shuffle(deck__)
slice = deck__[:2]
a.append(slice[0])
b.append(slice[1])
return a,b
c = cut_dk()
p1 = c[0]
p2 = c[1]
I have this function at the top of the program along with other functions.
It draws from a predefined list.
When calling this function dynamically in the program it returns the same variables.
It's the cutting of a card deck (two cards, highest wins the draw), when the cards are equal it needs to draw again (this is the problem, a second draw), a new selection from the list, yet it just repeats the variables it has in memory.
Calling the function again in a conditional statement just returns the same initial variables acquired on the first run, so I am unable to repeat the cut dynamically as part of the game play.
I would manage my deck as an object here with a class. This would allow us to define a deck, which is stored as an object and perform multiple functions against the deck whilst retaining the state changes from different functions.
class deck:
"""
Class designed to manage deck including iterations of changes.
Shuffling the deck will retain shuffle changes
"""
def __init__(self):
self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
self.original = self.deck[:]
def shuffle(self):
"""
Shuffle deck in-place. self.deck will be modified
"""
random.shuffle(self.deck)
def cut(self):
"""
Shuffles deck and draws the two top-most cards
Returns: tuple(2) two cards from top of the deck
"""
self.shuffle()
a, b = self.deck[:2]
return a, b
def highest_draw(self):
"""
Calls self.cut() to shuffle and retrieve 2x top-most cards.
If cards match the deck is shuffled and cut again.
Returns: 2 Unique cards from top of the deck
"""
a, b = self.cut()
while a == b:
a, b = self.cut()
return a, b
def reset(self):
self.deck = self.original[:]
game = deck()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
game.shuffle()
game.deck
#['A', 7, 5, 9, 8, 'J', 'K', 6, 4, 3, 1, 'Q', 2]
game.reset()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
game.cut()
#('A', 'Q')
game.highest_draw()
#('J', 2)
You would still need to define how you determine the "highest" card, however this is dependant on your deck, which you have left out of the question.
It sounds as if a generator function would be useful here. You call the function once to set up your iterator and then 'draw' cards from that iterator (in this case the iterator is 'cards'). Notice you have to catch the case where you run the whole deck and it's tied throughout. I've sprinkled print statements through this to make it easier to understand how generators work.
import random
deck__ = list(range(3))*2
def draw_from_shuffled():
random.shuffle(deck__)
print(f'Deck after shuffling: {deck__}')
for c in deck__:
yield c
cards = draw_from_shuffled() #cards is now an iterator
while True:
try:
a = next(cards)
b = next(cards)
except StopIteration:
print(f'End of deck!')
cards = draw_from_shuffled()
continue
print(f'Drew {a} and {b}')
if a != b:
break
print('Hand done.')
Sample output:
Deck after shuffling: [2, 2, 1, 1, 0, 0]
Drew 2 and 2
Drew 1 and 1
Drew 0 and 0
End of deck!
Deck after shuffling: [0, 0, 2, 2, 1, 1]
Drew 0 and 0
Drew 2 and 2
Drew 1 and 1
End of deck!
Deck after shuffling: [0, 2, 1, 0, 1, 2]
Drew 0 and 2
Hand done.
More on generators: https://realpython.com/introduction-to-python-generators/

Random number generator comparing a list

Hi I am trying to compare a list of picked numbers to a list of randomly generated numbers. I want to know how many times it took to get the same numbers in the same sequence picked. I am using the choice() function which i have imported. Please see my code below. I seem to continue to get an infinite loop and never generate the same list as "my ticket"
My code below
from random import choice
my_ticket = (9, 'z', 4, 0)
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
winning_numbers = []
picked_sequences = []
increment = 0
while True:
for pick in range(4):
pick = choice(lottery_numbs)
winning_numbers.append(pick)
if winning_numbers in picked_sequences:
continue
else:
picked_sequences.append(winning_numbers)
if my_ticket in picked_sequences:
print(increment)
break
else:
winning_numbers = []
print(increment)
increment += 1
print(winning_numbers)
print(my_ticket)
print(f"It took {increment} picks to pick my lottery numbers")
Think about the types of data that you're generating. What is choice(lottery_numbs) returning? What does winning_numbers contain? What are you comparing it against? If you have similar digits in different containers, you're not going to get a "match" unless you explicitly handle the containers.
The following is my take on your code.
Firstly, I changed your my_ticket into winning_ticket and made it into a list.
Then I changed your filtering of duplicate numbers inside current_ticket into a while loop, to ensure that the ticket will always contain 4 unique characters.
Then I converted your while true loop into a while condition on if the current ticket is the same as winning ticket.
Your main issue is the my_ticket being a tuple, the other minor issues are redundant for loop to filter duplicate, no guarantee on current ticket having 4 characters, variable namings, etc.
from random import choice
winning_ticket = [9, 'z', 4, 0]
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
picks = 0
current_ticket = []
while current_ticket != winning_ticket:
current_ticket = []
while len(current_ticket) < 4:
pick = choice(lottery_numbs)
if pick not in current_ticket:
current_ticket.append(pick)
picks += 1
print(f"It took {picks} picks to pick my lottery numbers")

How do you print values in lists with their index number in Python 2.7?

I am trying to make a Blackjack game in python. I ran into a problem because I am trying to use the random module with my game. I used the random module to get a number that coordinates with the index number in my list. The list I made consisted of card face values. I don't know how to print these values using the random index number, though. Here is my code:
# this is a blackjack game made in python
import random
import time
# make a list full of the card values
cards = (["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10])
indexNum1 = random.randint(0,12)
indexNum2 = random.randint(0,12)
indexNum3 = random.randint(0,12)
indexNum4 = random.randint(0,12)
indexNum5 = random.randint(0,12)
for card in cards:
print card(indexNum1)
print card(indexNum2)
print card(indexNum3)
print card(indexNum4)
print card(indexNum5)
I hope someone can help me solve this problem. Thanks!
You can index cards directly, e.g.:
print(cards[indexNum1])
But if you want in a loop you should iterate over the indexes:
for cardidx in (indexNum1, indexNum2, indexNum3, indexNum4, indexNum5):
print(cards[cardidx])
But you are making this much harder than you need to, because currently your code could return 5 Aces - which I assume you don't want:
cards = ["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10]
hand = random.sample(cards, k=5)
for card in hand:
print(card)
If you want to properly simulate a deck of cards, you'll have to do this:
import random
def clean_deck():
return list("AJQK234567890") * 4
def draw_cards(deck, n):
return [deck.pop() for _ in range(n)]
deck = clean_deck()
random.shuffle(deck)
for card in draw_cards(deck, 5):
print(card)
This keeps track of the deck of cards, literally shuffles them, which is conveniently a random function, and then "draws" from the deck (pops). You have to keep track of the deck so you could, for example, draw 4 aces but then there wouldn't be any more left. This approach is also persistent across card-drawings - when you draw cards from the deck, they are actually removed, so you also can't draw more than 4 aces in an entire game. It will crash if you try to draw from an empty deck, although you could put an if statement in draw_cards to refill the deck if needed, but you should be aware that this would happen if the deck ran out - it could lead to weird things like 5 aces in a game.
I've changed all your digits to strings, as there's no use for them as integers if some cards aren't integers. (An alternative is to keep them all as integers, which you can do with the range function - at a guess range(13), or if you want to go from 2, range(2, 15)). I've also changed 10 to 0 as 0 was unused and that made it a lot more concise. It should be easy enough to change back should you wish.
The difference between this and the other approaches is that the other approaches never remove cards (pop). They just randomly pick cards and then put them back, although they've been drawn.
If you want to randomly choose k cards without repetition and keep the indices, this may helps:
import random
cards = (["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10])
indices = random.sample(range(len(cards)), k=5)
print 'Indices are:', indices, '\nCards chosen are:',[cards[index] for index in indices]

Moving items around in a python list?

This is the final product. IF anyone else has any tips to cut it up, please let me know! Thanks a lot for the help!
def triple_cut(deck):
''' (list of int) -> NoneType
Modify deck by finding the first joker and putting all the cards above it
to the bottom of deck, and all the cards below the second joker to the top
of deck.
>>> deck = [2, 7, 3, 27, 11, 23, 28, 1, 6, 9, 13, 4]
>>> triple_cut(deck)
>>> deck
[1, 6, 9, 13, 4, 27, 11, 23, 28, 2, 7, 3]
'''
joker1 = deck.index(JOKER1)
joker2 = deck.index(JOKER2)
first = min(joker1, joker2)
first_cards = []
for cards in range(len(deck[:first])):
cards = 0
pop = deck.pop(cards)
first_cards.append(pop)
joker1 = deck.index(JOKER1)
joker2 = deck.index(JOKER2)
second = max(joker1, joker2)
second_cards = []
for cards in deck[second + 1:]:
pop = deck.pop(deck.index(cards))
second_cards.append(pop)
second_cards.reverse()
for card in second_cards:
deck.insert(0, card)
deck.extend(first_cards)
raah I need to type more because my post is mostly code: please add more details sss ss
A hint:
p = list('abcdefghijkl')
pivot = p.index('g')
q = p[pivot:] + p[:pivot]
List slicing is your friend.
answer to the second revision
when the function is finished, it won't mutate the deck.
The problem is that you didn't give the full code. I'm guessing it looks like this:
def triple_cut(deck)
…
deck = q
And according to your docstring you call it as
deck = […]
triple_cut(deck)
and have gotten confused that the assignment deck = q doesn't propagate out of triple_cut(). You can't modify the formal parameters of a method so the assignment remains local to triple_cut and does not affect the module level variable deck
The proper way to write this is
def triple_cut(cuttable)
…
return cuttable[first:] + cuttable[:first]
deck = […]
deck = triple_cut(deck)
where I changed the name of the argument to cuttable to for purposes of explanation. You could keep the argument name as deck but I wanted to show that when you thought you were assigning to deck you were really assigning to cuttable and that assignment wouldn't carry out of triple_cut().

Categories