Guide to Drawing Shapes and Loading Images in Pygame
Drawing Shapes and Images in Pygame
This beginner-friendly tutorial walks you through drawing shapes like rectangles and circles, and loading image files into your Pygame projects.
Setting Up Your Pygame Window
Start by importing Pygame and setting up your screen:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Drawing Shapes and Images")
Drawing Basic Shapes
Pygame makes it easy to draw basic shapes using built-in functions:
# Draw a red rectangle
pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 150))
# Draw a blue circle
pygame.draw.circle(screen, (0, 0, 255), (400, 300), 75)
# Draw a green line
pygame.draw.line(screen, (0, 255, 0), (0, 0), (800, 600), 5)
Loading and Displaying an Image
You can load and show image files using the `blit()` method:
# Load the image (make sure 'image.png' is in the same folder)
image = pygame.image.load('image.png')
# Display the image at position (300, 200)
screen.blit(image, (300, 200))
Make sure your image is a supported format like `.png`, `.jpg`, or `.bmp`.
Putting It All Together
Here’s how a complete loop with shapes and images might look:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # White background
pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 150))
pygame.draw.circle(screen, (0, 0, 255), (400, 300), 75)
pygame.draw.line(screen, (0, 255, 0), (0, 0), (800, 600), 5)
screen.blit(image, (300, 200))
pygame.display.flip()
pygame.quit()
Conclusion
Learning how to draw shapes and render images in Pygame gives you full control over 2D graphics. These basics are essential for building custom interfaces, characters, and levels in your games.
Also read: How to Animate Sprites in Pygame