I have set up a code in a class but i am not sure if this is the class that i would use.I have to put the logic of the game in a Class and then use the methods from the class to run the game.Right now i have some methods in a class but i am not sure on how i would go on getting it to work and calling the functions.I would like help on Possible telling me if i need another class and how to fix my methods in the class.Also if you would point me in the right direction on how i would use the methods and then call them in another file so i can make the BlackJack Program work. please and thanks for the help

from random import *

class DeckOfCards:
    def __init__(self):
        #Make the Deck Of Cards
        self.__cards = [2,3,4,5,6,7,8,9,10,10,10,10,11] * 4
        #keeps the score for the player and computer
        playerScore = 0
        computerScore = 0
        #holds the cards
        player = []
        computer =[]
        #boolean to see who wins
        PlayerLoser = False
        ComputerLoser = False



    def drawCard(self):
        #draw a card for the player
        player.append(choice(self.__cards))
    def drawCardComp(self):
        #draw a card for the computer
        computer.append(choice(self.__cards))

    def totalOfPlayer(self):
        #the total the player has in his hands
        self.__totalOfP = total(player)
        return self.__totalOfP
    def totalOfComputer(self):
        #the total the computer has in his hands
        self.__totalOfC = total(computer)
        return self.__totalOfC
    def playGame(self):#i dunno if this is the method i am going to use here


        while True:
            #i want it to call the function in the class to draw a card
            drawCard()
            drawCard()
     
    
        if self.__totalOfP > 21:
            print 'You Lost'
            playerLoser = True
       
        elif self.totalOfP == 21:
            print 'hey congrats you got BlackJack :)'
    
        else:
            goAgain = raw_input("Hit or Stand (h or s): ").lower()
            if goAgain == 'h':
                #i want it to call the function in the class to get another class
                drawCard()
            
        while True:
            # loop for the computer's play
            #draw the computer cards
            drawCardComp()
            drawCardComp()
           
            while True:
                       
                if totalOfC < 18:
                    #draw the card if its less than 18
             
                    print "the computer has %s for a total of %d" % (computer, self.__totalOfComputer)
                    # now figure out who won ...
                    if self.__totalOfComputer > 21:
                        print "The computer is busted!"
                        ComputerLoser = True
                        if PlayerLoser == False:
                            print 'The Player Wins'
                            playerScore += 1
                    elif totalOfC > totalOfP:
                        print 'the Computer wins'
                        computerScore += 1
                    elif totalOfC == totalOfP:
                        print 'TIE'
                    elif totalOfP > totalOfC:
                        if PlayerLoser == False:
                            print 'The Player Wins'
                            playerScore += 1
                        elif ComputerLoser == False:
                            print 'The Computer Wins'
                            computerScore += 1

        print
        print "Wins, player = %d  computer = %d" % (playerScore, computerScore)
        exit = raw_input("Press Enter (q to quit): ").lower()

    
    print

What's your objective?

What kind of interface do you need? Should the game play fully automated, or does the user interact with the game? If fully automated, where/how do you define the 'rules' for the player?

Do you need to shuffle the deck?

What keeps 'choice' from re-picking the same card that was picked previously?

When dealing Blackjack, don't you normally deal one to each player and then one to the dealer. Then repeat for the second card?

hi i want to make a text based interface where it displays the cards to the player and then next to them the total of the cards..the user is allowed to interact only if he has 18 or less in his cards..and if he has 18 or less he is then allowed to hit or stand.

the choice is supposed to pick a random card every time..i think i have that done with the 'from random import*'

this is supposed to be the class but like i said i am not sure if how i am doing it is correct.

i am supposed to have another file with me then calling the functions so that it can interact.

You're using 'choice' from the random module. This selects a random member of the list. This part is ok, but if you were to give the cards actual display values (like 5S for 5 of Spaces or 2H for the 2 of Hearts) nothing in choice prevents you from dealing the same card twice, its always picking a card from a new deck, regardless of the cards that have already been drawn.

I like the concept of a deck of cards as a class, but the deck of cards shouldn't know anything about the player or the computer or the score or anything besides the cards. That data should live in another class or as global data, depending on your design.

