Reputation: 11
I'm coding a card game. How do I assign my already created cards to an object through the parent class?
I tried to create a new object with like this:
name = Card(suit1, face1, value1)
but since I declare the name before that it doesn't work properly.
If I print the names after I define the variable name
the output is: 7Hearts, 7Diamonds, 7Clubs, 7Spades, 8Hearts, 8Diamonds...
I want to create objects in the Card class, so that the expected output for
print(7Hearts.suit, 7Hearts.face, 7Hearts.value)
is
>>> (Hearts, 7, 7)
or for
print(AceSpades.suit, AceSpades.face, AceSpades.value)
>>> (Spades, Ace, 11)
from random import *
class Card(object):
def __init__(self, suit, face, value):
self.suit = suit
self.face = face
self.value = value
class Deck(Card):
def __init__(self):
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = range(7, 15)
for rank1 in ranks:
for suit1 in suits:
if rank1 == 11:
face1 = 'Jack'
value1 = 2
elif rank1 == 12:
face1 = 'Queen'
value1 = 3
elif rank1 == 13:
face1 = 'King'
value1 = 4
elif rank1 == 14:
face1 = 'Ace'
value1 = 11
else:
face1 = str(rank1)
value1 = rank1
name = "{0}{1}".format(face1, suit1)
Upvotes: 0
Views: 43
Reputation: 531165
You neither need or want inheritance here. A Deck
is simply a collection of cards.
class Deck(object):
def __init__(self):
self.cards = []
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'],
ranks = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
values = {11: 2, 12: 3, 13: 4, 14: 11}
for suit in suits:
for rank in range(7,15):
card_rank = ranks.get(rank, str(rank))
value = values.get(value, value)
self.cards.append(Card(suit, card_rank, value))
You might use inheritance to represent different kinds of decks: poker deck, pinochle deck, etc. Deck
itself would have methods for things like shuffling, but each subclass would construct the Card
objects appropriate for that deck.
Upvotes: 2