杰瑞科技汇

python pygame blit

Of course! Let's dive deep into pygame.display.blit(). This is one of the most fundamental and frequently used functions in Pygame.

python pygame blit-图1
(图片来源网络,侵删)

What is blit()?

The name blit stands for BLock ITransfer. In simple terms, it's the command to copy a source surface onto a destination surface.

Think of it like cutting a picture out of one magazine (source) and pasting it onto another (destination). You can control where you paste it (the coordinates) and even if you want to rotate or scale it (though that's more advanced).


The Basic Syntax

The function is called on the destination surface object.

destination_surface.blit(source_surface, (x, y))

Let's break down the arguments:

python pygame blit-图2
(图片来源网络,侵删)
  1. destination_surface: This is the surface you are drawing onto. This is almost always your main game window, which you get from pygame.display.set_mode().
  2. source_surface: This is the surface you are copying from. This could be an image loaded with pygame.image.load(), a shape you've drawn on a separate surface, or text rendered with pygame.font.Font.render().
  3. (x, y): This is a tuple containing the coordinates for the top-left corner of the source_surface on the destination_surface. The origin (0, 0) is the top-left corner of the destination surface.

A Simple, Complete Example

This example will load an image and draw it in the center of the window.

Get an image: Save a simple image named player.png in the same folder as your Python script. You can download any small image, or create a simple one with a paint program.

The Python Code (blit_example.py):

import pygame
import sys
# 1. Initialize Pygame
pygame.init()
# 2. Set up the display (create a window)
#    This is our main 'destination_surface'
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pygame Blit Example")
# 3. Load an image
#    This is our 'source_surface'
try:
    player_image = pygame.image.load("player.png").convert_alpha()
except pygame.error:
    print("Error: Could not load 'player.png'. Make sure the image is in the same directory.")
    sys.exit()
# Optional: Scale the image if it's too large
player_image = pygame.transform.scale(player_image, (100, 100))
# 4. Main game loop
running = True
clock = pygame.time.Clock()
while running:
    # --- Event Handling ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # --- Drawing Logic ---
    # First, fill the screen with a background color (important!)
    screen.fill((135, 206, 235)) # A nice sky blue
    # Calculate the position to center the image
    image_x = (screen_width - player_image.get_width()) // 2
    image_y = (screen_height - player_image.get_height()) // 2
    # Use blit to copy the player image onto the screen
    screen.blit(player_image, (image_x, image_y))
    # --- Update the Display ---
    # This line takes everything drawn and shows it on the screen
    pygame.display.flip()
    # --- Cap the Frame Rate ---
    clock.tick(60) # 60 FPS
# 5. Quit Pygame
pygame.quit()
sys.exit()

Key Concepts Explained

Surfaces are Just canvases

Everything you draw in Pygame happens on a Surface. Your main window is a surface. When you load an image, it becomes a surface. When you create text, it becomes a surface. blit() is how you combine these surfaces.

python pygame blit-图3
(图片来源网络,侵删)

The Drawing Order is Crucial

blit() works like layers in Photoshop. The order in which you call blit() matters. The last thing you blit will appear on top of everything else.

Example of Drawing Order:

# Background
screen.fill((0, 0, 0)) # Black screen
# Draw a red square first
red_square = pygame.Surface((100, 100))
red_square.fill((255, 0, 0))
screen.blit(red_square, (200, 200))
# Draw a blue circle on TOP of the square
blue_circle = pygame.Surface((100, 100), pygame.SRCALPHA) # Use SRCALPHA for transparency
pygame.draw.circle(blue_circle, (0, 0, 255), (50, 50), 50)
screen.blit(blue_circle, (225, 225)) # Overlap the square
pygame.display.flip()

In this code, the blue circle will appear to be on top of the red square because it was blitted second.

pygame.display.flip() vs. pygame.display.update()

You'll notice both functions in tutorials. What's the difference?

  • pygame.display.flip(): Updates the entire display. It's simpler and works perfectly for most 2D games.
  • pygame.display.update(): Can update only a specific portion of the screen if you give it a rectangle. This is more efficient for performance if you're only moving a small object and redrawing that part of the screen.

For beginners, always use pygame.display.flip() at the end of your drawing loop.


Advanced blit() Features

The blit() function is more powerful than its simple form suggests. It has a third, optional argument: special_flags.

destination_surface.blit(source, dest, special_flags)

BLEND_ADD

Adds the colors of the source to the destination. Great for light effects or energy glows.

# Create a surface for the glow
glow = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.circle(glow, (100, 100, 255, 150), (100, 100), 100) # Semi-transparent blue
# Blit with blend_add
screen.blit(glow, (300, 200), special_flags=pygame.BLEND_ADD)

BLEND_MULT

Multiplies the colors. This is excellent for darkening an area or creating shadows.

# Create a dark overlay
shadow = pygame.Surface((screen_width, 100), pygame.SRCALPHA)
shadow.fill((0, 0, 0, 128)) # Semi-transparent black
# Blit with blend_mult to darken the bottom of the screen
screen.blit(shadow, (0, screen_height - 100), special_flags=pygame.BLEND_MULT)

BLEND_RGBA_SUBTRACT

Subtracts the colors. Useful for creating "dark spots" or void-like effects.

Using a Rect object instead of a tuple

You can also pass a pygame.Rect object as the destination coordinates. This is very useful because Rect objects have handy methods for positioning, like center, topleft, midright, etc.

player_image_rect = player_image.get_rect() # Get a rect the size of the image
# Easily center the rect on the screen
player_image_rect.center = (screen_width // 2, screen_height // 2)
# Blit using the rect object
screen.blit(player_image, player_image_rect)

Summary

Concept Description Example
What it is Copies a source surface onto a destination surface. screen.blit(image, (x, y))
Key Rule Drawing order matters. Last blit is on top. Draw background, then player, then UI.
Destination Usually the main game window. screen = pygame.display.set_mode(...)
Source An image, text, or a shape you've created. player_image = pygame.image.load(...)
Coordinates The top-left corner of the source on the destination. (100, 50)
Update Screen pygame.display.flip() shows all the blit operations. pygame.display.flip()
Advanced special_flags for blending effects like BLEND_ADD. screen.blit(glow, pos, flags=pygame.BLEND_ADD)
Easy Positioning Use a Rect object and its properties. image_rect = image.get_rect(center=(400, 300))

Mastering blit() is the first step to building any visual game in Pygame. It's the core of how you construct every scene.

分享:
扫描分享到社交APP
上一篇
下一篇