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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) pygame(("`Pygame`")) -.-> pygame/CoreConceptsGroup(["`Core Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") pygame/CoreConceptsGroup -.-> pygame/display("`Display Management`") pygame/CoreConceptsGroup -.-> pygame/event("`Event Handling`") pygame/CoreConceptsGroup -.-> pygame/font("`Font Styling`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/while_loops("`While Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} pygame/display -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} pygame/event -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} pygame/font -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/booleans -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/conditional_statements -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/for_loops -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/while_loops -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/list_comprehensions -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/lists -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/tuples -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/function_definition -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/importing_modules -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/standard_libraries -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/classes_objects -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/constructor -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/polymorphism -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/encapsulation -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/math_random -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} python/build_in_functions -.-> lab-298869{{"`Creating a Code Rain Animation Using Pygame`"}} end

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

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)

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.

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)]

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.

Run the Project

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

python code_rain.py
Code rain

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