So I have learned how to make a deck of cards with various functions through a course I am taking. Now, I would like to create a deck that can be used in the pygame window using the class I have made and my file of png
. When I run the various functions e.x. deal_card()
, it returns a card in the format '4 of Clubs', so I know it works. How can I get those to actually represent the png
of card images that I have?
import pygame
import os
from random import shuffle
# Initialize the pygame
pygame.init()
# Setting up the screen and background
screen = pygame.display.set_mode((800,600))
# Title and Icon of window
pygame.display.set_caption("Blackjack")
icon = pygame.image.load('card-game.png')
pygame.display.set_icon(icon)
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def __repr__(self):
# return "{} of {}".format(self.value, self.suit)
return f"{self.value} of {self.suit}"
class Deck:
def __init__(self):
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
self.cards = [Card(value, suit) for suit in suits for value in values]
def __repr__(self):
return f"Deck of {self.count()} cards"
def count(self):
return len(self.cards)
def _deal(self, num):
count = self.count()
actual = min([count,num])
if count == 0:
raise ValueError("All cards have been dealt")
cards = self.cards[-actual:]
self.cards = self.cards[:-actual]
return cards
def deal_card(self):
return self._deal(1)[0]
def deal_hand(self, hand_size):
return self._deal(hand_size)
def shuffle(self):
if self.count() < 52:
raise ValueError("Only full decks can be shuffled")
shuffle(self.cards)
return self
# Game Loop that ensures window is always running.
# We make sure we do our stuff in this loop
running = True
while running:
# RGB
screen.fill((50,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# RGB
screen.fill((50,0,0))
The file name of the card corresponds to the "official" string representation of the card (
__repr__
). Extend the name by the file extension (.png
) and usepygame.image.load
to load the card image: