即時學習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
,這是兩張卡,這又是兩個值(value
和suit
)的列表清單。因此,我寫了一個功能:
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 ''
我現在得到的,是這樣的:
每個「播放器」,得到了相同的手環後。不知怎的,所有先前的手牌都會被最後一次使用pop()
覆蓋。這必須是一個參考問題。但是我該如何解決這個問題,以便每個玩家都有不同的牌?我搜索了一下,發現了一些類似的問題,但找不到合適的解決方案。
注意:對於打印,我翻譯卡片值和玩家名稱通過字典工作正常。
非常感謝!將「x.hand.append([0,0])」更改爲「x.hand = [[0,0],[0,0]]」是正確的解決方案。 – Maarrco