Blackjack In Python

Posted onby

Today, we will study blackjack by writing up a blackjack simulator in Python, simulating a bunch of games, and then studying how our player did. I will assume some basic familiarity with the game of Blackjack, but here is a quick refresher for how the game is played: Players make their bets. Players are dealt 2 cards. $ begingroup $ I think you really need to read the documentation on how classes in python work. For example, you would rarely ever have free standing code as seen in the Deck class, you would either put it in the init function or under a different function $ endgroup $ – Navidad20 Dec 14 '16 at 18:26.

  1. Simple Blackjack In Python
  2. How To Make Blackjack In Python
  3. How To Code Blackjack In Python
Latest version

Released:

Red-black trees

Project description

Blackjack is a simple implementation of the classic red-black tree as astandard Python data structure. A set and a dictionary are included:

  1. Create our own Blackjack Game using Python Blackjack is a card-based game played at casinos. The participants in this game do not compete with each other but the dealer assigned by the casino. In this article, we will be creating the Blackjack game between a player and a dealer from scratch, that can be played on the terminal.
  2. Blackjack Game in Python Movies like Rain Man and 21 portray the ability to count cards in blackjack as being equivalent to a genius. In a nutshell, counting cards means assigning points to each card that is dealt during a round of blackjack, and using this point system to place higher bets when you are in favor of winning more money.
  3. Create our own Blackjack Game using Python Blackjack is a card-based game played at casinos. The participants in this game do not compete with each other but the dealer assigned by the casino. In this article, we will be creating the Blackjack game between a player and a dealer from scratch, that can be played on the terminal.

Usage

Blackjacks and decks behave just like normal Python sets and dictionaries, buthave different performance characteristics and different requirements forkeys. All keys must be comparable, but need not be hashable:

This does impact heterogeneity somewhat, but shouldn’t be a problem for mostcommon uses. On the other hand, the average and worst-case times for access,membership testing, insertion, and deletion are all logarithmic, which makesblackjacks ideal for storing mappings of data with untrusted keys:

Even on small- to medium-sized sets of data, blackjacks quickly become moreeffective than dictionaries in the face of untrusted input.

This package only contains the blackjack module; tests are in the moduleand may be run with any standard test runner:

Technical information

The specific trees used are left-leaning red-black trees. Red children areopportunistically reduced during balancing if nodes will be recreated anyway;this tends to shorten overall tree height by reducing the number of redchildren. Complexities are as follows:

OperationTimeSpace
LookupO(log n)O(1)
MembershipO(log n)O(1)
InsertionO(log n)O(log n)
DeletionO(log n)O(log n)
UpdateO(log n)O(log n)
SortO(1)O(1)
LengthO(1)O(1)

Sorting according to the provided key function is constant because the tree’straversal order is presorted. Length is recorded and updated on mutation.Nodes are persistent and altering the tree generally requires a logarithmicspace commitment to create new nodes.

Release historyRelease notifications RSS feed

1.1.1

1.1

1.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for blackjack, version 1.1.1
Filename, sizeFile typePython versionUpload dateHashes
Filename, size blackjack-1.1.1.tar.gz (6.2 kB) File type Source Python version None Upload dateHashes
Close

Hashes for blackjack-1.1.1.tar.gz

Hashes for blackjack-1.1.1.tar.gz
AlgorithmHash digest
SHA2569b709b61fc2888f3ab76231c78c1e1642e89f4c67a3e2629481680a8100801e0
MD5f6ab60d22e93f1d60a8f75688380c91a
BLAKE2-256bf36fcfea476d0def0fb62d4d65646d4ac6898381018aa99fc847f5cd44a5bc9

Here is a little bit of documentation about the more important functions andclasses from the blackjack program. This documentation is auto-generatedfrom the Python source code and doc strings contained in the source code.

blackjack.py
A Blackjack game
class blackjack.Blackjack(win)¶
Python blackjack tutorialHow to code blackjack in python

Controller or coordinator of the game. All buttons belongto this class.

go()¶
This the entry and exit point to/from main. The MouseTrapengine exits to here, then we exit back to main
hit()¶
Button call back – give player another card and let dealerplay then check if game over yet. Otherwise, back to theHit or Stand choice.
play()¶
Button call back to begin a hand. It does some clean upfrom the previous hand and does the initial deal to the dealer andplayer. Unless the player or dealer got a Blackjack (21 from justthe two cards in the initial deal), then after this functionexits, players next pick to Hit or Stand
quit()¶
Button call back to exit the program. It just returnsFalse so that the MouseTrap engine will exit
stand()¶
Button call back – player does not need another card. Let thedealer play now, which finishes the hand.
startOver()¶
Button click handler for reseting the game
blackjack.main()¶
The main() program that gets everything started. It basicallyjust creates the graphics window, creates the Blackjack(controller) object and gets it started. Another external programthat imports this module could easily do the same and start aBlackjack game in it’s own graphics window.
bkJplayers.py
The participants (Dealer, Player) of a Blackjack game
class bkJplayers.Contestant(win, deck, xmin, ymin, xmax, ymax)¶

