Can't remove card from Euchre hand in Python - python

I'm trying to program the card game Euchre in Python and I'm running into some errors with it. I'll post my code below and then explain my current problem:
import random
class Card(object):
'''defines card class'''
RANK=['9','10','J','Q','K','A'] #list of ranks & suits to make cards
SUIT=['c','s','d','h']
def __init__(self,rank,suit):
self.rank=rank
self.suit=suit
def __str__(self):
rep=self.rank+self.suit
return rep
#Next four definitions haven't been used yet. Goal was to use these
#to define a numerical vaule to each card to determine which one wins the trick
def getSuit(self):
return self.suit
def value(self):
v=Card.RANK.index(self.rank)
return v
def getValue(self):
print(self.value)
def changeValue(self,newValue):
self.value=newValue
return self.value
class Hand(object):
def __init__(self):
self.cards=[]
def __str__(self):
if self.cards:
rep=''
for card in self.cards:
rep+=str(card)+'\t'
else:
rep="EMPTY"
return rep
def clear(self):
self.cards=[]
def add(self,card):
self.cards.append(card)
def give(self,card,other_hand):
self.cards.remove(card)
other_hand.add(card)
def remove(self,card):
self.cards.remove(card)
class Deck(Hand):
def populate(self):
for suit in Card.SUIT:
for rank in Card.RANK:
self.add(Card(rank,suit))
def shuffle(self):
random.shuffle(self.cards)
def reshuffle(self):
self.clear()
self.populate()
self.shuffle()
def deal(self,hands,hand_size=1):
for rounds in range(hand_size):
for hand in hands:
if self.cards:
top_card=self.cards[0]
self.give(top_card,hand)
else:
print("Out of cards.")
#These two are the total scores of each team, they haven't been used yet
player_score=0
opponent_score=0
#These keep track of the number of tricks each team has won in a round
player_tricks=0
opponent_tricks=0
deck1=Deck()
#defines the hands of each player to have cards dealt to
player_hand=Hand()
partner_hand=Hand()
opp1_hand=Hand()
opp2_hand=Hand()
trump_card=Hand() #This is displayed as the current trump that players bid on
played_cards=Hand() #Not used yet. Was trying to have played cards removed from
#their current hand and placed into this one in an attempt to
#prevent playing the same card more than once. Haven't had
#success with this yet
hands=[player_hand,opp1_hand,partner_hand,opp2_hand]
deck1.populate()
deck1.shuffle()
print("\nPrinting the deck: ")
print(deck1)
deck1.deal(hands,hand_size=5)
deck1.give(deck1.cards[0],trump_card)
def redeal(): #just to make redealing cards easier after each round
player_hand.clear()
partner_hand.clear()
opp1_hand.clear()
opp2_hand.clear()
trump_card.clear()
deck1.reshuffle()
deck1.deal(hands,hand_size=5)
deck1.give(deck1.cards[0],trump_card)
print("\nPrinting the current trump card: ")
print(trump_card)
while player_tricks+opponent_tricks<5:
#Converts players hand into a list that can have its elements removed
Player_hand=[str(player_hand.cards[0]),str(player_hand.cards[1]),str(player_hand.cards[2]),\
str(player_hand.cards[3]),str(player_hand.cards[4])]
print("\nYour hand: ")
print(Player_hand)
played_card=str(raw_input("What card will you play?: "))#converts input into a string
if played_card==Player_hand[0]: #crudely trying to remove the selected card
Player_hand.remove(Player_hand[0]) #from player's hand
if played_card==Player_hand[1]:
Player_hand.remove(Player_hand[1])
if played_card==Player_hand[2]:
Player_hand.remove(Player_hand[2])
if played_card==Player_hand[3]:
Player_hand.remove(Player_hand[3])
if played_card==Player_hand[4]: #received the 'list index out of range' error
Player_hand.remove(Player_hand[4]) #here. Don't know why this is an error since
#Player_hand has 5 elements in it.
opp1_card=opp1_hand.cards[0] #just having a card chosen to see if the game works
#will fix later so that they select the best card
#to play
partner_card=partner_hand.cards[0]
opp2_card=opp2_hand.cards[0]
print("First opponent plays: ")
print(opp1_card)
print("Your partner plays: ")
print(partner_card)
print("Second opponent plays: ")
print(opp2_card)
trick_won=[0,1] #Just used to randomly decide who wins trick to make sure score is
#kept correctly
Trick_won=random.choice(trick_won)
if Trick_won==0:
print("\nYou win the trick!")
player_tricks+=1
if Trick_won==1:
print("\nOpponent wins the trick!")
opponent_tricks+=1
if player_tricks>opponent_tricks:
print("\nYou win the round!")
if opponent_tricks>player_tricks:
print("\nOpponont wins the round!")
print("\nGOOD GAME") #Just to check that game breaks loop once someone wins the round
So far what I'm able to accomplish is have a deck created and each of the four players be dealt a five card hand and then have the player asked what card they would like to play. Once they play a card, the other three players (two opponents and a partner) play their cards and then I randomly decide who wins the "trick" just to see if the score is being kept correctly.
The current problem I'm trying to tackle is that once a player plays a card and the trick is played out, on the next trick they should have one less card in their hand when it's displayed but I'm not able to remove the card that was previously played so the player will still have five cards in their hand.
Do any of you know what I'm doing wrong and how I can have the selected card removed? Thanks for any help.

