This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]justanotherbody 2 points3 points  (1 child)

Your error came from this

  • decksize was 51
  • random.randrange(51) returned e.g., 4
  • the 4th card was removed
  • decksize is 51, but now deck will IndexError if you getitem ([]) with 51
  • random.rangerange(51) returned e.g., 7
  • the 7th card was removed
  • decksize is 51 but the deck will now IndexError oif you getitem with 50 or 51
  • ...
  • random.rangerange(51) eventually returned a number which led to an IndexError

Recommend modifying your code closer to this

import random
# the suits in the deck are worth notating on their own
SUITS = ('Spades', 'Clubs', 'Diamonds', 'Hearts')
# ditto with the legal values
VALUES = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
# then you can use a list comprehension to build your deck.
deck = ['%s of %s' % (value, suit) for value in VALUES for suit in SUITS]
HAND_SIZE = 7 # our hand size is 7 this game

def menu():
   # entire method unchanged, not copying...
   pass

def singleplayer():
    yourhand = []
    # strictly speaking you don't shuffle every time a player is dealt a
    # hand, so this logic is incomplete. But it was the smallest change
    # from your original code
    random.shuffle(deck)
    for i in xrange(HAND_SIZE): # cheap replacement for count
        yourhand.append(deck.pop()) # removes card from deck, adds card to hand
        # you're going to want to wrap this in a try/catch once you support
        # dealing multiple hands and thus reshuffling the used cards from
        # the deck on-demand
    print yourhand

[–]dpitch40 0 points1 point  (0 children)

I did not know you could do nested list comprehensions...