Common stuff between player and dealer. Don’t create aninstance of this class - that’s what player and dealer are for.They inherit form this class, which on exists to cut down on codeduplication.

busted()¶
Just return if contestant went bust
clear()¶
Clear the stuff from last hand and get ready for next
finish()¶
Not really a turn, just flip the downcard and report finalscore.
getScore()¶
Pick out the best score and return it
hit()¶
Called from player.hit and from dealer.
standing()¶
Just return if contestant is standing - satisfied with cards inhand
upScore()¶
Pick out the best score of the only the face up cards and return it
wentBust()¶
Set the bust status to true and show a message saying went bust
class bkJplayers.Dealer(win, deck, xmin, ymin, xmax, ymax)¶

Functions specific to the dealer (different than player). Theinit function from Contestant does what’s needed for this class.

deal()¶
The initial deal to dealer - one face up, one face down
play()¶
Dealer finishes the hand after player is finished
setStand()¶
Set the stand status to true and display a message that the dealerstands.
turn()¶
Dealer takes a to turn see what they come up with
class bkJplayers.Player(win, deck, xmin, ymin, xmax, ymax)¶

Functions specific to the player (different than dealer) Theinit function from Contestant does what’s needed for thisclass.

deal()¶
The initial deal to player - one card face up, one down
bkJhand.py
Each player’s hand of cards for a Blackjack game
class bkJhand.Twohands(win, xmin, xmax, ycenter, yscore)¶

One hand for all cards and another hand for just the face-up cards.The later is just for calculating the points of the face up cards, whichyour opponent can see. This class is a wrapper around the Hand class sothat the player classes only have to talk to one Hand class.

In hindsight, this may not have been the best approach. I could havechanged the Hand class to make note of the value of the face down card andkept two scores and two scoreBoxes.

clear()¶
Reset the Hand and remove displayed cards for a new hand
dealdown(card)¶
Deal a card Face down
dealup(card)¶
Deal a card Face up
flip2nd()¶
Flip the 2nd, face down, card over. Remove the face up score andshow the score for all cards.
score()¶
Return the list of scores
scoreBoxAMesg(mesg)¶
Display a message in the all card score box
scoreBoxBMesg(mesg)¶
Display a message in the face up card score box
setDealer()¶
Dealer calls this, just so we know this is the dealer’s hand. Itsets a Boolean variable Only difference is how the face down card isshown.
showScore()¶
Display the score for all cards
upScore()¶
Return the list of scores

Simple Blackjack In Python

upShowScore()¶
Display the score for the face up cards
class bkJhand.Hand(win, xmin, xmax, ycenter, yscore, label)¶

Manage the set of card in the hand. Keeps a list of the cards,shows them on the screen and counts the points. Also has functions todisplay the points for the hand, but the player and dealerdetermine when to do that.

clear()¶
Clear the screen and the hand of cards in prep for next hand
dealdown(card)¶
Add a dealt card face down
dealup(card)¶
Add a dealt card face up
flip2nd()¶
The second card is first dealt face down. At the last turnof each dealer and player, it is turned up.
hideScoreBox()¶
Clear the score box message area
score()¶
Return the set of current non-bust scores. If best is 21,return it as the only item in the score list.

How To Make Blackjack In Python

scoreBoxMesg(mesg)¶
Display some special message in the score box
showScore()¶
Display the current score for the hand
cards.py
Card and Deck classes for games played with playing cards -Blackjack being the first...
class cards.Card((rank, suit))¶

Playing card for games such as Blackjack - this is the non-drawn card,DrawnCard class extends this class to add drawing the card on thescreen.

Note: Deck’s deal method returns a tuple of form (rank, suit),and Card’s __init__ method takes the same tuple to create a deck,so they work nicely together, but may require special care if not usedtogether. This makes it easier to create the type of card needed.

