-2

This is my code so far:

import sys
import os
import random
Question():
    os.system('cls')
    SQ=input('Do you want to play blackjack y/n')
    if(SQ == y or SQ == Y):
        StartGame()
    if(SQ == n or SQ == N):
        sys.exit()
    if(SQ != n and SQ != N and SQ != y and SQ != Y):
        print('You did answer the question with a y or a n which correspond to yes and no accordingly')
        Question()
Question()

StartGame():
    slot1=False
    slot2=False
    slot3=False
    slot4=False
    slot5=False
    slot6=False
    slot7=False
    slot8=False
    slot9=False
    slot10=False
    slot11=False
    slot12=False
    slot13=False
    slot14=False
    slot15=False
    slot16=False
    slot17=False
    slot18=False
    slot19=False
    slot20=False
    slot21=False
    slot22=False
    slot22=False
    slot23=False
    Slot24=False
    slot25=False
    slot26=False
    slot27=False
    Slot28=False
    slot29=False
    slot30=False
    slot31=False
    slot32=False
    slot33=False
    slot34=False
    slot35=False
    slot36=False
    slot37=False
    slot38=False
    slot39=False
    slot40=False
    slot41=False
    slot42=False
    slot43=False
    slot44=False
    slot45=False
    slot46=False
    slot47=False
    slot48=False
    slot49=False
    slot50=False
    slot51=False
    slot52=False

    aceHEART = randrange(1, 52)
    aceHEART

I don't understand the correct way to make the slots and a random number generator together to make a random shuffle. How can i make it so it does not try to put more than one card in one slot. I also do not know how to manage these cards in a more efficient way. I am making a blackjack game in python and i do not know the correct way to approach this. Please help me in the best way you can.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
  • 5
    Might want to fix those SyntaxError's and NameError's first :p – Jon Clements Dec 30 '14 at 00:24
  • thanks for being constructive and useful (sarcasm intended) – Ryan Cobourn Dec 30 '14 at 00:25
  • 1
    use a [list](http://www.tutorialspoint.com/python/python_lists.htm). what you're attempting to do with the 52 variables is a very common novice programmer mistake though – Ryan Haining Dec 30 '14 at 00:26
  • also as to the `os.system('cls')` this is also a common thing to see in new-programmer code, people don't like having their screens cleared unexpectedly, hardly anyone does this unless strictly necessary in the real world, and you're binding your code to windows only by doing `cls` – Ryan Haining Dec 30 '14 at 00:27
  • `if(SQ == y or SQ == Y):` y and Y here indicate variables, not letters, you need to quote them for that to work, and also you're generally better off using a call to lower `if SQ.lower() == 'y':` – Ryan Haining Dec 30 '14 at 00:29
  • really? hmmm wierd must just be me then because i prefer to have my screen cleared, it makes me feel more neat and organized – Ryan Cobourn Dec 30 '14 at 00:29
  • yeah, like I said it's extremely common with novices, but you get used to not having it clear, and being able to look at your previous runs without having to navigate back to them. when you do `dir` and `cd` it doesn't clear the screen either after all – Ryan Haining Dec 30 '14 at 00:31
  • if you do your first two `if` checks, the last one becomes unnecessary because if you reach that point you know it's true, probably better off using `if`/`elif`/`else` – Ryan Haining Dec 30 '14 at 00:32
  • and, about the os.system('cls'), i know it ties it down it windows but i mean i have to change the color of the text and backround anyway so that is not important. – Ryan Cobourn Dec 30 '14 at 00:36
  • @Ryan Haining if(SQ == y or SQ == Y): y and Y here indicate variables, not letters, you need to quote them for that to work, and also you're generally better off using a call to lower if SQ.lower() == 'y': your correct, that is a better way to do it – Ryan Cobourn Dec 30 '14 at 00:47

3 Answers3

1

Not sure what you're trying to do, but here is a way to generate a shuffled deck of cards:

ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suite = ['clubs', 'hearts', 'spades', 'diamonds']

deck = [r + ' ' + s for r in ranks for s in suite]

random.shuffle(deck)

Or with objects:

class Card(object):
    def __init__(self, rank, suite):
        self.rank = rank
        self.suite = suite

deck = [Card(r,s) for r in ranks for s in suite]
random.shuffle(deck)
Mihai Zamfir
  • 2,167
  • 4
  • 22
  • 37
  • from what youve showed me i can now do this correctly, thank you very much. I did not know about the random.shuffle fuction and the way you implemented the deck list is very clever. +1 if i could and accepted answer – Ryan Cobourn Dec 30 '14 at 00:44
  • Except that this will get you a list of 52 strings. And strings are a bad way to represent cards in code, because you need to do things like add and compare them. – Lee Daniel Crocker Dec 30 '14 at 00:47
  • It was just an example, you can put in objects for representing them or whatever – Mihai Zamfir Dec 30 '14 at 00:48
  • That is true. Although if that is your claim, you should show me a better one or your comment is somewhat useless (no offence intended) – Ryan Cobourn Dec 30 '14 at 00:50
  • can you show me how to implement that? – Ryan Cobourn Dec 30 '14 at 00:50
  • Can't understand exactly what you need but here's an edit to use objects instead – Mihai Zamfir Dec 30 '14 at 00:54
  • @RyanCobourn just don't forget when using this that Blackjack allows an ace to rank as both 1 and 11 – Jon Clements Dec 30 '14 at 00:57
  • ya, thats a tough one, im getting boged down and i feel like stopping making this program ): i dont like using classes and such which become complicated but the other way would take 52 lines of code to decifer what rank a card was, along with taking a few extra lines for the ace. – Ryan Cobourn Dec 30 '14 at 00:59
  • It's not overly difficult - and classes aren't scary beasts - just take one step at a time - that's how programming works :p Good luck @RyanCobourn – Jon Clements Dec 30 '14 at 01:01
  • thank you for your help! I really do dislike people who dislike a question and leave, without any explanation or reason to why they disliked it or how i can improve. – Ryan Cobourn Dec 30 '14 at 01:04
