Reputation: 13
This is my first StackOverflow post, so please tell me if I have done anything wrong!
I am trying to make a card game in python and have been told that using a class based system would be best.
Whilst trying to do so, when putting all the cards into a deck, the classes seem to duplicate the values onto the board.cards part of the code.
#definitions and imports
import random
class Card:
suit = ""
base = ""
class Hand:
cards = []
poweri = 0
powerii = 0
class Stack:
cards = []
#instantiates classes
deck = Stack()
board = Stack()
player = Hand()
dealer = Hand()
#creates ordered empty deck
def newdeck(obj):
for x in ["2","3","4","5","6","7","8","9","A","B","C","D","E"]:
for y in ["C","D","H","S"]:
card = Card()
card.base = x
card.suit = y
obj.cards.append(card)
#shuffles deck
def shuffle():
random.shuffle(deck.cards)
newdeck(deck)
#disabled to make debug easier
#shuffle()
#prints entire deck
print("\nDeck")
for i in range(len(deck.cards)):
print(deck.cards[i].base, deck.cards[i].suit)
print(len(deck.cards))
#prints entire board
print("\nBoard")
for i in range(len(board.cards)):
print(board.cards[i].base, board.cards[i].suit)
The program returns this:
Deck
2 C
2 D
2 H
2 S
3 C
3 D
3 H
3 S
4 C
4 D
4 H
4 S
5 C
5 D
5 H
5 S
6 C
6 D
6 H
6 S
7 C
7 D
7 H
7 S
8 C
8 D
8 H
8 S
9 C
9 D
9 H
9 S
A C
A D
A H
A S
B C
B D
B H
B S
C C
C D
C H
C S
D C
D D
D H
D S
E C
E D
E H
E S
52
Board
2 C
2 D
2 H
2 S
3 C
3 D
3 H
3 S
4 C
4 D
4 H
4 S
5 C
5 D
5 H
5 S
6 C
6 D
6 H
6 S
7 C
7 D
7 H
7 S
8 C
8 D
8 H
8 S
9 C
9 D
9 H
9 S
A C
A D
A H
A S
B C
B D
B H
B S
C C
C D
C H
C S
D C
D D
D H
D S
E C
E D
E H
E S
Process returned 0 (0x0) execution time : 0.314 s
Press any key to continue . . .
Board should be empty???
Regards, Alex
Upvotes: 1
Views: 51
Reputation: 378
The Stack.cards
is a mutable class attribute. That means, all class instances will have reference to the same object with the same data.
You probably want each object to have its own data. To change it, instantiate cards
within __init__()
method:
class Stack:
def __init__(self):
self.cards = []
Upvotes: 1