[Tutor] Cards Program
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 21 Feb 2001 15:54:01 -0800 (PST)
On Tue, 20 Feb 2001, Timothy M. Brauch wrote:
> As it is right now, I can get the program to deal as many cards as I
> want, but I cannot think of a way to get the cards into seperate hands,
> other than just having the program deal out the cards and then manually
> split these cards up into hands myself. That is not what I am looking
> for. Here is my code so far:
> values=['2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace']
> suits=['Hearts','Spades','Diamonds','Clubs']
>
> def card():
> value=random.randint(0,12)
> suit=random.randint(0,3)
> return [suit,value]
>
> while (c<cards):
> new_card=card()
> if new_card not in dealt:
> dealt.append(new_card)
> c=c+1
> else: pass
Although this will work, there's another way to approach this problem. We
can construct the whole deck as a list of [value/suit] pairs:
###
def makeDeck():
values=['2','3','4','5','6','7','8','9','10',
'Jack','Queen','King','Ace']
suits=['Hearts','Spades','Diamonds','Clubs']
deck = []
for v in values:
for s in suits:
deck.append([v, s])
return deck
###
Let's see how this will work:
###
>>> makeDeck()
[['2', 'Hearts'], ['2', 'Spades'], ['2', 'Diamonds'], ['2', 'Clubs'],
['3', 'Hearts'], ['3', 'Spades'], ['3', 'Diamonds'], ['3', 'Clubs'],
# [... lots and lots of cards.]
>>> len(makeDeck())
52
###
So that sounds like the right number of cards. Then all we'd need to do
to draw new cards is to pull out a random card from the deck with
random.choice().
###
>>> deck = makeDeck()
>>> random.choice(deck)
['3', 'Spades']
>>> random.choice(deck)
['8', 'Hearts']
>>> random.choice(deck)
['King', 'Clubs']
###
(Note: the above might be buggy because it's as if we take a random card
from the deck, but then put it right back into the deck. We need to
actually _pull_ our choice out of the deck; otherwise, we'll hit
duplicates.)
So this might lead to an easier way of generating hands, and you even get
a fully contructed deck too.
Good luck!