2011-05-07 97 views
1

我正在做一個洗牌程序。最後我用for loop打印出10張隨機卡,但我不知道它有什麼問題。需要我的洗牌方案幫助

在結束deal_card(card),爲什麼我把card因爲我的H/W這麼說,但如果你有其他的答案我會好好聽你說什麼。

這是我的計劃:

import random 

def define_cards(): 
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king") 
    suit_string = ("clubs","diamonds","hearts","spades") 
    cards = [] 
    for suit in range(4): 
     for rank in range(13): 
      card_string = rank_string[rank] + " of " + suit_string[suit] 
      cards.append(card_string) 
     return cards 

def create_deck(deck): 
    for i in range(52): 
     deck.append(i) 
     return 

def shuffle_deck(deck): 
    random.shuffle(deck) 
    return 

def deal_card(deck): 
    return deck.pop(0) 

deck=[] 

create_deck(deck) 
shuffle_deck(deck) 
print "The first 10 cards are:" 
for i in range(10):    # I don't know why won't work 
    deal_card(card) 
    print define_cards() 

打印出來chould樣子:

The first 10 cards are: 
queen of hearts 
ten of diamonds 
... 

回答

6

既然你define_cards已經產生卡名稱的列表,你應該用它來生成甲板代替create_deck。然後在for循環中處理一張卡片並打印出來。

deck = define_cards() 
shuffle_deck(deck) 
print "The first 10 cards are:" 
for i in range(10): 
    card = deal_card(deck) 
    print card 

只要做到這一點,程序就會從卡組頂部打印十張卡片。但是,define_cards仍然有一個小錯誤。你能發現它嗎?提示:定位return。代碼

+0

是不是應該只有4個空間,與'在範圍內(4)'和在'cards.append(card_string)'或者下面'cards.append(card_string)'whit 12的空間相同級別空間?I嘗試是工作的兩種方式,有什麼不同? – phhnk 2011-05-07 07:31:40

+0

@phhnk:根據縮進情況,'return'要麼在'for'循環中,要麼在兩者之後。在'for'循環完成之後,你會想要它,所以4個空格。在問題中的版本(8個空格)中,您只能看到* clubs *卡片。 – dancek 2011-05-07 07:43:39

+0

哦,我明白了現在怎麼樣了,非常感謝... – phhnk 2011-05-07 08:05:44

3

一半是多餘的:

>>> import random 
>>> deck = range(1,52) 
>>> random.shuffle(deck) 
>>> deck 
[4, 38, 40, 18, 35, 44, 50, 22, 49, 26, 8, 45, 14, 20, 25, 34, 37, 51, 42, 29, 24, 28, 27, 30, 7, 47, 23, 3, 10, 2, 9, 39, 6, 16, 12, 17, 11, 41, 33, 48, 5, 1, 36, 21, 13, 32, 43, 19, 15, 31, 46] 
+2

你的套牌缺少一張卡片... – 2011-05-07 06:55:27

+0

我知道我沒有如此乾淨地回答這個問題,但我仍然感謝你的幫助,tho。謝謝 – phhnk 2011-05-07 07:07:06

1

你可能要考慮創建一個類卡和類甲板保持一副撲克牌。這會給你更清晰的代碼。