1

I am making a game using pygame based on the game war. I am getting an error when running the code for splitting my deck in the main loop (it is in its own file). The error says:

"/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

The deck splitting file looks like this:

import Deck
from random import *
deck = Deck.deck
playerDeck = []
AIDeck = []

def splitDeck():
    player_deck_count = 26

    while player_deck_count > 0:

        transfer_card = (choice(deck))

        playerDeck.append(transfer_card)
        deck.remove(transfer_card)

        player_deck_count -= 1

    AIDeck = deck
    shuffle(playerDeck)
    shuffle(AIDeck)


print "Player deck length:" + str(len(playerDeck))
print "AI deck length:" + str(len(AIDeck))
print "Deck length:" + str(len(deck))

The Deck file looks like this:

deck = [
    '2_c',
    '2_d',
    '2_h',
    '2_s',

I get that is has to do with the sequence (list is empty) but there is obviously still 26 cards in the original deck. I have tried changing when the while player_deck_count loop stops but with no luck. Thanks for the help in advance

P.S. just comment if you want the main loop.

sloth
  • 99,095
  • 21
  • 171
  • 219
  • use `return random.choice(seq)`. See this [SO QA](http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python) – Pynchia Oct 30 '15 at 08:40
  • 1
    `shuffle(deck);playerDeck=deck[:26];AIDeck=deck[26:]` – gboffi Oct 30 '15 at 09:28

1 Answers1

0

I believe your problem is that you are relying on the function to set the value of AIDeck. When you attempt to set

AIDeck = deck

you are moving the reference of AIDeck to the reference of deck. When the function returns, AIDeck is restored to its original definition, which was the empty list. If you are doing choice(AIDeck) anywhere in your file, it is probably the cause of your error.

BallpointBen
  • 9,406
  • 1
  • 32
  • 62