Pygame library is like a toolkit for making video games using the Python programming language. It provides a set of tools and functions that allow you to create graphics, handle user input (like keyboard or mouse actions), play sounds, and more.
Imagine you’re building a game from scratch, starting with just a blank screen. Pygame gives you all the building blocks you need to add graphics, characters, and interactive elements to that screen, allowing you to bring your game ideas to life.
let’s create a simple game using the Python library called Pygame, which is commonly used for game development and understand it. We’ll create a basic game where the player controls a character to avoid obstacles.
First copy the below code and save it in your editor and give the file name let say s.py (in my case)
# Import the Pygame library
import pygame
import sys
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("Dodger Game")
# Set up colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Set up player
player_width = 50
player_height = 50
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 10
player_speed = 5
player = pygame.Rect(player_x, player_y, player_width, player_height)
# Set up obstacles
obstacle_width = 50
obstacle_height = 50
obstacle_speed = 5
obstacle_gap = 200
obstacle_list = []
# Set up clock
clock = pygame.time.Clock()
# Main game loop
running = True
while running:
screen.fill(WHITE)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Player movement
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
# Spawn obstacles
if len(obstacle_list) == 0 or obstacle_list[-1].y > obstacle_gap:
obstacle_x = random.randint(0, screen_width - obstacle_width)
obstacle_y = 0 - obstacle_height
obstacle = pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height)
obstacle_list.append(obstacle)
# Move obstacles
for obstacle in obstacle_list:
obstacle.y += obstacle_speed
pygame.draw.rect(screen, RED, obstacle)
# Collision detection
if obstacle.colliderect(player):
pygame.quit()
sys.exit()
# Remove obstacles that go off-screen
for obstacle in obstacle_list:
if obstacle.y > screen_height:
obstacle_list.remove(obstacle)
# Draw player
pygame.draw.rect(screen, BLACK, player)
# Update the display
pygame.display.flip()
# Set the frame rate
clock.tick(60)
If you love to watch tutorial and code side by side you can watch the full tutorial of the same below and also don’t miss out on each line explanation below:
Let’s break each line of code and understand it:
import pygame: This line imports the Pygame library, which is used for game development in Python.import sys: This line imports thesysmodule, which provides access to some variables used or maintained by the Python interpreter and functions that interact with the interpreter.import random: This line imports therandommodule, which provides functions for generating random numbers and selecting random items from sequences.pygame.init(): This line initializes Pygame and prepares it for use. It initializes all the Pygame modules that are required for the game to function properly.screen_width = 800: This line sets the width of the game screen to 800 pixels.screen_height = 600: This line sets the height of the game screen to 600 pixels.screen = pygame.display.set_mode((screen_width, screen_height)): This line creates the game window with the specified dimensions using theset_mode()function. It returns aSurfaceobject representing the game window.pygame.display.set_caption("Dodger Game"): This line sets the title of the game window to “Dodger Game” using theset_caption()function.WHITE = (255, 255, 255),BLACK = (0, 0, 0),RED = (255, 0, 0): These lines define RGB color values for white, black, and red, respectively, which will be used for drawing objects in the game.player_width = 50,player_height = 50: These lines set the width and height of the player character to 50 pixels each.player_x = screen_width // 2 - player_width // 2: This line calculates the initial x-coordinate (horizontal position) for placing the player character at the center of the screen horizontally.player_y = screen_height - player_height - 10: This line calculates the initial y-coordinate (vertical position) for placing the player character near the bottom of the screen, leaving a small gap from the bottom.player_speed = 5: This line sets the speed at which the player character can move.player = pygame.Rect(player_x, player_y, player_width, player_height): This line creates a rectangle object (Rect) representing the player character with the specified dimensions and position.obstacle_width = 50,obstacle_height = 50: These lines set the width and height of the obstacles to 50 pixels each.obstacle_speed = 5: This line sets the speed at which the obstacles will move downward.obstacle_gap = 200: This line sets the gap between successive obstacles.obstacle_list = []: This line initializes an empty list to store the obstacle objects in the game.clock = pygame.time.Clock(): This line creates a Clock object to control the frame rate of the game.- The
while runningloop: This loop runs continuously until the player quits the game. screen.fill(WHITE): This line fills the screen with white color at the beginning of each iteration of the game loop, effectively clearing the screen.- Event handling: This section handles events such as quitting the game by checking for
pygame.QUITevents. - Player movement: This section handles player movement based on keyboard input (left and right arrow keys).
- Spawn obstacles: This section randomly spawns obstacles at the top of the screen.
- Move obstacles: This section moves the obstacles downward and checks for collisions with the player.
- Collision detection: This section checks if the player collides with any obstacles. If a collision occurs, the game quits.
- Remove obstacles: This section removes obstacles that have gone off-screen.
- Draw player: This section draws the player character on the screen.
pygame.display.flip(): This line updates the contents of the entire display.clock.tick(60): This line limits the frame rate to 60 frames per second, ensuring smooth gameplay.





Leave a Reply