Create a Simple Card Game with Pygame

Hey there, aspiring game developers! Have you ever wanted to create your own games but felt intimidated by complex game engines? Well, today, we’re going to dive into the exciting world of Pygame, a fantastic library that makes game development in Python fun and accessible, even for absolute beginners.

In this blog post, we’ll walk through the process of building a super simple card game. Don’t worry, we won’t be building a full-fledged poker game just yet, but we’ll lay the groundwork by learning how to represent a deck of cards, shuffle them, deal a hand, and display them in a Pygame window. It’s a perfect way to get your feet wet with game development!

What is Pygame?

Pygame is a set of Python modules designed for writing video games. It provides tools and functions for graphics, sound, and input, allowing you to create 2D games with relative ease. Think of it as a toolbox specifically crafted for building games using Python.

Why Pygame for Beginners?

  • Python-based: If you already know Python, you’re halfway there! Pygame uses standard Python syntax.
  • Simple to learn: Its API (Application Programming Interface – basically, the set of tools and functions it offers) is straightforward.
  • Great for 2D games: Perfect for card games, platformers, puzzles, and more.
  • Active community: Plenty of resources and help available online.

Getting Started: Prerequisites

Before we jump into coding, you’ll need two things:

  1. Python: Make sure you have Python installed on your computer (version 3.6 or newer is recommended). You can download it from the official Python website.
  2. Pygame: Once Python is installed, you can install Pygame using pip, Python’s package installer. Open your terminal or command prompt and type:

    bash
    pip install pygame

    • Supplementary Explanation: pip install pygame
      pip is a tool that helps you install and manage Python packages (libraries or modules written by others that you can use in your own code). When you type pip install pygame, you’re telling Python to download and set up the Pygame library so you can use it in your projects.

Our Simple Card Game Idea

For this project, our goal is modest but educational:
* Create a standard 52-card deck.
* Shuffle the deck.
* Deal a 5-card hand to the “player.”
* Display these 5 cards on a Pygame window.

We’ll represent cards using text (e.g., “A♠” for Ace of Spades) to keep things simple and avoid needing external image files for now.

Step-by-Step Implementation

Let’s break down the code into manageable chunks.

Step 1: Setting Up the Basic Pygame Window

Every Pygame application starts with some boilerplate code. This sets up the window where our game will be displayed and handles basic events like closing the window.

import pygame
import random # We'll need this for shuffling cards later

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

pygame.display.set_caption("Simple Card Game")

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

running = True

while running:
    # Event handling
    for event in pygame.event.get():
        # Supplementary Explanation: pygame.event.get()
        # This function checks for any events (like mouse clicks, key presses, or closing the window) that have happened since the last check.
        if event.type == pygame.QUIT:
            # Supplementary Explanation: pygame.QUIT
            # This is a specific event that occurs when the user clicks the 'X' button to close the game window.
            running = False

    # Drawing
    screen.fill(GREEN) # Fill the background with green (like a card table)
    # Supplementary Explanation: screen.fill()
    # This command fills the entire screen surface with a specified color. You usually do this at the start of each loop
    # to "clear" the previous frame before drawing new things.

    # Update the display
    pygame.display.flip() # Or pygame.display.update()
    # Supplementary Explanation: pygame.display.flip()
    # This command makes everything you've drawn on the 'screen' surface actually visible on your monitor.
    # Think of it as showing the completed drawing to the player.

pygame.quit()

If you run this code, you’ll see a green window pop up, and you can close it by clicking the ‘X’ button.

Step 2: Representing the Deck of Cards

Now, let’s create our deck of cards. A standard deck has four suits (Hearts, Diamonds, Clubs, Spades) and 13 ranks (2-10, Jack, Queen, King, Ace).

SUITS = ['Hearts', 'Diamonds', 'JOKER', 'Clubs', 'Spades']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
SUIT_SYMBOLS = {'Hearts': '♥', 'Diamonds': '♦', 'Clubs': '♣', 'Spades': '♠', 'JOKER': '🃏'}

deck = []
for suit in SUITS:
    if suit == 'JOKER':
        # Add two jokers
        deck.append('JOKER')
        deck.append('JOKER')
    else:
        for rank in RANKS:
            deck.append(f"{rank}{SUIT_SYMBOLS[suit]}")

Step 3: Shuffling and Dealing a Hand

We’ll use Python’s built-in random module to shuffle our deck list and then pop() cards off to deal a hand.

random.shuffle(deck)

player_hand = []
num_cards_to_deal = 5
for _ in range(num_cards_to_deal):
    if deck: # Make sure the deck isn't empty
        player_hand.append(deck.pop(0)) # Deal from the top of the deck
        # Supplementary Explanation: list.pop(0)
        # The `pop()` method removes an item from a list at a given position and returns that item.
        # `pop(0)` removes the first item, simulating dealing from the top of the deck.
    else:
        print("Deck is empty!")
        break # Stop if deck is empty

