Step 1: Install Pygame
First, you need to install Pygame. You can do this using pip:
pip install pygame
Step 2: Create a Simple Pygame Window
Here’s a basic example of how to create a window and display a colored background.
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up the display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Graphical Genius Tutorial')
# Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Fill the background with a color (RGB)
screen.fill((0, 128, 255)) # Blue color
# Update the display
pygame.display.flip()
Step 3: Drawing Shapes
You can draw shapes like rectangles, circles, and lines. Here’s how to draw a rectangle and a circle:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Drawing Shapes')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255)) # White background
# Draw a rectangle
pygame.draw.rect(screen, (255, 0, 0), (50, 50, 200, 100)) # Red rectangle
# Draw a circle
pygame.draw.circle(screen, (0, 255, 0), (400, 300), 50) # Green circle
pygame.display.flip()
Step 4: Handling User Input
You can handle keyboard and mouse events to make your application interactive. Here’s an example that moves a rectangle with arrow keys:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Move the Rectangle')
# Rectangle position
rect_x, rect_y = 100, 100
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
rect_x -= 5
if keys[pygame.K_RIGHT]:
rect_x += 5
if keys[pygame.K_UP]:
rect_y -= 5
if keys[pygame.K_DOWN]:
rect_y += 5
screen.fill((255, 255, 255)) # White background
pygame.draw.rect(screen, (0, 0, 255), (rect_x, rect_y, 50, 50)) # Blue rectangle
pygame.display.flip()
Step 5: Adding Images and Text
You can also display images and text. Here’s an example that adds a text display:
import pygameimport sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Text and Images')
# Load a font
font = pygame.font.Font(None, 74)
text_surface = font.render('Hello, Pygame!', True, (0, 0, 0)) # Black text
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255)) # White background
screen.blit(text_surface, (200, 250)) # Draw the text
pygame.display.flip()
Leave a Reply