2015-10-15 81 views
2

即時學習python(在大學時學過的第一種編程語言是C),並且想要一步一步地寫出一個小小的紙牌遊戲作爲練習。更具體的是關於德州撲克遊戲。在對象中操作列表,再次站在列表中

我寫了一個類cPlayer與所有相關的屬性。

class cPlayer(object): 
    def __init__ (self, id=0, name='', hand=[], credit=1000): 
     self.id=id 
     self.name=name 
     self.hand=hand 
     self.credit=credit 

然後我做了一張撲克牌的清單,並洗牌。

deck=[] 
for i in range(0,4): 
    for j in range(0,13): 
     deck.append([value[j], suit[i]]) 
shuffle(deck) 

另外我有一個列表,其通過一個for循環填充有6 cPlayer

list_of_players=[]  
for i in range(PLAYERS): 
    x=cPlayer() 
    x.id=i+1 
    x.name=i+1 
    for j in range(2): 
     x.hand.append([0,0]) 
    list_of_players.append(x) 

在第一步中,我只是想給每個cPlayer一個hand,這是兩張卡,這又是兩個值(valuesuit)的列表清單。因此,我寫了一個功能:

def deal_hole_cards(): 
    for i in range(2): 
     for j in range(len(list_of_players)): 
      list_of_players[j].hand[i]=deck.pop() 

要檢查我做的一切打印功能。有關的一個是這樣的一個:

def print_hands(): 
    print '==HANDS==' 
    for i in range(len(list_of_players)): 
     print dict_player[list_of_players[i].name] +' ', 
     print_card(list_of_players[i].hand[0]) 
     print_card(list_of_players[i].hand[1]) 
     print '' 

我現在得到的,是這樣的:

output

每個「播放器」,得到了相同的手環後。不知怎的,所有先前的手牌都會被最後一次使用pop()覆蓋。這必須是一個參考問題。但是我該如何解決這個問題,以便每個玩家都有不同的牌?我搜索了一下,發現了一些類似的問題,但找不到合適的解決方案。

注意:對於打印,我翻譯卡片值和玩家名稱通過字典工作正常。

回答

0

所以正如你所指出的,你不應該在你的簽名中使用可變的默認值,但這不是你的主要問題。我認爲你沒有正確解開這些值。你不應該追加,而是覆蓋這些值。 在創建過程中,你應該設置默認:

x.hand = [[0,0], [0,0]] 
list_of_players.append(x) 

並添加彈出甲板上時,使用此方法,而不是附加的:

for j in range(len(list_of_players)): 
    list_of_players[j].hand = [deck.pop(),deck.pop()] 

通過使用附加的,你以爲你是引用相同的列表。

所有版本:

from random import shuffle 

PLAYERS = 6 

class cPlayer(object): 
    def __init__ (self, id=0, name='', hand=[], credit=1000): 
     self.id=id 
     self.name=name 
     self.hand=hand 
     self.credit=credit 


deck = [] 
for i in range(0,4): 
    for j in range(0,13): 
     deck.append([i,j]) 

shuffle(deck) 

list_of_players = [] 
for i in range(PLAYERS): 
    x=cPlayer() 
    x.id=i+1 
    x.name=i+1 
    x.hand = [[0,0], [0,0]] 
    list_of_players.append(x) 


def deal_hole_cards(): 
    for j in range(len(list_of_players)): 
     list_of_players[j].hand = [deck.pop(),deck.pop()] 


deal_hole_cards() 

for i in list_of_players: 
    print i.id, i.hand 

輸出:

1 [[0, 12], [0, 7]] 
2 [[3, 9], [1, 1]] 
3 [[1, 6], [3, 3]] 
4 [[3, 5], [2, 9]] 
5 [[2, 3], [1, 5]] 
6 [[1, 11], [2, 4]] 

我知道我錯過了統一的東西,但是這應該是微不足道的。

+0

非常感謝!將「x.hand.append([0,0])」更改爲「x.hand = [[0,0],[0,0]]」是正確的解決方案。 – Maarrco