I’m making a poker game in python and this loop (deal function below) is not behaving the way I expect it to.
import random
def card(suit, value):
return f'{value}{suit}'
def deck():
values = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
suits = ['s', 'd', 'h', 'c']
new_deck = [card(suit, value) for suit in suits for value in values]
return new_deck
def player(name, seat, buyin, hand=[None, None]):
return [name, seat, buyin, hand]
def deal(new_deck, players):
deck_remaining = new_deck
for player in players:
random_card_1 = random.choice(deck_remaining)
deck_remaining.remove(random_card_1)
player[3][0] = random_card_1
random_card_2 = random.choice(deck_remaining)
deck_remaining.remove(random_card_2)
player[3][1] = random_card_2
return deck_remaining, players
if __name__ == '__main__':
pA = player('A', 1, 100)
pB = player('B', 2, 80)
players = [pA, pB]
print(players)
new_deck = deck()
deck_remaining, players = deal(new_deck, players)
print(players)
Each player is a list formatted like this: [name='A', seat=1, buyin=100, hand=[None, None]]
There are two test players ‘A’ and ‘B’. There is a deal function which loops through the players list and selects two random cards from the deck and assigns them to that player’s hand=[None, None]
list and then removes those card from the deck.
The problem is the code above is producing the same hand for both players:
[['A', 1, 100, ['Jc', '7s']], ['B', 2, 80, ['Jc', '7s']]]
Which is not the behavior I expect.
On the first iteration of the loop player A’s hand is [None, None] and then it is correctly assigned, but on the second iteration of the loop player B’s hand has somehow been assigned the same hand as player A, which seems like a mistake to me, unless I’m misunderstanding something?
This code spells is out:
def deal(new_deck, players):
deck_remaining = new_deck
for player in players:
print(player)
print(player[3][0])
print(player[3][1])
random_card_1 = random.choice(deck_remaining)
deck_remaining.remove(random_card_1)
player[3][0] = random_card_1
random_card_2 = random.choice(deck_remaining)
deck_remaining.remove(random_card_2)
player[3][1] = random_card_2
print(player)
print(player[3][0])
print(player[3][1])
return deck_remaining, players
Which produces this output:
['A', 1, 100, [None, None]]
None
None
['A', 1, 100, ['7h', '4d']]
7h
4d
['B', 2, 80, ['7h', '4d']]
7h
4d
['B', 2, 80, ['3c', '6c']]
3c
6c
I made this test loop as a sanity check and it is producing the correct result:
import random
players = [['A', 1, 100, [None, None]], ['B', 2, 80, [None, None]]]
for player in players:
print(player)
print(player[3][0])
print(player[3][1])
player[3][0] = random.randint(0, 9)
player[3][1] = random.randint(0, 9)
print(player)
print(player[3][0])
print(player[3][1])