Card, Deck, and Hand

First, copy over the Card class from the code you wrote for Chapter 2, Back to the Command Line - Basic Blackjack. There are no changes to the existing methods in this class, but we need to add one more for our graphical implementation:

@classmethod
def get_back_file(cls):
cls.back = tk.PhotoImage(file=assets_folder + "/back.png")

return cls.back

This new method will use a decorator to make it into a class method. A class method functions much like a regular method (or function), except that it does not require an instance of the class to work.

For this reason, we name the first variable cls instead of self. Python will automatically pass a reference to the class itself to a class method, meaning just as is the case with a regular method, we will call it with one fewer argument than it is defined with.

Our get_back_file class method returns the image back.png stored in our assets folder. This allows the graphical piece of our application to acquire and draw this particular image onto the screen when the dealer has a card which is face down.

In order for an image to be usable by Tkinter, we need to create a PhotoImage instance. When we initialize a PhotoImage, we can use the file argument to supply the path to the image file, then Tkinter will handle the rest.

Something important to note when using a PhotoImage in Tkinter is that the object will be garbage collected if no reference to it is kept. In order to avoid this, we assign the PhotoImage to the back attribute of our Card class. This allows us to keep a reference to it for as long as a Card instance sticks around.

Our Deck class does not need to change for now. If you are using a new file, simply copy and paste this code over from the previous chapter.

Our Hand class does not need anything new either, although there is no longer any need for the display method since we are not using print at all anymore, so either delete the method or don't copy it over.

Instead of a class holding our game loop, we will maintain a GameState class which handles the state of the current game. Our GameScreen class, which handles the graphical elements of the game, can use this class to access the state of the game at any time it needs to redraw graphics.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset