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()
Related
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.
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:
I have windows 8 running on my computer and I think I downloaded python 2 and 3 simultaneously or I think my computer has built in python 2 and I downloaded python 3. And now when I ran my code in IDLE, the code works fine but when I save my program and double click the save file, it will run but it doesn't worked like it used to work in IDLE.
Can someone explain the possible problem I'm currently facing?
I just want my program to run perfectly in both IDLE and when I double click the saved file.
I tried what Anand S. Kumar suggested but I'm not sure I know what I'm doing.
So here is what I inputted in the CMD adminstrator but the output is still the same as the first picture above.
so here is the code
the games module:
# Games
# Demonstrates module creation
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
the cards module:
# Cards Module
# Basic classes for a game with playing cards
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit, face_up = True):
self.rank = rank
self.suit = suit
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
rep = self.rank + self.suit
else:
rep = "XX"
return rep
def flip(self):
self.is_face_up = not self.is_face_up
class Hand(object):
"""A hand of playing cards."""
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)
class Deck(Hand):
""" A deck of playing card. """
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print("Can't continue deal. Out of cards!")
if __name__ == "__main__":
print("This is a module with classes for playing cards.")
input("\n\nPress the enter key to exit.")
and then the main code:
# Blackjack
# From 1 to 7 players compete against a dealer
# Daghan pakog wa nasabtan ani so balikan pa nako ni!
import cards, games
class BJ_Card(cards.Card):
""" A Blackjack Card. """
ACE_VALUE = 1
#property
def value(self):
if self.is_face_up:
v = BJ_Card.RANKS.index(self.rank) + 1 # unsaon pag kabalo sa self.rank xia.
if v > 10:
v = 10
else:
v = None
return v
class BJ_Deck(cards.Deck):
""" A Blackjack Deck. """
def populate(self):
for suit in BJ_Card.SUITS:
for rank in BJ_Card.RANKS:
self.cards.append(BJ_Card(rank, suit)) # kay naa may __init__ sa BJ_Card
class BJ_Hand(cards.Hand):
""" A Blackjack Hand. """
def __init__(self, name):
super(BJ_Hand, self).__init__()
self.name = name
def __str__(self):
rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
if self.total:
rep += "(" + str(self.total) + ")"
return rep
#property
def total(self):
# if a card in the hand has value of None, then total is None
for card in self.cards:
if not card.value:
return None
# add up card values, treat each ACE as 1
t= 0
for card in self.cards:
t += card.value #-->? tungod sa # property pwede na xa .value ra
#--> Libog ning diri dapita, unsaon pag kabalo nga self.rank xia
# determine if hand contains an ACE
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains_ace = True
# if hand contains Ace and total is low enough, treat Ace as 11
if contains_ace and t <= 11:
# add only 10 since we've already added 1 for the Ace
t += 10
return t
def is_busted(self):
return self.total > 21
class BJ_Player(BJ_Hand):
""" A Blackjack Player. """
def is_hitting(self):
response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
return response == "y"
def bust(self):
print(self.name, "busts.")
self.lose()
def lose(self):
print(self.name, "losses.")
def win(self):
print(self.name, "wins.")
def push(self):
print(self.name, "pushes.")
class BJ_Dealer(BJ_Hand):
""" A Blackjack Dealer. """
def is_hitting(self):
return self.total < 17
def bust(self):
print(self.name, "busts.")
def flip_first_card(self):
first_card = self.cards[0]
first_card.flip()
class BJ_Game(object):
""" A Blackjack Game. """
def __init__(self, names):
self.players = []
for name in names:
player = BJ_Player(name)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()
#property
def still_playing(self):
sp = []
for player in self.players:
if not player.is_busted():
sp.append(player)
return sp
def __additional_cards(self, player):
while not player.is_busted() and player.is_hitting():
self.deck.deal([player])
print(player)
if player.is_busted():
player.bust()
def play(self):
# deal initial 2 cards to everyone
self.deck.deal(self.players + [self.dealer], per_hand =2)
self.dealer.flip_first_card() # hide dealer's first card
for player in self.players:
print(player)
print(self.dealer)
# deal additional cards to playeres
for player in self.players:
self.__additional_cards(player)
self.dealer.flip_first_card() # reveal dealer's first
if not self.still_playing:
# since all players have busted, just show the dealer's hand
print(self.dealer)
else:
# deal additional cards to dealer
print(self.dealer)
self.__additional_cards(self.dealer)
if self.dealer.is_busted():
# everyone still playing wins
for player in self.still_playing:
player.win()
else:
# compare each player still playing to dealer
for player in self.still_playing:
if player.total > self.dealer.total:
player.win()
elif player.total < self.dealer.total:
player.lose()
else:
player.push()
# remove everyone's cards
for player in self.players: # dapat inside ra xia sa class kay kung dili. self is not defined.
player.clear()
self.dealer.clear()
def main():
print("\t\tWelcome to Blackjack!\n")
names = []
number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
for i in range(number):
name = input("Enter player name: ")
names.append(name)
print()
game = BJ_Game(names)
again = None
while again != "n":
game.play()
again = games.ask_yes_no("\nDo you want to play again?: ")
main()
input("\n\nPress the enter key to exit.")
Please don't mind the comments if you don't understand. That is my first language by the way.
Most probably, the default program associated with .py files is the Python 2.x's executable . That could be the reason it is not running correctly, when you double-click the python file.
Because when you double click a file (or run it in command prompt without giving an executable ) , windows picks up the default program that is associated with .py files and runs the file using that executable.
In your case, even though you installed Python 3, this may still be pointing to Python 2.
From python installation doc, to change the default executable for Python files , use -
You can also make all .py scripts execute with pythonw.exe, setting
this through the usual facilities, for example (might require
administrative rights):
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\python3.exe "%1" %*
Use the above to redirect .py files to Python 3.
I have never tried to run a Python program by double clicking the save file, but I can point you in the direction that tells you how to run a program in the Command Line or Python Shell.
First off, Windows does not come with Python 2 or 3. You can check which version you have by simply going to wherever the Python files were installed. By default, they will be in the C drive. Once you have your enviornment path set up, you can also check which version of Python you have via the Python shell.
Here is where you can find the steps to set up your environment to run Python from the Command Line. This also will help you set up your enviornment. Essentially what you are doing is telling Windows where to find the Python libraries when you type 'python' into the Command Line. Once you have your environment set up, you can run your files in the Command Line or in the Python Shell. Look at Escualo's answer for how to do this.
You could try to to change the assosiation to:
python.file="C:\Windows\py.exe" "%L" %*
or set the "C:\Windows" part to where-ever Python3.exe is.
The Python installer (for Python3 at least) seems to specify that the filename should be on the wide-character form; Hence the %L modifier.
BTW. You can use ftype in your cmd-shell too (instead of poking around
in Explorer). Untested, so beware:
ftype python.file=="C:\Windows\py.exe" "%L" %*
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.
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)