The IndexError you're getting is because you're using multiple ifs instead of elif.
if played_card==Player_hand[0]:
Player_hand.remove(Player_hand[0])
# The next if is still evaluated, with the shortened Player_hand
if played_card==Player_hand[1]:
Player_hand.remove(Player_hand[1])
use:
if played_card==Player_hand[0]:
Player_hand.remove(Player_hand[0])
elif played_card==Player_hand[1]:
Player_hand.remove(Player_hand[1])
But yeah, use those classes you made, and use __eq__ to compare.

Related

Python Blackjack Project Type Error: Chips.place_bet() missing 1 required positional argument

I am trying to write my first python project blackjack. I was advised to write the program with each class and its methods in a different file so that the code would be more manageable. I divided my code up into smaller files and used import statements.
When I run my code I get the following error message:
Chips.place_bet() missing 1 required positional argument. self.
I thought self was, pardon the pun, self explanatory. I do not need to put a value for self. I am wondering if this is an import issue.
I am trying to get my place_bet function to activate so that I can ask the user to input the number of chips for a bet. Can anyone advise me on how to do this?
My code is spread over these files:
blackjack.py
import random
from player import Player
from hand import Hand
from chips import Chips
from deck import Deck
from card import Card
# import helper_functions
# Blackjack/
# ├── app/
# │ ├── card.py
# │ ├── chips.py
# │ ├── deck.py
# │ ├── hand.py
# │ ├── player.py
# │ ├── main.py
# │ ├── helper_functions.py
# Gameplay and Outline of Project
# Welcome message and rules
print("Welcome to Blackjack! The rules for blackjack can be found here. https://www.youtube.com/watch?v=PljDuynF-j0")
print("The object of this blackjack game is to make it to 100 chips. You will start with 25 chips.")
# Establish player name
print("Please insert your player name: ")
player_name = input()
print('Please insert your player name ' + player_name)
print("Lets get started" + player_name + "please place your bet!")
# Place the bets BEFORE the cards are dealt. Pure risk.
place_bet()
# . Deal 2 cards to user and dealer
# . print a message explaining the total hand value of the user. ask player to hit/stay?
# . If the player busts print player busts. if the player is under 21 ask them again to hit or stay.
# . If stay, move on to dealers turn.
# . If the hand is less than 17 have him hit, if it is over 17 have the dealer stay.
# . If the dealer stays print the dealers hand total. IF the dealers hand total is greater than the player the dealer wins.
# . if the dealer busts print the message he busts and the player wins and the player gets the chips.
# 1. Ask dealer to hit/stay?
# 2. If hit, deal 2 cards
# 3. If broke or blackjack deliver message
# 4. If stay, compare hands
# 5. If users hand is closer to 21, (user wins)
# 6. If dealers hand is closer to 21, (user loses)
def main():
player = Player('strikeouts27', 500,)
dealer = Player()
player_chips = Chips()
dealer_chips = Chips()
cards = Card()
deck = Deck()
if __name__ == '__main__':
main()
card.py
class Card:
"""Card class"""
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
return f'{self.__class__.__name__}(rank={self.rank}, suit={self.suit})'
class Chips:
"""Chip class manages chip balance"""
def __init__(self, balance):
self.balance = balance
self.bet = 0
def place_bet(self):
while True:
total = input(f'How much do you bet? (1-{self.balance}):\n> ')
# return True if a digit string. false otherwise. hover over the method for visual studio code to show you.
if not total.isdigit():
continue
total = int(total)
if total > self.balance:
print('You do not have enough')
continue
return total
def add_value(self, value):
"""Add value to chip total"""
self.balance += value
def deduct_value(self, value):
"""Deduct value from chip total"""
self.balance -= value
def display_chips(player, dealer):
print(f'player chips: ${player.chips.balance}')
print(f'dealer chips: ${dealer.chips.balance}')
# Displays player and dealer chip count
class.py
class Card:
#"""Card class"""
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
return f'{self.__class__.__name__}(rank={self.rank}, suit={self.suit})'
deck.py
class Deck:
"""Deck class, represents 52 cards"""
def __init__(self):
self.ranks = [str(n) for n in range(2, 11)] + list('jqka')
self.suits = ["hearts", "diamonds", "clubs", "spades"]
self.cards = [Card(rank, suit)
for suit in self.suits for rank in self.ranks]
random.shuffle(self.cards)
# dunder method rewrites what pythons default method to show better information about itself.
def __repr__(self):
return f'{self.__class__.__name__}({self.cards})'
def __len__(self):
return len(self.cards)
def __getitem__(self, item):
return self.cards[item]
def shuffle(self):
"""shuffles deck of cards"""
random.shuffle(self.cards)
hand.py
class Hand:
"""Hand class to hold the cards for the player and the dealer"""
def __init__(self, cards=None):
self.cards = [] if cards is None else cards
self.value = 0
self.aces = 0
def add_to_hand(self, card):
"""Adds a cards to self.cards."""
self.cards.append(card)
def display_hand(self):
hashtable = {'hearts': 9829, 'diamonds': 9830,
'spades': 9824, 'clubs': 9827}
return [[i.rank, chr(hashtable.get(i.suit))] for i in self.cards]
def display_hand_two(player, dealer):
# Displays player and dealer hand
print(
f'players Hand: {player.hand.display_hand()} --> total {player.total}')
print(
f'dealer Hand: {dealer.hand.display_hand()} --> total {dealer.total}')
player.py
class Player:
"""Player class"""
def __init__(self, name, chips, hand):
self.name = name
self.chips = chips
self.hand = hand
#property
def total(self):
"""Returns the value of the cards. Face cards equal 10, aces can equal
11 or 1, this function picks best case"""
value = 0
aces_count = 0
# Each card is a tuple in a list:
cards = [card for card in self.hand.cards]
for card in cards:
if card.rank == 'a':
aces_count += 1
elif card.rank in 'kqj':
# Face cards are worth 10 points
value += 10
else:
# Numbered cards are worth their value.
value += int(card.rank)
# Add value of aces - 1 per ace
value += aces_count
for i in range(aces_count):
# If another 10 can be added,then do it!
if value + 10 <= 21:
value += 10
return value
#staticmethod
def get_move():
"""returns player choice to hit or stand"""
move = input('>>> (H)it, (S)tand ?:\n> ').lower()
return move
def main():
# Instantiate Deck
deck = Deck()
# shuffle deck
deck.shuffle()
# Instantiate player and dealer chips
player_chips = Chips(500)
dealer_chips = Chips(500)
while True:
# Instantiate player and dealer hand
player_hand = Hand()
dealer_hand = Hand()
# Instantiate player and dealer
player = Player('seraph', player_chips, player_hand)
dealer = Player('codecademy', dealer_chips, dealer_hand)
# Check if player has enough money
if player_chips.balance <= 0:
print('need more money')
# Then place bet
bet = player_chips.place_bet()
# player draws 2 cards
player.hand.add_to_hand(deck.cards.pop())
player.hand.add_to_hand(deck.cards.pop())
# Dealer draws cards
dealer.hand.add_to_hand(deck.cards.pop())
dealer.hand.add_to_hand(deck.cards.pop())
# display player ann dealers hand
display_hand(player, dealer)
# Begin game
while True:
if player.total > 21:
break
# Get the player's moves
player_move = player.get_move()
if player_move == 'h':
new_card = deck.cards.pop()
rank, suit = new_card.rank, new_card.suit
player.hand.add_to_hand(new_card)
print(f'You drew a {rank} of {suit}')
display_hand(player, dealer)
if player.total > 21:
print('You busted...')
# Busted
continue
if player_move == 's':
break
# Get the dealer's moves
if dealer.total <= 21 and not player.total > 21:
while dealer.total <= 17:
print('Dealer hits...')
new_card = deck.cards.pop()
dealer.hand.add_to_hand(new_card)
if dealer.total > 21:
break
if dealer.total > 21:
print('Dealer Busted - You win!')
display_hand(player, dealer)
player.chips.add_value(bet)
dealer.chips.deduct_value(bet)
display_chips(player, dealer)
elif player.total > 21 or player.total < dealer.total:
print('You lost!')
display_hand(player, dealer)
player.chips.deduct_value(bet)
dealer.chips.add_value(bet)
display_chips(player, dealer)
elif player.total == dealer.total:
print("It's a tie! Money is returned")
if __name__ == '__main__':
main()
Does anyone have advice for a rookie?
I have tried calling the function and have gotten an error. Nothing else to be honest.
A few issues:
The file class.py is redundant. It is not imported, and only defines a class that is already defined in card.py.
There are two main function definitions. One in blackjack.py and one in player.py. The first one defines a player 'strikeouts27', while the other defines 'seraph', 'codecademy'. The second one seems the more developed one, and uses more than what is in player.py, and so it should actually be moved into blackjack.py.
Related to the previous point: blackjack.py has code that executes outside of any function. This counters the pattern where you put the driver code in a function main. It is better to move all relevant driver code inside one main function that is placed in blackjack.py. But still, that code looks unfinished, and the code already present in main is much more developed. I think you only need the code in main (the larger one).
Related to the previous point: that code in blackhack.py calls a function place_bet which is not defined. There is a method with that name, but not a standalone function with that name. For calling the method you first need an instance of Chips, so like I mentioned in the previous bullet, I would suggest to just remove this code, including also the input that is made there. Maybe you just want to keep the introductory print statements that are made there, and move those into main.
random is used in deck.py, but it is imported in blackjack.py. It would make deck.py more self-contained, if you would move that import statement to the deck.py file.
display_hand_two should not be a method of the Hand class. It doesn't even expect a self argument of the type Hand. Instead this should be a standalone function in blackjack.py.
In main you have several calls like display_hand(player, dealer), but display_hand is not a standalone function, but a method. What you really wanted to do here, is call display_hand_two(player, dealer), and for that to work you must make display_hand_two a standalone function as mentioned in the previous bullet point.
If you implement all those changes, your code will run.

