Game Programming in Python. Part 1.

Welcome to this introduction to game programming in Python! In this series, we’ll use the pygame library to create interactive games step by step. By the end of Part 1, you’ll have a working window with basic graphics and event handling.

Why Python for Games?

Python might not be the first language that comes to mind for game development (C++ and Unity/C# are more common for professional games), but it’s an excellent choice for:

  • Learning game development concepts
  • Rapid prototyping
  • Creating small, fun games
  • Teaching programming through game creation

What is pygame?

pygame is a Python library built on top of SDL (Simple DirectMedia Layer) that provides functionality for creating games and multimedia applications. It handles:

  • Window creation and display
  • Drawing shapes, images, and text
  • Handling keyboard and mouse input
  • Playing sounds and music
  • Basic collision detection

Installation

pip install pygame

Your First pygame Window

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("My First Game")

# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Game loop
clock = pygame.time.Clock()

while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
    
    # Fill the screen with a color
    screen.fill(BLACK)
    
    # Draw some shapes
    pygame.draw.circle(screen, RED, (400, 300), 50)
    pygame.draw.rect(screen, GREEN, (100, 100, 150, 100))
    pygame.draw.line(screen, BLUE, (0, 0), (WIDTH, HEIGHT), 3)
    
    # Update the display
    pygame.display.flip()
    
    # Cap the frame rate
    clock.tick(60)

Understanding the Game Loop

The game loop is the heart of any game. It runs continuously until the game ends, and each iteration is called a “frame.” Our loop:

  1. Handles events: Keyboard input, mouse clicks, window close button
  2. Updates game state: Move objects, check collisions, update scores
  3. Draws everything: Clear screen, draw all objects, display result

Adding a Moving Object

import pygame
import sys

pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Ball")
clock = pygame.time.Clock()

# Ball properties
ball_x, ball_y = WIDTH // 2, HEIGHT // 2
ball_radius = 20
ball_speed_x = 5
ball_speed_y = 5

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # Move the ball
    ball_x += ball_speed_x
    ball_y += ball_speed_y
    
    # Bounce off walls
    if ball_x + ball_radius > WIDTH or ball_x - ball_radius < 0:
        ball_speed_x = -ball_speed_x
    if ball_y + ball_radius > HEIGHT or ball_y - ball_radius < 0:
        ball_speed_y = -ball_speed_y
    
    # Draw
    screen.fill((0, 0, 0))
    pygame.draw.circle(screen, (255, 100, 0), (int(ball_x), int(ball_y)), ball_radius)
    
    pygame.display.flip()
    clock.tick(60)

Handling Keyboard Input

There are two ways to handle keyboard input in pygame:

  • Events: For one-time actions (jumping, shooting)
  • Key state: For continuous movement (walking)
# Continuous movement with key state
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    player_x -= player_speed
if keys[pygame.K_RIGHT]:
    player_x += player_speed
if keys[pygame.K_UP]:
    player_y -= player_speed
if keys[pygame.K_DOWN]:
    player_y += player_speed

Summary

In Part 1, we learned:

  • How to set up a pygame window
  • The game loop structure (events → update → draw)
  • Drawing basic shapes (circles, rectangles, lines)
  • Creating moving objects with collision detection
  • Handling keyboard input

In Part 2, we'll build on these fundamentals to create a complete Tic-Tac-Toe game with a proper game board, win detection, and a restart mechanism. See you there!

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *