Creating a Code Rain Animation Using Pygame

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to create a simple code rain animation using the Pygame library in Python. Code rain animations, popularized by movies like "The Matrix," display falling characters on a screen, giving the impression of a digital rain. We'll use the Pygame library to create the animation and display it on a window.

👀 Preview

Code rain

ðŸŽŊ Tasks

In this project, you will learn:

  • How to set up the animation window in Pygame
  • How to define a "Raindrop" class to represent each falling character
  • How to generate and display multiple instances of the Raindrop class
  • How to implement the main loop to continuously update the animation
  • How to close the animation window properly

🏆 Achievements

After completing this project, you will be able to:

  • Use the Pygame library to create animations
  • Define and use a class in Python
  • Handle user events in Pygame
  • Create a main animation loop in Pygame
  • Properly close an animation window in Pygame

Create the Project Files

Before you start, make sure you have Pygame installed. If you don't have Pygame installed, you can do so using pip:

sudo pip install pygame

Next, create a file named code_rain.py in your preferred code editor or IDE. This will be the main file where you write the code for the Pong game.

cd ~/project
touch code_rain.py
âœĻ Check Solution and Practice

Setting up the Animation Window

Inside the code_rain.py file, import the required libraries at the beginning of the code:

import pygame
import random

Then, initialize Pygame by calling pygame.init():

pygame.init()

Next, set up the animation window by defining the width, height, and caption:

width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Code Rain")

Define the colors used in the animation:

background_color = (0, 0, 0)
text_color = (0, 255, 0)

Font settings:

font = pygame.font.Font(None, 36)
âœĻ Check Solution and Practice

Defining the Raindrop Class

Next, we define the Raindrop class, which represents each falling character in the code rain animation. The Raindrop class contains attributes such as the initial position, text, and falling speed of each raindrop.

class Raindrop:
    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)
        self.text = chr(random.randint(33, 126))
        self.speed = random.randint(1, 5)

    def fall(self):
        self.y += self.speed
        if self.y > height:
            self.y = 0
            self.x = random.randint(0, width)

    def display(self):
        text_surface = font.render(self.text, True, text_color)
        screen.blit(text_surface, (self.x, self.y))

The __init__ method is called when the class is instantiated to initialize the properties of the raindrop, including random initial position (x, y), random text characters (ASCII between 33 and 126), and random falling speed (between 1 and 5).

The fall method is used to move raindrops downward. It increases the value of self.y according to the velocity of the raindrop. If the raindrop moves out of the screen (when self.y is larger than the screen height), reset it to the top of the screen and randomly select a new x position on the screen.

The display method is used to display raindrops. It uses the font.render function from the pygame library to create a text surface and render it at the raindrop position (self.x, self.y) on the screen.

âœĻ Check Solution and Practice

Generating and Displaying Raindrops

Now, we'll create and display multiple instances of the Raindrop class to simulate the falling characters. The code below generates a specified number of raindrops and updates their positions on the screen.

num_raindrops = 100
raindrops = [Raindrop() for _ in range(num_raindrops)]
âœĻ Check Solution and Practice

Handling the Main Loop

In this step, we implement the main loop that handles the animation by continuously updating the screen. It also listens for the quit event to close the window properly.

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill(background_color)

    for drop in raindrops:
        drop.fall()
        drop.display()

    pygame.display.flip()

pygame.quit()

The main body of the animation loop is a while loop, where the running variable controls the loop. The loop will only continue running if running is True.

Within the animation loop, use pygame.event.get() to get a list of pygame events and examine each event by iterating over the list of events. In this case, the main check is whether there is a exit event pygame.QUIT, which is generated when the user closes the animation window. If an exit event is detected, set running to False to exit the animation loop.

screen.fill(background_color) fills the background color of the animation window screen to cover the contents of the previous frame in preparation for drawing a new frame.

Iterate through the raindrops list, calling the fall() method on each raindrop object to make it fall, and calling the display() method to display the raindrop on the game window.

pygame.display.flip() is used to refresh all of the above drawing operations to the screen for animation.

After the animation loop ends, call pygame.quit() to clean up the pygame library and exit the animation.

âœĻ Check Solution and Practice

Run the Project

Finally, swicth to Desktop and run the project using the following command:

python code_rain.py
Code rain
âœĻ Check Solution and Practice

Summary

In this project, you learned how to create a simple code rain animation using the Pygame library in Python. You initialized the Pygame module, defined the Raindrop class, generated and displayed multiple raindrops, and implemented the main loop to handle the animation. This project provides a basic understanding of how to create simple animations using Pygame.

Other Python Tutorials you may like