GnarGnar
GnarGnar

Reputation: 345

Sorting a hand of cards accoring to rank and suit in python

I'm tying to make a card game and at the moment I'm working on the beginning of it. What I am confused on is sorting the cards in a hand by their rank then suit and pretty much how to cut down on repetition. At the moment I could probably make a for loop for organizing the cards and then have 52 different if for each possibility but I was wondering if their is an easier way to do this and a lot of the other repetitive task. Thanks :D I'll put the code below:

from random import shuffle

class deckOfCards:
  def __init__(self):
    self.rank = ['2','3','4','5','6','7','8','9','T','J','Q','K','A']
    self.suit = ['C', 'S', 'H', 'D']
    self.deck = [r+s for r in self.rank for s in self.suit]
    shuffle(self.deck)

  def setValue(self, deck):
    cnt = 1
    self.value = {}
    for i in self.deck:
      self.value[i] = cnt
      cnt += 1

class Deal:
     def __init__(self, deck, position):
         self.hand = deck[position::4]  #divides the deck into 4 hands
         hand = self.hand
     def value(self, key):  # Gives each card that the player has a value
       newHand = {}
       for i in self.hand:
         if i in key:
           newHand[i] = key[i]
       return newHand

deck = deckOfCards()

player1 = Deal(deck.deck, 0)  #######################################
player2 = Deal(deck.deck, 1)  # Example of repetition that I wanted #
player3 = Deal(deck.deck, 2)  # to get rid of if possible           #
player4 = Deal(deck.deck, 3)  #######################################

EDIT: I think that this works pretty well for sorting cards but I'm still confused on how to eliminate some of the repetition. Thanks for all the help :D

def sortHand(player):
hand = player.hand
for i in hand:
  for i in hand:
    index = player1.hand.index(i)
    if index != 12:
      if deck.value[i] > deck.value[hand[index+1]]:
        hand.insert(index+1, hand.pop(index))

Upvotes: 4

Views: 5602

Answers (1)

NPE
NPE

Reputation: 500773

I'd probably simplify this a bit:

from random import shuffle

class Hand(list):
  pass

class Deck(object):

  rank = '23456789TJQKA'
  suit = 'CSHD'

  def deal(self, n):
    deck = [r+s for r in Deck.rank for s in Deck.suit]
    shuffle(deck)
    return [Hand(sorted(deck[i::n], key=Deck.cmpkey)) for i in xrange(n)]

  @staticmethod
  def cmpkey(card):
    return Deck.rank.index(card[0]), Deck.suit.index(card[1])

print Deck().deal(4)

With this arrangement, the result of deal() is the list of four hands. Each hand is sorted by rank then suit.

(I didn't fully understand the "value" logic, so I've left it out of my example.)

Upvotes: 5

Related Questions