How to access a list initialized in a class

I am new to programming and have decided to create a card game in python to learn more. I believe I have complicated my code more than necessary and coded myself into a corner, so I could use some guidance. I recognize my code is a bit of a logistical nightmare, so I will take any pointers you can give.
I am creating a high-low game that has a grid of 9 stacks of cards to choose from. The player chooses any of the cards and guesses if the next card pulled from the deck will be higher or lower than the card they chose. Regardless of whether or not they are right, the new card is added to the top of whichever stack was chosen. The grid itself is a list called table that contains the 9 stacks of cards. Once the deck has run out, I want to remove the last stack in the grid and append it to my deck, thus giving more cards to play with.
My Deck class creates my deck and holds logic for shuffling, drawing, counting, etc
class Deck:
def __init__(self):
self.cards = []
def build(self):
for s in suits:
for v in range(1, 14):
self.cards.append(Card(s,v))
def show(self):
print(self.cards)
def shuffle(self):
for i in range(len(self.cards) - 1, 0, -1):
r = random.randint(0, i)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
def drawCard(self):
return self.cards.pop()
def countDeck(self):
return len(self.cards)
def getTopCard(self):
print(self.cards[0])
My Stack class includes logic for adding, counting, removing stacks.
class Stack:
def __init__(self):
self.cards = []
def __repr__(self):
return "{}".format(self.cards)
def add(self, card):
self.cards.insert(0, card)
def showStack(self):
for card in self.cards:
card.show()
def countStack(self):
return len(self.cards)
def removeStack(self, card):
self.cards.remove(card)
deck.cards.append(card)
My Setup class then creates the table by building the grid of 9 stacks
class Setup:
def __init__(self, deck):
self.table = []
def buildStacks(self, deck):
for s in range(9):
stack = Stack()
c = deck.drawCard()
stack.add(c)
self.table.append(stack)
print(self.table)
Within my Game class I have the logic for comparing the card in the chosen stack with the new card pulled from the deck. Here is where I believe I should be checking to see if the deck has run out of cards, and calling my Stack.removeStack() method. For the purpose of testing, I have set the conditional to remove the last stack if the deck gets to len 40.
def compareCards(self, currCard, stackIndex):
newCard = self.deck.drawCard()
newCardVal = newCard.value
choice = input("Higher or Lower?").capitalize()
# get index of stack to add new card
stackCount = self.setup.table[stackIndex].countStack()
if choice == "Higher" and newCardVal < currCard:
print("You failed!", newCardVal, " is lower than ", currCard)
elif choice == "Lower" and newCardVal > currCard:
print("You failed!", newCardVal, " is higher than ", currCard)
elif newCardVal == currCard:
print("You failed!", newCardVal, " is the same as ", currCard)
else:
print("You chose to go ", choice, " on ", currCard, ".")
print("The new card you pulled was ", newCardVal)
print("Nice!")
self.round += 1
print("Round: ", self.round)
self.setup.table[stackIndex].add(newCard)
print(self.setup.table)
if self.deck.countDeck() == 40:
crd = self.setup.table[-1]
for c in crd:
self.setup.table[-1].removeStack(c)
print(self.setup.table)
#continue game prompting for new stack choice
self.stackMatches(deck, self.setup)
The error I am getting is "TypeError: 'Stack' object is not iterable" specifically pertaining to the for loop in the following snippet:
if self.deck.countDeck() == 40:
crd = self.setup.table[-1]
for c in crd:
self.setup.table[-1].removeStack(c)
I realize the removal logic is incorrect to begin with, but I will still need to iterate through list crd and am unsure what the workaround would be for this issue or how I would restructure my code to accomplish what I need while still utilizing best practices. I also tried changing my for loop to something like the following, resulting in the same error:
for c.cards in crd:
for c[0] in crd:

