STep 0: Import

Python wrapper for the SDL library, which stands for Simple DirectMedia Layer. SDL provides cross-platform access to your system’s underlying multimedia hardware components, such as sound, video, mouse, keyboard, and joystick. pygame started life as a replacement for the stalled PySDL project. The cross-platform nature of both SDL and pygame means you can write games and rich multimedia Python programs for every platform that supports them!

To install pygame on your platform, use the appropriate pip command:

pip install pygame

Pygames has many modules that provide abstract access to specific hardware on your system, as well as uniform methods to work with that hardware. For example, display allows uniform access to your video display, while joystick allows abstract control of your joystick.

STEP 1: Setting Up the Game Environment

Introduction: Create a simple window with a circle. This code provides you the starting point of Pygames, where we are creating a simple window with fixed size

Coding Example:

# Import and initialize the pygame library
import pygame
pygame.init()

# Define constants for the screen width and height
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Set up the drawing window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Run until the user asks to quit
running = True
while running:

    # Did the user click the window close button?
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the background with white
    screen.fill((255, 255, 255))

    # Draw a solid blue circle in the center
    pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)

    # Flip the display
    pygame.display.flip()

# Done! Time to quit.
pygame.quit()


STep 2: Rendering

In Pygame, drawing on the screen involves understanding the coordinate system used to position elements. The screen is treated as a grid with coordinates that help place objects precisely where you want them.

Coordinate System in Pygame

  • Origin (0, 0): The top-left corner of the window or screen is the origin, where the coordinate (0, 0) is located.
  • X-Axis: The x-axis runs horizontally across the screen. Increasing values on the x-axis move from left to right.
  • Y-Axis: The y-axis runs vertically. Increasing values on the y-axis move from top to bottom.

The call to pygame.display.flip() is made after the call to blit(). This updates the entire screen with everything that’s been drawn since the last flip. Without the call to .flip(), nothing is shown.

1. blit()

The blit() function is an abbreviation of “block transfer.” It is used to copy the contents of one surface to another. In the context of Pygame, a “surface” represents an off-screen buffer where you can draw or manipulate images. Here’s what blit() is primarily used for:

2. flip() and update()

flip() is used to update the entire screen. In double-buffering, which Pygame uses by default, all drawing operations are done on a hidden buffer (not visible on the screen). Once all drawing is completed (using blit()), flip() is called to make the hidden buffer visible, effectively updating the entire display.

  • Efficiency: This method is efficient because it prevents partial and frequent screen updates, which can cause flickering and performance issues. Instead, the screen is updated all at once.
  • Double Buffering: flip() is part of the double buffering technique where two buffers are used: one for displaying on the screen and the other for drawing. When you call flip(), Pygame swaps these buffers, making the drawing buffer visible.

Alternatively, pygame.display.update() can be used to update only parts of the screen (instead of the entire area), which is more efficient if only small portions of the screen change between frames.

Code



import pygame
import random
import sys

# Helps us access system folders
import os                                           

# Define constants for the screen width and height
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 600

# Times/sec screen is updated
FPS = 60                                            

# Define colours to reuse again and again (RGB ntotation)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

# Import pygame.locals for easier access to key coordinates
from pygame.locals import (
    K_UP,
    K_DOWN,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

# Initialize the pygame library
pygame.init()

# Initialize the pygame sound library
pygame.mixer.init()

# Set up the drawing window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Set up in-game clock for FPS and deltatime
clock = pygame.time.Clock()

# Set title for the game window
pygame.display.set_caption("CodeCrafters")

## GAME LOOP
game_over = True
running = True
while(running):
    # Keep loop running at the right speed
    clock.tick(FPS)

    # Look for any events happening in the game
    for event in pygame.event.get():
        #Check for closing the window
        if(event.type == pygame.QUIT):
            running = False

        # Check for inputs in the game
        elif(event.type == KEYDOWN):
            # Check for Escape Key
            if(event.key == K_ESCAPE):
                running = False

            # Check for Up Key
        elif(event.key == K_UP):
                print("Pressed up!")

    # Fill the screen with white
    screen.fill(WHITE)

    # Create a surface and pass in a tuple containing its length and width
    surf = pygame.Surface((50, 50))

    # Give the surface a color to separate it from the background
    surf.fill(BLACK)
    rect = surf.get_rect()

    # This line says "Draw surf onto the screen at the center"
    screen.blit(surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))

    # *After* drawing everything, flip the display
    pygame.display.flip()

# Closing everything related to Pygames and freeing up memory
pygame.quit()
sys.exit()