0

Learn to love lists, and use numbers to represent cards, not strings. Here's a simple card class that should work nicely:

class Card(object):
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return "23456789TJQKA"[self.rank] + "cdhs"[self.suit]

Then create decks and hands that are just lists of cards:

deck = [ Card[r,s] for r in range(13) for s in range(4) ]
random.shuffle(deck)

Why you want to use lists for hands and decks, for example, is that dealing a card is simply:

hand.append(deck.pop())

Why you want to use numbers for card ranks instead of strings is to make it possible to add and compare them. You could add a "value" member to Mihai's code above, that would help. WIth mine, you just have to adjust the numbers a bit:

def bjTotal(hand):
    total = 0
    hasAce, isSoft = False, False

    for card in hand:
        if card.rank == 12:
            hasAce = True
            total += 1
        elif card.rank > 7:
            total + 10
        else:
            total += card.rank + 2

    if hasAce and total < 12:
        isSoft = True
        total += 10

    return total, isSoft
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
0

classes do a good job of representing cards and games

import random
class Card:
     def __init__(self,rank,suit):
        self.rank = rank
        self.suit = suit
     def rankName(self):
        return "A23456789TJQK"[self.rank]
     def suitName(self):
        return "HCDS"[self.suit]
     def __int__(self):
        if self.rank > 8: return 10
        if self.rank == 0:return 11
        return self.rank + 1
     def __eq__(self,other):
        try:
            return self.rank == other.rank
        except:
            return self.rank == other
     def __str__(self):
        return self.rankName() +self.suitName()
     def __repr__(self):
        return "<Card: %s>"%self

class Deck:
    def __init__(self,cards=None):
        if cards is None:
           cards = [Card(rank,suit) for rank in range(13) for suit in range(4)]
        self.cards = cards
        random.shuffle(self.cards)
    def draw(self):
        return self.cards.pop(0)
    def __add__(self,other):
        return Deck(self.cards+other.cards)


class Hand:
    def __init__(self):
        self.cards = []
    def __int__(self):
        total = sum(map(int,self.cards))
        aces = self.cards.count(0)
        while aces > 0 and total > 21:
            aces -= 1
            total -= 10
        return total
    def put(self,card):
        self.cards.append(card)
    def __str__(self):
        return ", ".join(map(str,self.cards))
    def __repr__(self):
        return "<Hand %s>"%self.cards

once you have your classes you can now start constructing your game

class Game:
      def __init__(self,n_players=1,use_dealer=True):
         self.main_deck = Deck()+Deck() # 2 deck shoe
         self.n_players = n_players
         self.dealer = use_dealer
      def play_hand(self,hand):
         while int(hand) <= 21 and raw_input("%r\nHit?"%hand)[0].lower() == "y" :
              hand.put(self.main_deck.draw())
         if int(hand) > 21:
              print "BUST!!!"

      def play_game(self):
         current_player = 0
         hands = [Hand() for _ in range(self.n_players+self.dealer)]
         for i in range(2):
             for hand in hands:
                 hand.put(self.main_deck.draw())
         while current_player < len(hands) - self.dealer:
               self.play_hand(hands[current_player])
               current_player += 1
         if self.dealer:
            while int(hands[-1]) < 17:
                hands[-1].put(self.main_deck.draw())
                print "DEALER HITS:",hands[-1]
         print "FINAL SCORES:"
         print "\n".join("%s. %r %d"%(i,h,h) for i,h in enumerate(hands))


game = Game()
game.play_game()

(something like that anyway)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179