Rhys
Rhys

Reputation: 425

Python Method in a Class

I'm trying to start using objects properly, I've built a deck of cards which is my object. I want to be able shuffle and deal cards from it. However I can't figure out how to get the shuffle method to work correctly or even if this is the best way to do it.

import itertools
import random

class Deck:
    '''Deck of cards to be used in a card game'''
    def __init__(self):
        self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
        self.suits = ['c', 'd', 'h', 's']
        self.cards = set(itertools.product(self.faces, self.suits))

    def shuffle(self):
        self.cards = random.shuffle(self.cards)

    def deal(self):
        card = self.cards.pop()
        return card[0] + card[1]

Usage;

deck = Deck()
deck.shuffle()
deck.deal()

Upvotes: 1

Views: 46

Answers (1)

dzang
dzang

Reputation: 2260

Sets are not ordered, you could use list() to obtain an ordered deck. Furthermore random.shuffle(l) acts directly on the list and returns None, so you are overwriting the list with None.

import itertools
import random

class Deck:
    '''Deck of cards to be used in a card game'''
    def __init__(self):
        self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
        self.suits = ['c', 'd', 'h', 's']
        self.cards = list(itertools.product(self.faces, self.suits))  # ordered deck
        # self.cards = set(itertools.product(self.faces, self.suits))  # unordered deck

    def shuffle(self):
        random.shuffle(self.cards)

    def deal(self):
        card = self.cards.pop()
        return card[0] + card[1]

Upvotes: 2

Related Questions