Updating the value of an attribute on an instance of a class

I was not sure how to word this problem I'm having and after 4 hours of searching I am left here to ask. So i will lay out my problem and hope for the best!
I have completed every step of this program and have gotten it to run, but my brain can not wrap around how to solve this problem.
Here is the instructions:
Match Coins: Create a coin toss game with two players.
Each player starts with 20 coins. Rules:
each player tosses their own coin
If the coins match,
Player1 gets Player2’s coin.
If not, the Player2 gets the coin from Player1.
Whoever has the most coins wins.
In main(), create a while loop that asks to user to continue play.
In each loop, report the results … coins matched?
Total coins for each player?
The loop should toss the coins at least once.
A ‘Coin’ class is needed. The class requires:
The methods __init__(), toss(), get_sideup(), get_amount(), set_amount()
The class needs the attributes ’__amount’, initialized to 20, and ’__sideup’
initialized to one of two values, ‘Heads’ or ‘Tails’.
‘toss()’ method : generates a random value of ‘0’ or ‘1’, assigning ‘Heads’ or ‘Tails’ accordingly.
‘get_sideup()’ method : returns the current value of __sideup.
‘set_amount()’ method : passes a +1 or -1 to change __amount, depending on the results of the toss.
‘get_amount()’ method : returns the current value of __amount.
I have most of this working but I can not figure out how to add coins to one instance and subract from the next.
(I put self.get_amount as filler in the function im having problems with)
Here is my code:
import random
class Coin (object):
def __init__ (self, __amount = 20, __sideup = "Heads"):
self.__amount = __amount
self.__sideup = __sideup
def toss (self):
val = random.randint(0,1)
if val == 0:
self.__sideup = "Heads"
else:
self.__sideup = "Tails"
def get_sideup (self):
return self.__sideup
def get_amount(self,):
return self.__amount
def set_amount (self, __amount):
self.get_amount
c1 = Coin()
c2 = Coin()
play = input ("Do you want to play? (Y/N): ")
while play == "Y" or "y":
c1.toss()
c2.toss()
if c1.get_sideup() == c2.get_sideup():
c1.set_amount(+1)
c2.set_amount(-1)
print("player 1 wins")
else:
c1.set_amount(-1)
c2.set_amount(+1)
print("player 2 wins")
print(" player1: " + str(c1.get_amount()) + " and player2: " + str(c2.get_amount()))
play = input("Do you want to play? (y/n): ")
Thank you to anyone who reaches out. If the answer to my question is on here please link it. I'm a beginner and not sure how to word my questions very well.
You just need to update the self.__amount property of your coin object by rebinding it to the sum of __amount and self.__amount in your coin's set_amount method.
def set_amount (self, __amount):
self.__amount = self.__amount + __amount
or a little more succinctly,
def set_amount (self, __amount):
self.__amount += __amount

