import randomclassCard(object):def__init__(self,suit,val): self.suit = suit self.value = val# Implementing build in methods so that you can print a card objectdef__unicode__(self):return self.show()def__str__(self):return self.show()def__repr__(self):return self.show()defshow(self):if self.value ==1: val ="Ace"elif self.value ==11: val ="Jack"elif self.value ==12: val ="Queen"elif self.value ==13: val ="King"else: val = self.valuereturn"{} of {}".format(val, self.suit)classDeck(object):def__init__(self): self.cards = [] self.build()# Display all cards in the deckdefshow(self):for card in self.cards:print card.show()# Generate 52 cardsdefbuild(self): self.cards = []for suit in ['Hearts','Clubs','Diamonds','Spades']:for val inrange(1,14): self.cards.append(Card(suit, val))# Shuffle the deckdefshuffle(self,num=1): length =len(self.cards)for _ inrange(num):# This is the fisher yates shuffle algorithmfor i inrange(length-1, 0, -1): randi = random.randint(0, i)if i == randi:continue self.cards[i], self.cards[randi]= self.cards[randi], self.cards[i]# You can also use the build in shuffle method# random.shuffle(self.cards)# Return the top carddefdeal(self):return self.cards.pop()classPlayer(object):def__init__(self,name): self.name = name self.hand = []defsayHello(self):print"Hi! My name is {}".format(self.name)return self# Draw n number of cards from a deck# Returns true in n cards are drawn, false if less then thatdefdraw(self,deck,num=1):for _ inrange(num): card = deck.deal()if card: self.hand.append(card)else:returnFalsereturnTrue# Display all the cards in the players handdefshowHand(self):print"{}'s hand: {}".format(self.name, self.hand)return selfdefdiscard(self):return self.hand.pop()# Test making a Card# card = Card('Spades', 6)# print card# Test making a DeckmyDeck =Deck()myDeck.shuffle()# deck.show()bob =Player("Bob")bob.sayHello()bob.draw(myDeck, 5)bob.showHand()
Blackjack with Python
Learn how to code a command line game of Blackjack with the Python programming language.
CHECK OUT THE FOLLOW ON VIDEO TO TURN THIS SAME CODE BASE INTO A BEST OF FIVE GAME https://youtu.be/fn61C_GQUwQ
You know Blackjack. Also, referred to as 21.
In this game, you play against the dealer. You are both dealt hands and you can Hit or Stay based on the knowledge of your cards and the one card you can see of the dealers.
Welcome to Las Vegas or Atlantic City!! We are going to bring that to your Terminal :)
The source code for this program can be found here on Github https://github.com/techBytesIO/python...
Other cool coding and tech things can be found here https://techbytes.io/
The Python programming language can be found here https://www.python.org/