print("Player Hand:", player_hand) # For debugging in the console

Step 4: Displaying Cards on Screen

To display text in Pygame, we need to create a Font object, then render the text into a surface, and finally blit (draw) that surface onto our main screen.

font = pygame.font.Font(None, 40) # Default font, size 40


    # Display the player's hand
    x_offset = 50
    y_offset = 50
    card_width = 100
    card_height = 150
    card_margin = 20

    for i, card_text in enumerate(player_hand):
        # Create a surface for the card background
        card_rect = pygame.Rect(x_offset + i * (card_width + card_margin), y_offset, card_width, card_height)
        pygame.draw.rect(screen, WHITE, card_rect, 0, 5) # Draw white rectangle for card
        pygame.draw.rect(screen, BLACK, card_rect, 3, 5) # Draw black border

        # Render the card text
        text_surface = font.render(card_text, True, BLACK) # Text, Antialias, Color
        # Supplementary Explanation: font.render(text, antialias, color)
        # This creates a *new surface* that contains your text. `True` for antialias makes the text smoother.
        # It doesn't draw directly to the screen; it just prepares the text image.

        # Center the text on the card
        text_rect = text_surface.get_rect(center=card_rect.center)
        screen.blit(text_surface, text_rect)
        # Supplementary Explanation: screen.blit(source_surface, destination_rect)
        # This draws one surface (like our text_surface) onto another surface (our main screen).
        # We use `text_rect.center` to place the text nicely in the middle of our card rectangle.

    # ... (rest of the game loop and pygame.quit()) ...

Putting It All Together: The Full Code

Here’s the complete code for our simple card game. Copy and paste this into a Python file (e.g., card_game.py) and run it!

import pygame
import random

pygame.init()

SCREEN_WIDTH = 900 # Slightly wider to fit 5 cards better
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Simple Card Game")

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (50, 150, 50) # A nice table green

SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
SUIT_SYMBOLS = {'Hearts': '♥', 'Diamonds': '♦', 'Clubs': '♣', 'Spades': '♠'}

deck = []
for suit in SUITS:
    for rank in RANKS:
        deck.append(f"{rank}{SUIT_SYMBOLS[suit]}")

random.shuffle(deck)

player_hand = []
num_cards_to_deal = 5
for _ in range(num_cards_to_deal):
    if deck:
        player_hand.append(deck.pop(0))
    else:
        print("Deck is empty!")
        break

font = pygame.font.Font(None, 40) # Default font, size 40

running = True

while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Drawing
    screen.fill(GREEN) # Fill the background with green

    # Display the player's hand
    x_start = (SCREEN_WIDTH - (5 * (100 + 20) - 20)) // 2 # Center the hand
    y_offset = SCREEN_HEIGHT // 2 - 75 # Center vertically
    card_width = 100
    card_height = 150
    card_margin = 20

    for i, card_text in enumerate(player_hand):
        # Position for the current card
        card_x = x_start + i * (card_width + card_margin)
        card_rect = pygame.Rect(card_x, y_offset, card_width, card_height)

        # Draw card background and border
        pygame.draw.rect(screen, WHITE, card_rect, 0, 5) # Fill with white, rounded corners
        pygame.draw.rect(screen, BLACK, card_rect, 3, 5) # Draw black border, rounded corners

        # Render the card text
        text_surface = font.render(card_text, True, BLACK)

        # Center the text on the card
        text_rect = text_surface.get_rect(center=card_rect.center)
        screen.blit(text_surface, text_rect)

    # Update the display
    pygame.display.flip()

pygame.quit()

What’s Next? Ideas for Your Card Game!

Congratulations! You’ve successfully created a basic Pygame application that shuffles cards and deals a hand. This is just the beginning. Here are some ideas to expand your game:

  • Add card images: Instead of text, load actual card images for a more visual experience.
  • Implement game logic: Add rules for a simple game like “Higher or Lower,” “War,” or “Blackjack.”
  • Player interaction: Allow players to click on cards, draw new cards, or discard cards.
  • Multiple players: Extend the game to support dealing hands to more than one player.
  • Buttons: Add Pygame buttons to “Deal New Hand” or “Quit.”
  • Scorekeeping: Keep track of points or wins.

Conclusion

Pygame is a powerful yet approachable library for game development in Python. By following these steps, you’ve learned the fundamental concepts of setting up a Pygame window, handling events, drawing shapes, displaying text, and managing game elements like a deck of cards. Keep experimenting, keep building, and most importantly, have fun creating your own games!


Comments

Leave a Reply