(Side note: if you build a list of cards you could use random.shuffle to mix up the order of the cards in the list. Then you could 'walk through' the list from head to tail to get cards which would guarantee you didn't deal the same card twice.)

Why do you limit the user to only being able to hit when the total is 18 or less? Granted it wouldn't be very common to hit at or above 18, but I think it is the player's decision to make.

You might consider a 'card' class that has a display (like AD, 7C, JS) and a value. (Right now your deck is only values.) This might make it easier to 'score' a hand. The problem being that an ace is either 1 or 11, whichever makes more sense for the hand.

You might want to generate a 'hand' class if you can find something useful for it to do, or you could just use a list.

What is the pseudo code for a hand? What steps does the computer take to play one hand? Maybe round is a better term, I'm looking for the logical steps from start to decision as to who won.

As I understand the game, the dealer deals his first card 'face down' and the second 'face up' shouldn't the user get to 'see' the dealer's face up card?

There are other concepts from blackjack that depend some on the 'bet' which does not appear to be represented in your game. (Insurance, Split, Double Down). But they may not be necessary to your implementation.

If you're planning another file to interact with this one, what do you envision the interface between the two looking like?

okay how would i make the two classes interact with each other? how would i make the class DeckOfCards interact with another class that i make for the game play? i dunno how to do this.

For my other class i want it to be how you said how the user gets one card and the dealer gets one..then the user gets one and the dealer gets another one..i have no clue how i would then implement what you said on how the user is then allowed to see one card of the computer.

also are you saying that i could just implament the interface and the class of the blackjack in the same class file? bc i think this way would be much easier than making a whole new file that interacts with the class

sorry i am very new at this and i get confused on this

Yes the code can all be in one file, but you still have to end up defining the objects (classes) and how they interact. The multi-file method would make more sense if you planned to re-use some of the classes.

For example, the 'deck of cards' would probably populate itself when you make it, support a 'shuffle' or 'mix' method to mix all the cards up. It would probably have a 'deal' method that would return the next card from the deck and maybe a counter to tell you how many cards are left in the deck. You could then re-mix the cards every hand or every few hands without having to worry about the deck anymore.

The game would interact with the deck by calling mix and then deal to get a card for the player. Then deal for the 'down card' for the dealer. Then calling deal twice more to get the player's second card and the 'up card' for the dealer.

Is this how you think of the problem, or do you think about it some other way?

NOTE: this is the key part of the problem (or assignment) how do YOU think about the problem? How do you think about breaking the problem up into smaller, more-managable pieces?

What else would be required to complete a round of play?

How does the user (player) decide to keep playing or to quit?

I am intentionally asking leading questions to help you think about the problem. Put just a bit of thought into it and tell me how you think it ought to work. If you have ideas that make it harder, I'll try and point you toward easier routes if they exist, but you have to put in most of the effort, I have no desire to write the program for you.

Okay i have tried to make the DeckOfCards class and tried testing it out in the IDLE window by calling the function to see if i get a shuffled 'deck of cards' but i get an error i have no clue what i am doing wrong

from random import*

class DeckOfCards:
    def __init__(self):
        self.cards = ['2','3','4','5','6','7','8','9','10','10','10','10','11']

    def mix(self):
        return random.shuffle(self.cards)

I have tried making the list without the ' ' and it still wont work..so do i even need the ' ' ?

this is the error i get from the idle window

>>> import CardsBJ
>>> a = DeckOfCards
>>> a.mix()

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a.mix()
TypeError: unbound method mix() must be called with DeckOfCards instance as first argument (got nothing instead)

Sorry it took so long to reply, but it would have been longer if I could sleep (grin).

Your current problem is that you can't create a DeckOfCards with a = DeckOfCards you need to a = DeckOfCards() If you want, you can stop reading here and go try that, it will make a world of difference.

Here's the little test app I wrote up to build the deck with more of what I had in mind. You seem to keep thinking of the cards in terms of their value to blackjack. What if you wanted to use the deck to play poker, or cribbage? This implementation will be slightly harder to score, but if I can score my hand in my head, why can't the computer?

import random

class DeckOfCards:
    def __init__(self):
        self._cards = []
        for suit in ["S","C","H","D"]:
            for card in ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]:
                self._cards.append(card+suit)
        self._drawIndex = 0

    def mix(self):
        random.shuffle(self._cards)
        self._drawIndex = 0

    def draw(self):
        rval = self._cards[self._drawIndex]
        self._drawIndex += 1
        return rval

if __name__ == "__main__":
    thedeck = DeckOfCards()
    thedeck.mix()

    playercards = []
    dealercards = []

    playercards.append(thedeck.draw())
    dealercards.append(thedeck.draw())
    playercards.append(thedeck.draw())
    dealercards.append(thedeck.draw())

    print playercards
    print dealercards

The if __name__ == "__main__" is how I'm currently adding test code to modules. This expression will be true if this file is the 'main' file, but it will be false if this file was included due to an import command.

You may also note that I didn't use the same style of import for random that you did. You used from random import * which pulls all of the symbols from random into your top-level namespace. The funny part is, when you called the shuffle function, you used random.shuffle when shuffle should have been sufficient. I prefer not to add things to my top-level namespace unless it is necessary and I don't usually mind typing a little extra to make sure I'm getting what I want.

The first part helped me a lot and it helped me figure out why i couldn't call my class now i have started to write my second class and i have just have some of it done. i am now trying to calculate the score of the hand because i want to be able to display them next to the cards.. this is what i have so far

class BlackJack:
    def __init__(self):
        self.Playerscore = 0
        self.Computescore = 0

    def valueOfCards(self, hand):
        for card in hand:
            try:
                value += int(card[0])
            except ValueError:
                value +=10
            return value

i can display the value of the cards if they are integers or when they are not integers then the card value is 10. but i want to be able to figure out how i would put the 'Ace' value to equal 11 in my function.. also i want to be able to put something like this ' if value > 21 and if an ace is your hand then make the ace worth 1' i dont know where i would add this to my code or how i would word it in code.
would i make a statement like this?

if value > 21 and card[0].startswith("A"):
value -= 10

Your approach to getting the card number is pretty good, but it will fail for the 10 card (you'll get the value 1). You could fix what you have by doing int(card[:-1]) . The code also doesn't handle the ace yet either.

Another option to using the slice (that's what the card[:-1] is) would be to change the representation of the cards in the deck. When making the cards in the deck of cards, instead of making a single string with the card and the suit, you could split them into a tuple. Where we have card + suit in the DeckOfCards. __init__ you could put (card,suit) . Each card then would be a tuple (sort of like a list, but you can't modify it) where card[0] would be the card's face value and card[1] would be the suit. If you do this, you would have to merge them when you display the cards with either card[0]+card[1] or ''.join(card) {I love how there is always more than one way way to do something, don't you} use the way that makes the most sense to you.

Ok having said the above, the way I would address the hand value would be something like the following. (I'll leave the writing of cardValue(card) to you.)

def handValue(hand):
    cardValues = []
    for card in hand:
        cardValues.append(cardValue(card))
    while sum(cardValues) > 21 and 11 in cardValues:
        cardValues.remove(11)
        cardValues.append(1)
    return sum(cardValues)

Note that this was written, expecting cardValue and handValue to be stand alone functions and not in the class BlackJack as I didn't see where they need any of the classes data. If you want them to live in BlackJack for scoping, add 'self' where necessary.

I made this new function for the

cardValue(card)

but for some reason everytime i run it i dont get the correct result.I think i worded it correctly and have checked it but i still dont find where i made an error..

def cardValue(card):
    value = 0
    for c in card:
        if c[:-1] == "A":
            value += 11
        elif c[:-1] == "J" or "K" or "Q":
            value += 10
        else:
            value += int(c[:-1])
    return value

This is my result for some reason it doesn't display the correct result i am looking for.

>>>
>>> card = 'AH'
>>> print cardValue(card)
20
>>> print card
AH
>>> print card[:-1]
A
>>> card = 'A'
>>> print cardValue(card)
10
>>> card = '4'
>>> print cardValue(card)
10

okay also after this function executes and you get the value of the cards in your hand it then passes it to the

handValue(value)

? is this correct?

You don't want the for in the cardValue method.

You also can't compare against 3 string values with elif c[:-1] == "J" or "K" or "Q": you either need to change it to elif c[:-1] == "J" or c[:-1] == "Q" or c[:-1] == "K": or to elif c[:-1] in ["J","Q","K"]: cardValue is only trying to get the value for a single card.
handValue uses it to help calculate the value for the hand.

Here's a version without the for loop and just returning the card value when it knows what it is. (Note this has multiple exit points, which can be bad form, but in this case I would do it anyway.)

def cardValue(card):
    if card[:-1] == "A":
        return 11
    if card[:-1] in ["J", "Q", "K"]:
        return 10
    return int(card[:-1])

Once you get it working, the handValue method will call cardValue to get the value for each card.

Hey what do you mean "multiple exit points"?

also i want to the DeckOfCard class to interact with the BlackJack class i am going to make..but how would the DeckOfCard "instance" work with the BlackJack class "instance". What i'm trying to say is how would i call the DeckOfCard class inside the BlackJack class.

Multiple exit points means there is more than one way out of the function. (Each 'return' statement is an exit point.)

I think you want to have the BlackJack class create a DeckOfCards; something like [/icode]self.deck = DeckOfCards()[/icode] then you can do things like self.deck.mix()

oh okay thanks that will help me when i make my final method to check if they player needs to 'hit' or 'stay'. and to show if the player won(would you make this into a different method than the method that ask the player to 'hit' or 'stay')

When I was testing the deck, I put in a couple of helper functions and just put the play in main.

You should probably have one method to play a hand or round, which will include dealing, hit/stay, dealer hit/stay and scoring. Whether you put those directly in the method or in other methods called from there is mostly a matter of preference. (Unless something gets really big, then you're almost always better of breaking it up.)

Another method might 'sequence' the hands and determine if the user wanted to keep playing, but that's just my take on it; there is no 'One True Way' to write it.

The class should probably also keep track of the number of hands won vs the number of hands lost.

for this blackjack code, do u have algrothim, if you do , post it, as i know mate of my mine, who may able to help, sort your code.

tutti,

We haven't been working on this thread for over 2 weeks...if you want to get help with your program, start a new thread and show us your work.

i was just asking for you algorithm, not for your code mate, just wanted see, you had wriiten, before your started coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.