2015-10-30 126 views
1

我正在使用基於遊戲戰爭的pygame製作遊戲。我在運行用於在主循環中分割我的套牌的代碼時發生錯誤(它在它自己的文件中)。錯誤說:隨機選擇功能

"/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 

甲板分割文件看起來是這樣的:

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)) 

甲板上的文件看起來是這樣的:

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

我得到的是有順序做(名單是空的),但在原來的套牌中顯然還有26張牌。當player_deck_count循環停止但沒有運氣的時候,我試圖改變它。感謝您的幫助提前

P.S.只是評論你是否想要主循環。

+0

使用'return random.choice(seq)'。看看這個[SO QA](http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python) – Pynchia

+1

'shuffle(deck); playerDeck = deck [:26]; AIDeck = deck [26:]' – gboffi

回答

0

我相信你的問題是你依賴於函數來設置AIDeck的值。當您嘗試設置

AIDeck = deck 

要移動的AIDeckdeck參考參考。當函數返回時,AIDeck恢復到原來的定義,即空列表。如果你在文件的任何地方都在做choice(AIDeck),這可能是你錯誤的原因。

+0

我不是在做'choice(AIDeck)' – Paradizigmania

+0

在任何情況下,即使在調用'splitDeck()'後,'AIDeck'都將成爲空套牌。 – BallpointBen