class Deck(object):
def __init__(self,starting_cards = None):
self._cards = starting_cards
def get_cards(self):
if self._cards==None:
return []
else:
return self._cards
def add_cards(self,new_cards):
if self._cards == None:
self._cards = []
self._cards.extend(new_cards)
else:
self._cards.extend(new_cards)
class Player(object):
def __init__(self,name):
self._name= name
def get_deck(self):
return Deck()
So if I input:
a = Player('a')
b = [1,2,3,4]
a.get_deck.add_cards(b)
a.get_deck.get_cards
It just return [], but is should be [1,2,3,4], why?
But if I change
'def init(self,starting_cards = None):'
to
'def init(self,starting_cards = []):'
it could give the '[1,2,3,4]'
That's because you always returned new Deck instance in get_deck() function.
You should have Deck instance as member variable of Player.
It seems like you're never storing a players deck. Every time you call getDeck it looks to be creating a new deck object.
Second Aran-Fey's comment. Your get_deck function returns a deck, so callinga.get_deck.add_cards(b) will first return a deck, and add b cards to this deck, but this deck is not stored anywhere.
You could do
xyqrz = a.get_deck() then xyqrz.add_cards(b) and call xyqrz.get_cards().
Related
I'm trying to pass a class object as an argument to a global function.
Here's the function:
def CreatePlayers(p1_Name, p2_Name, cardDeck):
#Function to Create Players
#Takes 3 variables: Names of player 1 and player 2 and the card deck
#Returns a List of players [p1,p2]
print("Creating Players... \n")
print(f"Dealing a deck of ", len(cardDeck), " among 2 players")
player1 = Player(p1_Name)
player2 = Player(p2_Name)
#Share cards between players
for i in range(25):
player1.addCard(cardDeck.dealOne())
player2.addCard(cardDeck.dealOne())
print("Verify... player creation\n")
print(player1)
print(player2)
return [player1, player2]
The class object here's "cardDeck", and the class object is initialized before making the function call with the variable name, of course
And here's the class definition:
class Deck:
'''A Python Deck class. Holds a list of Card objects
Possesses the following
* Attributes: - myDeck (A list of cards. Expected = 50 cards in deck)
* Methods: - Constructor (creates list)
- Shuffle
- Deal a card
- return number of cards
'''
def __init__(self):
'''Method to initialize a deck'''
self.myDeck = []
#initialize cards
for rank in Ranks:
for order in Orders:
self.myDeck.append( Card(order, rank) )
##other functions....
def __len__(self):
'''Return the size of the card deck'''
return len(self.myDeck)
This is where I call my createPlayer() function:
myDeck = Deck().shuffle()
#Create my players
players = CreatePlayers("Adam", "Bob", myDeck)
And finally here's the error that I keep getting while running the 'createPlayer' function
File "/home/CardGame.py", line 32, in CreatePlayers
print(f"Dealing a deck of ", len(cardDeck), " among 2 players")
TypeError: object of type 'NoneType' has no len()
Deck().shuffle() doesn't return the deck
you can do this to solve it :
myDeck = Deck();
myDeck.shuffle();
players = CreatePlayers("Adam", "Bob", myDeck)
an other alternative is to change shuffle to be a class method :
class Deck:
def __init__(self):
...
#classmethod
def shuffle(cls):
new_deck = cls()
# Do shuffle here for new_deck
return new_deck
and use it that way :
myDeck = Deck.shuffle();
players = CreatePlayers("Adam", "Bob", myDeck)
but that way you can't shuffle an existing deck so it depend on what you want to do.
I am working on a texas hold-em game in python, and am looking to traverse an array containing a complete hand of 7 cards (2 in the hole + 5 on the board). The array contains elements of class Cards, where the Card class constructor is
class Card:
def __init__(self, suit, val):
self.suit = suit
self.value = val
So, I have a "hand" array within a "Player" class of 7 random cards, where the suit is one of 4 strings (spade, club, heart, diamond) and the value is one of 9 numbers (2-10) or 4 strings (jack-ace). I want to traverse the array to check if the list contains any of the hands in poker, but I'm failing to figure out how I can "extract" the suit/value of the cards from my array. I've started a method within my "Player" class to check for a suit, here that suit is a spade.
class Player:
def __init__(self, name):
self.name = name
self.pocket = []
self.hand = []
def spadeChecker(self):
card = Card("Blank", 0)
for i in self.hand:
card = self.hand[i]
if(card.suit == "Spade"):
print("Hi! you have a spade!")
else:
pass
When running the program from my terminal I receive a TypeError message:
in spadeChecker card = self.hand[i] TypeError: list indices must be integers or slices, not Card
I know my method is pretty bad but I'm very new to this and just can't figure out how to get it to work. Any advice?
Thanks
Here is the rewritten method, including an example with a 3 card hand.
class Card:
def __init__(self, suit, val):
self.suit = suit
self.value = val
class Player:
def __init__(self, name):
self.name = name
self.pocket = []
self.hand = [Card("Heart", 10), Card("Spade", 10), Card("Diamond", 10)]
def spadeChecker(self):
for card in self.hand:
if(card.suit == "Spade"):
print("Hi! you have a spade!")
#return True
else:
#return False
pass
p = Player("Bob")
p.spadeChecker()
Output is:
Hi! you have a spade!
In your code, your iterator is i and your iterable is self.hand, which is a list of Card objects. Thus, i will be a Card object each time the loop iterates. If you want to be able to get the index of the Card object as well as the Card object itself, I recommend using the enumerate() function. However, since you only reference the Card objects, you can just get the suit attribute directly.
class Player:
def __init__(self, name):
self.name = name
self.pocket = []
self.hand = []
def spadeChecker(self):
card = Card("Blank", 0)
for card_obj in self.hand:
if(card_obj.suit == "Spade"):
print("Hi! you have a spade!")
else:
pass
There's a Python library for generating, comparing & evaluating poker hands called tilted which can be found here: https://github.com/MaxAtkinson/tilted
I've used it myself before and it's really easy. This may allow you to avoid having to implement it yourself.
Originally I had 2 files, one named "cards" and one named "decks". The cards file contain the definition of the cards class and was imported into the "decks" file. In the decks files was the definition of the deck object. After defining the deck object, I would test the class in the lines below by typing something like "deck = deck()" and everything would work.
After verifying everything, I wanted to move the deck definition into the "cards" file, to create a library that would contain both the "card" and "deck" class definitions. However after doing this, running "deck = deck()" failed, giving the following error. This happens even if I run the "deck = deck()" line in the bottom of the cards file, or if I import cards an run in a separate file.
"card = card(name = name_of_card,suit = card_suit,value = 0)
UnboundLocalError: local variable 'card' referenced before assignment"
Below is the cards file code:
import random
class card:
def __init__(self, name, suit, value):
self.name = name
self.suit = suit
self.value = value
class deck:
def __init__(self, contents = [], num_cards = 0):
self.contents = contents
self.num_cards = num_cards
self.generate()
def generate(self):
card_values = ['Ace', *range(2,11,1),'Jack', 'Queen', 'King']
suits = ['Hearts','Clubs','Diamonds','Spades']
for i in suits:
card_suit = str(i)
for n in card_values:
name_of_card = str(n) + " of " + card_suit
card = card(name = name_of_card,suit = card_suit,value = 0)
self.contents.append(card)
self.num_cards += 1
def shuffle(self):
random.shuffle(self.contents)
def print_contents(self):
for i in self.contents:
print(i.name)
def draw_card(self):
card_drawn = self.contents[0]
self.contents.pop(0)
return card_drawn
def reveal(self,num_to_reveal = 1,from_top = True):
for i in range(0,num_to_reveal,1):
if from_top == True:
print(self.contents[i].name)
else:
print(self.contents[-1-i].name)
def return_to_deck(self,card, position = 0):
self.contents.insert(position,card)
deck = deck()
You're using the same name for the class card and for the object you create for it. Your code will work if you use different names. Typically classes have names starting with a capitol letter, so I'd suggest class Card and then later, card = Card(name=name_of_card,suit=card_suit,value = 0).
Below is a class of a deck of cards from 'Fluent Python' by Luciano Romalho.
I hope it's ok that I have copied the code, I really don't have a better more concise class example than this one.
import collections
from random import choice
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
so, an instance of this class will have 52 cards, each a namedtuple as defined in 'Card' object.
I wanted to draw a hand of n cards so that it will reflect in the deck.
I tried the following:
def a_hand(deck, size):
the_hand = []
for n in range(size):
c = choice(deck)
the_hand.append(c)
deck = [i for i in deck if i != c]
return the_hand
so when I try:
>> deck = FrenchDeck()
>> a = a_hand(deck, 5)
I get a hand but the deck is untouched:
>> hand
[Card(rank='9', suit='spades'),
Card(rank='A', suit='hearts'),
Card(rank='2', suit='diamonds'),
Card(rank='8', suit='clubs'),
Card(rank='10', suit='hearts')]
>> len(deck)
52
when I try directly in the interperter:
>> c = choice(deck)
>> alt = [i for i in deck if i != c]
it works:
>> len(alt)
51
I understand that this is due to the FrenchDeck's instance not being affected by what is happening in the scope of the function a_hand.
What would be the way to do it? I tried to define a dunder-delitem function in the class but didn't get it right, also wasn't sure if this was the right function to use and whether it was to be defined in the Card object or in the FrenchDeck object.
Really you just need to move a_hand to be a method of FrenchDeck:
class FrenchDeck:
# All previous code here, plus:
def a_hand(self, size):
the_hand = []
for n in range(size):
c = choice(self._cards)
the_hand.append(c)
self._cards.remove(c)
return the_hand
You're right that it's due to the fact that FrenchDeck instance is not modified inside a_hand function. Instead, you only override deck variable. To achieve your goal, you could e.g. add deal_hand method to FrenchDeck class, that will return a hand of given size and remove selected cards from deck itself.
You create a new deck instead of updating the existing deck.
deck = [i for i in deck if i != c]
This creates a new list, built by the list comprehension, and makes deck point to it, instead of pointing at the original list that was passed.
You need is to use deck.remove(...) if you are to alter the existing list.
(Also: try making the deck and hands sets, not lists. It matches the domain better.)
When you get a card from the deck, also remove it from the deck. Use list.pop in __getitem__.
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
print(f'__len__ called: {len(self._cards)}')
return len(self._cards)
def __getitem__(self, position):
print(f'getting item {position}')
return self._cards.pop(position)
def a_hand(deck, size):
the_hand = []
for n in range(size):
print('getting another card')
c = choice(deck)
the_hand.append(c)
return the_hand
deck = FrenchDeck()
a = a_hand(deck, 5)
I am working on creating a class for the first time, and I am thinking that I have done every thing to get it run, but I still get bunch of issues which is 'list' object has no attribute 'shffule' so the problem here is it will not shuffle the cards, and it will not tell the remaining cards, can any one tell me what am I doing wrong? Thanks in advance
import random
class card_deck:
def __init__(self, rank, suite, card):
self.rank= rank
self.suite = suite
def ranks(self):
return self.rank
def suites(self):
return self.suite
def cards(self,card):
suit_name= ['The suit of Spades','The suit of Hearts', 'The suit of Diamonds','Clubs']
rank_name=['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
def value(self):
if self.rank == 'Ace':
return 1
elif self.rank == 'Jack':
return 11
elif self.rank == 'Queen':
return 12
elif self.rank == 'King':
return 13
def shffule(self):
random.shuffle(self.cards)
def remove(self,card):
self.cards.remove(card)
def cardremaining(self):
self.suite-self.rank
def main():
try:
deck=[]
for i in ['Spades','Hearts', ' Diamonds','Clubs']:
for c in ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']:
deck.append((c, i))
deck.shffule
hand = []
user =eval(input('Enter a number of cards: 1-7 '))
print()
while user <1 or user >7:
print ("Only a number between 1-7:")
return main()
for i in range(user):
hand.append(deck[i])
print (hand)
except ValueError:
print("Only numbers")
main()
Apart from your code containing many small errors; I will try to answer your main problems.
If you are going to use shffule[sic] method of card_deck class, then you first need to create an instance of that class(whereas you tried to call that method with a list). Like this:
deck = card_deck(some_rank,some_suit,some_card)
deck.shffule() #Now you can call the method
Now, since you made it a class instance, you cannot get items from it like hand.append(deck[i])
Unless you defined the method __getitem__ in your class definition, like this:
#this will be in your class definition
def __getitem__(self,i):
return self.card_list[i] #Of course you have to define a list of cards in your class too.
In my opinion, you should spend a little more time trying to understand how is a class defined, how does methods work and how to access members of a class. After that you will be doing much better here
You are never actually creating an instance of the card_deck class. The expression
deck=[]
creates a variable named deck referring to an empty list.
In python, [a, b, c,...] is the syntax for creating list literals.
from collections import namedtuple
Card = namedtuple('Card', 'sign, value') # no need to write class to represent card
SIGNS = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
class Deck:
def __init__(self):
self.cards = [Card(sign, value) for sign in SIGNS for value in range(2,
11) +
'J Q K A'.split()]
def __repr__(self):
return str([str(card) for card in self.cards])
def __len__(self):
return len(self.cards)
def __getitem__(self, item):
return self.cards[item]
def __setitem__(self, key, value):
self.cards[key] = value
deck = Deck()
print deck[11] # indexing works, prints Card(sign='Hearts', value='K')
print len(deck) # prints 52
print deck[13:16] # slicing works
import random
random.shuffle(deck) # shuffle works using no extra code