Python BlackJack game -

i want to print all cards in the deck (randomly). The program runs and prints up to 48 cards (prints different amount every time program is executed). i suspect my problem lies within the get_card() function. this is my first program so please be nice (=
import random
class Deck(object):
def __init__(self,deck={},suit=[],suitDict={},cardValue=0,cardKey={}):
self.deck=deck
self.suit=suit
self.suitDict=suitDict
self.cardValue=cardValue
self.cardKey=cardKey
def create_deck(self):
spades={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
hearts={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
diamonds={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
clubs={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
self.deck={'Spades':spades,'Clubs':clubs,'Hearts':hearts,'Diamonds':diamonds}
print 'Deck Created'
def get_card(self):
while 1:
#gets random suit
self.suit=random.sample(self.deck,1)
self.suitDict=self.deck[self.suit[0]]
if self.suit[0] in self.deck:
#get random key[CARD]
self.cardKey=random.sample(self.suitDict,1)
if self.cardKey[0] in self.suitDict:
#get card value
self.cardValue=self.deck[self.suit[0]].pop(self.cardKey[0])
break
else:
self.get_card()
else:
self.get_card()
def return_hand(self):
self.get_card()
return [self.suit,self.cardKey,self.cardValue]
d=Deck()
d.create_deck()
x = 52
while x!=0:
print d.return_hand()
x-=1
Well this answer just fixes the specific problem you're facing which is not getting all the cards from your deck. I made the minimum required changes to just make your program work. You should how ever try to make the design and code cleaner.
This is the code:
import random
class Deck(object):
def __init__(self,deck={},suit=[],suitDict={},cardValue=0,cardKey={}):
self.deck=deck
self.suit=suit
self.suitDict=suitDict
self.cardValue=cardValue
self.cardKey=cardKey
def create_deck(self):
spades={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
hearts={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
diamonds={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
clubs={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
self.deck={'Spades':spades,'Clubs':clubs,'Hearts':hearts,'Diamonds':diamonds}
print 'Deck Created'
def empty(self):
return all(len(suit) == 0 for suit in self.deck.values())
def get_card(self):
while 1:
if self.empty():
break
#gets random suit
self.suit=random.sample(self.deck,1)
self.suitDict=self.deck[self.suit[0]]
if self.suitDict and self.suit[0] in self.deck:
#get random key[CARD]
self.cardKey=random.sample(self.suitDict,1)
if self.cardKey[0] in self.suitDict:
#get card value
self.cardValue=self.deck[self.suit[0]].pop(self.cardKey[0])
break
else:
self.get_card()
else:
self.get_card()
def return_hand(self):
self.get_card()
return [self.suit,self.cardKey,self.cardValue]
d=Deck()
d.create_deck()
x = 52
while x!=0:
print d.return_hand()
x-=1
I suggest you run a diff between this and your code to see exactly what has changed.
Basically:
I added an "empty()" boolean function that checks if there aren't any cards left in the deck
I checked each time you choose a new card that the chosen self.suitDict is not empty before trying to randomly choose a chard from it.
i figured it out [=
import random
class Deck(object):
def __init__(self,deck={}):
self.deck=deck
def create_deck(self):
spades={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
hearts={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
diamonds={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
clubs={'Ace':[1,10,11],2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Jack':10,'Queen':10,'King':10}
self.deck{'Spades':spades,'Clubs':clubs,'Hearts':hearts,'Diamonds':diamonds}
def get_card(self):
while True:
#picks random suit from deck // picks random key from deck dict.
#returns card attr. in a tuple
suit=random.choice(self.deck.keys())
if len(self.deck[suit]) > 0:
#picks random card from suit
card=random.sample(self.deck[suit],1)
cardValue=self.deck[suit].pop(card[0])
return (suit,card,cardValue)
else:
#deletes empty suit from deck.
del self.deck[suit]
and then this will print out all cards randomly:
deck=Deck()
deck.create_deck()
for i in range(52):
print i,deck.get_card()

updating score in card game

I am a total beginner with python.
I need help updating the score of a card game.
The scoring works as follows:
Player A or B has a pair: score += 1
Player A asks Player B (vice versa) for a card and that player has it: score += 1
Player B doesn't have it, Player A has to draw a card. If there is pair after draw: score += 2
I have the logic down but I don't really know how to connect it together.
I tried manually adding the scores in my functions, but it get's messy and complicated :(
I assume I would have to make a new function for the score and call them in my other functions?
I would appreciate the guidance,
Thank-you!
Here is some code to get you started:
class Player:
def hasPair(self):
haveIt = False
#write logic here to see if you have it
return haveIt
def hasCard(self,card):
haveIt = False
#write logic here to see if this player has the card
return haveIt
def drawCard(self):
#write logic here
pass
def ask(self,player,card):
return player.hasCard(card)
def increment_score(self,by=1):
self.score += by
def updateScores(a,b,card):
if a.hasPair(): a.increment_score()
if b.hasPair(): b.increment_score()
if a.ask(b,card):
a.increment_score()
else:
a.drawCard()
if a.hasPair(): a.increment_score(2)
if b.ask(a,card):
b.increment_score()
else:
b.drawCard()
if b.hasPair(): b.increment_score(2)

Categories

Resources