BJValue()¶
Returns how may points the card is worth in Blackjack.Returns Ace as 1 point, so counting it as either1 or 11 point must be done some where else
draw(center)¶
Just a stub - it does nothing
drawDown(center)¶
Just a stub - it does nothing
flip()¶
Just a stub - it does nothing
getImageDown()¶
Just a stub - it does nothing
getImageName()¶
Just a stub - it does nothing
getRank()¶
Returns in range 1 (Ace) to 13 (King) for card
getSuit()¶
Returns suit (one of ‘d’, ‘c’, ‘h’, ‘s’) for diamonds,clubs, hearts or spades
moveTo(new)¶
Just a stub - it does nothing
undraw()¶
Just a stub - it does nothing
class cards.DrawnCard(win, cardTuple)¶

Playing card for games such as Blackjack - this is for a card objectthat we want to display in a graphics window. It extends the genericcard.

draw(center)¶
Show the image of the card face up
drawDown(center)¶
Show the image of the card face down
flip()¶
Flip the card over. Switch the image between face up and facedown
getImageDown()¶
Returns file name for face down image of the card
getImageName()¶
Returns file name for face up image of the card
moveTo(new)¶
Move the card image to a new location. new is a Point object
undraw()¶
Remove the image of the card from graphics window
class cards.CoveredCard(win, cardTuple)¶

This is a specialized card for games such as Blackjack.Like the DrawnCard, it draws an image of the card, but in the case whencard is supposed to be face down, instead of displaying the image forthe back of the card, it first shows the card face up, and then coversmost of the card with a face down image. This is to communicate to theuser that to their opponents, this is a face down card, but it lets themsee enough of the card to know what it is. It extends the DrawnCardClass. While self.face = True (it is face up) it behaves the same asDrawnCard class.

drawDown(center)¶
Show the image of the card covered by a face down card
flip()¶
Flip the card over. Switch the image between face up and facedown
moveTo(new)¶
Move the card image to a new location. new is a Point object
undraw()¶
Remove the image of the card from graphics window
class cards.Deck¶

A deck of 52 playing cards

cardsLeft()¶
Returns how many undealt cards are left in the deck
deal()¶
Deal one card from the deck. Returns a card object.
shuffle()¶
Just what the function name says
cards.unitTest()¶
Some unit testing code for deck and card classes: Card, DrawnCard and Covered Card
textboxes.py
Part of the Blackjack game. Displays the scoreboard and other messages.
class textboxes.ScoreBox(win, center, begin=None)¶

Just a Text area to keep the score in

setScore(score=None)¶
Show the score with the begin message, call with no parameters toremove the score from the screen
class textboxes.MessageBox(win, center)¶

Just a Text area to display a message in

setColor(color)¶
Change the text color
setMsg(msg=None)¶
Show a message, call with no parameters toremove the score from the screen
guiengine.py
A simple mouse click event catching engine with button callbacks and a simple Button widget.
Python
class guiengine.MouseTrap(win)¶

A class to catch mouse click events on buttons and run theappropriate call back function. This provides a framework forasychronous programming using the event catching and call backmodel.

Buttons are registered with the trap engine so that they arewatched for a mouse click over the button.

Important notes about call back functions:

1) If the class extends the Button class and has a function namedrun(), then it will be the call back. That implies that the classhas only one button. Probably more useful is to use the baseButton class or an extension of it and use the Button classessetRun() function to specifiy a function of choice for the callback. (See the Button class for more on info.)

2) Rather using a parameter to init or other special function tospecify which Button is the Quit button, the mechanism used isthat a call back function can cause the MousTrap engine to exit(and presumably, the rest of the program) by having the functionreturn a Boolean False value. Thus any function that wants theprogram to continue watching for mouse clicks needs to returnTrue. This can allow more than one exit path for error handlingand avoids needing to register a button as a Quit button. Butdon’t forget in coding the call back function to return thedesired value of True or False.

registerButton(button)¶
Register the button class, each button needs to have a run() methodand a clicked() boolean method (part of the base Button class).
run()¶
Run the event catcher waiting for mouse clicks.
class guiengine.Button(win, center, width, height, label)¶

A button is a labeled rectangle in a window.It is activated or deactivated with the activate()and deactivate() methods. The clicked(p) methodreturns true if the button is active and p is inside it.

activate()¶
Sets this button to ‘active’.
clicked(p)¶
Returns true if button active and p is inside
deactivate()¶
Sets this button to ‘inactive’.
getLabel()¶
Returns the label string of this button.
run()¶
The default event handler. It either runs the handler functionset in setRun() or it raises an exception.
setRun(function)¶
set a function to be the mouse click event handler
setUp(win, center, width, height, label)¶
set most of the Button data - not in init to make easierfor child class methods inheriting from Button.If called from child class with own run(), set self.runDef

How To Code Blackjack In Python

graphics.py
Simple object oriented graphics library for Introduction to Programmingusing Python by John Zelle, Ph.D.