Reputation: 31
I'm trying to make a 5 card poker game, and I'm trying to make a card_draw
function that doesn't give duplicate cards, but I'm running into problems when trying to check if the randomly drawn card has already been drawn.
from random import choice
class standard_card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
self.card = value + ' of ' + suit
def val():
values = ['Ace','2','3','4','5','6','7','8',
'9','10','Jack','Queen','King']
return choice(values)
def suits():
suit = ['Spades','Hearts','Clubs','Diamonds']
return choice(suit)
def card_draw(player_hand,nogo):
for i in range(5):
draw = standard_card(val(),suits())
while draw in nogo:
draw = standard_card(val(),suits())
player_hand.append(draw)
nogo.append(draw)
nogo = []
player_hand = []
card_draw(player_hand,nogo)
So in def card_draw()
I'm just trying to make sure that the same card is not drawn twice, which is why I have while draw in nogo:
.
However, while draw in nogo
is always False
, meaning sometimes a duplicate card is put into player_hand
and nogo
.
I don't understand why draw in nogo
is always False
. For example, if I do:
test_card = standard_card('7','Spades')
and one of the cards in nogo
generated through card_draw()
also happens to be given the value '7'
and 'Spades'
,
test_card in nogo
is always False
. Could someone explain why please?
Upvotes: 3
Views: 57
Reputation: 7186
The problem is that you are always creating a new object. Two Python objects are by default only the same if they are the same object.
In other words, standard_card('2', 'Spades') == standard_card('2', 'Spades')
will return False
.
In order for Python to know how to compare two cards for equality, you need to tell it how, by implementing the magic method __eq__
:
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def __eq__(self, other):
return self.value == other.value and self.suit == other.suit
def __str__(self):
return self.value + ' of ' + self.suit
I also implemented the __str__
method, so you can do print(card)
and named it according to Python's official style-guide, PEP8.
In the end you might want to implement a Deck
class that holds a deck of cards. Then you can shuffle the cards and successively pop cards from the deck, guaranteeing that every card can only be drawn exactly once.
Upvotes: 6
Reputation: 5833
Because you are comparing a new instance with other instances from the nogo
list every time.
You are essentially doing this:
class A:
pass
a1 = A()
a2 = A()
print(a1 == a2)
Which will always yield False
Upvotes: 1