python - Manipulating lists in objects, which again stand in a list -
this question has answer here:
im new @ learning python (first programming language learned @ university c) , want write little card-game step step practice. more it's texas holdem poker game.
i wrote class cplayer
relevant attributes.
class cplayer(object): def __init__ (self, id=0, name='', hand=[], credit=1000): self.id=id self.name=name self.hand=hand self.credit=credit
then made list of playing cards, , shuffled it.
deck=[] in range(0,4): j in range(0,13): deck.append([value[j], suit[i]]) shuffle(deck)
further have list, filled 6 cplayer
via for-loop.
list_of_players=[] in range(players): x=cplayer() x.id=i+1 x.name=i+1 j in range(2): x.hand.append([0,0]) list_of_players.append(x)
in first step, want give each cplayer
hand
, list of 2 cards, again list of 2 values (value
, suit
). therefor wrote function:
def deal_hole_cards(): in range(2): j in range(len(list_of_players)): list_of_players[j].hand[i]=deck.pop()
to check made print functions. relevant 1 one:
def print_hands(): print '==hands==' 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 ''
what now, this:
each "player" gets same hand after loop. somehow previous hands overwritten last latest use of pop()
. must reference problem. how can fix it, each player has different hand of cards? googled , found similiar problems couldn't find right solution me.
note: prints translate card-values , player-names via dictionaries work fine.
so noted should not use mutable default value in signature, not main problem. think not unpacking values correctly. should not append, overwrite values. during creation should set default:
x.hand = [[0,0], [0,0]] list_of_players.append(x)
and when adding popping deck, use method instead of append:
for j in range(len(list_of_players)): list_of_players[j].hand = [deck.pop(),deck.pop()]
by using append referencing same list thought.
whole version:
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 = [] in range(0,4): j in range(0,13): deck.append([i,j]) shuffle(deck) list_of_players = [] 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(): j in range(len(list_of_players)): list_of_players[j].hand = [deck.pop(),deck.pop()] deal_hole_cards() in list_of_players: print i.id, i.hand
output:
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]]
i know i'm missing unicode stuff, should trivial.
Comments
Post a Comment