Pygame – create a simple interactive game

Here’s an code example using Pygame to create a simple interactive game where the player controls a character to avoid obstacles.

import pygame
import random

# Initialize Pygame
pygame.init()

# Set up the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pygame Game Example")

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

# Player properties
player_width = 50
player_height = 50
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 20
player_speed = 5

# Obstacle properties
obstacle_width = 50
obstacle_height = 50
obstacle_speed = 7
obstacles = []

# Clock to control the frame rate
clock = pygame.time.Clock()

# Function to draw obstacles
def draw_obstacles():
    for obstacle in obstacles:
        pygame.draw.rect(screen, RED, obstacle)

# Main game loop
running = True
while running:
    screen.fill(WHITE)

    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Move the player
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
        player_x += player_speed

    # Create new obstacles
    if random.randint(0, 100) < 5:
        obstacle_x = random.randint(0, screen_width - obstacle_width)
        obstacle_y = -obstacle_height
        obstacles.append(pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height))

    # Move obstacles
    for obstacle in obstacles:
        obstacle.y += obstacle_speed
        if obstacle.y > screen_height:
            obstacles.remove(obstacle)

    # Check for collisions
    player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
    for obstacle in obstacles:
        if player_rect.colliderect(obstacle):
            running = False

    # Draw player and obstacles
    pygame.draw.rect(screen, BLACK, (player_x, player_y, player_width, player_height))
    draw_obstacles()

    # Update the display
    pygame.display.flip()

    # Cap the frame rate
    clock.tick(60)

# Quit Pygame
pygame.quit()
Code Explanation
  1. Initializing Pygame and Setting up the Screen:
    • pygame.init(): Initializes Pygame.
    • screen_width and screen_height: Define the dimensions of the game window.
    • screen = pygame.display.set_mode((screen_width, screen_height)): Sets up the game window with the specified dimensions.
    • pygame.display.set_caption("Pygame Game Example"): Sets the title of the game window.
  2. Defining Colors:
    • Colors are defined using RGB values for convenience in drawing shapes and objects later in the code.
  3. Player Properties:
    • player_width and player_height: Dimensions of the player character.
    • player_x and player_y: Initial position of the player character.
    • player_speed: Speed at which the player character moves.
  4. Obstacle Properties:
    • obstacle_width and obstacle_height: Dimensions of the obstacles.
    • obstacle_speed: Speed at which the obstacles fall from the top of the screen.
    • obstacles: List to store the positions of the obstacles.
  5. Clock:
    • clock = pygame.time.Clock(): Creates a clock object to control the frame rate of the game.
  6. Drawing Obstacles Function:
    • draw_obstacles(): A function to draw the obstacles on the screen.
  7. Main Game Loop:
    • while running:: The main loop that runs the game.
    • Event handling: Handles Pygame events such as quitting the game.
    • Player movement: Moves the player character based on keyboard input.
    • Creating new obstacles: Randomly generates new obstacles.
    • Moving obstacles: Updates the position of obstacles and removes them when they are off the screen.
    • Collision detection: Checks for collisions between the player character and obstacles.
    • Drawing: Draws the player character and obstacles on the screen.
    • Updating the display: Updates the game display.
    • Frame rate control: Caps the frame rate to 60 frames per second.
  8. Quitting Pygame:
    • pygame.quit(): Quits Pygame when the game loop ends.

This code example demonstrates a simple interactive game using Pygame, including player movement, obstacle generation, collision detection, and frame rate control.

Output

The output of the above code example is a simple interactive game window created using Pygame. In this game window, there will be a player character represented by a black rectangle that the player can control using the left and right arrow keys. Additionally, there will be red rectangles falling from the top of the screen, representing obstacles. The player’s objective is to avoid colliding with these obstacles while maneuvering the player character.

The game window will continue running until either the player collides with an obstacle or the player closes the window. Upon collision or window closure, the game will terminate, and the Pygame window will close.