2015-10-15 76 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