### Main Application Loop - Python Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt The main Python function `run_matrix_rain` orchestrates the application. It initializes Pygame, loads and processes an image, sets up the display and background, centers the image, creates symbol columns, and manages the main rendering loop. It handles user input for quitting and toggling drawing modes, along with a fade effect for the background. Dependencies include Pygame, config, image, symbol modules, and the random module. ```python import sys import pygame from config import Config from image import Image from symbol import Symbol, SymbolColumn from random import randrange def run_matrix_rain(image_path): # Initialize Pygame pygame.init() # Load and process image img = Image(image_path) img.scale_image(Config.IMG_SCALE) img.calculate_all_threshold_positions( Config.FONT_SIZE, Config.ISOLATE_COLOR ) # Setup display screen = pygame.display.set_mode(Config.SCREEN_SIZE, pygame.RESIZABLE) pygame.display.set_caption("Matrix Rain") background = pygame.Surface(Config.SCREEN_SIZE) background.set_alpha(Config.STARTING_ALPHA) clock = pygame.time.Clock() # Center image on screen s_x, s_y = (Config.SCREEN_WIDTH // 2, Config.SCREEN_HEIGHT // 2) i_x, i_y = img.get_centre() vec_x = round((s_x - i_x) / Config.FONT_SIZE) vec_y = round((s_y - i_y) / Config.FONT_SIZE) img.translate_points_by_vector((vec_x * Config.FONT_SIZE, vec_y * Config.FONT_SIZE)) # Create symbol columns symbol_columns = [ SymbolColumn( x, randrange(0, Config.SCREEN_HEIGHT), img.get_positions_for_column(x) ) for x in range(0, Config.SCREEN_WIDTH, Config.FONT_SIZE) ] # Setup for JUST_DISPLAY_MODE symbol_list = [] if Config.JUST_DISPLAY_MODE: for x, yPositions in img.column_positions.items(): for y in yPositions: symbol_list.append(Symbol(x, y, 0, pygame.Color("white"))) toggle_drawing = True is_running = True while is_running: for event in pygame.event.get(): if event.type == pygame.QUIT: is_running = False # Black background with fade effect screen.blit(background, (0, 0)) background.fill(pygame.Color("black")) # RAIN_ACCUMULATION_MODE: place symbols as columns reach positions if Config.RAIN_ACCUMULATION_MODE and toggle_drawing and img.columns_left_to_place(): for symbol_column in symbol_columns: if (img.column_has_positions(symbol_column.x) and symbol_column.get_white_symbol().get_y_position() == img.get_next_position_for_column(symbol_column.x)): symbol_column.place_white_symbol() img.get_positions_for_column(symbol_column.x).pop(0) # JUST_DISPLAY_MODE: show all symbols at once elif Config.JUST_DISPLAY_MODE and toggle_drawing: for symbol in symbol_list: symbol.update() symbol.draw(background) # Draw all columns for symbol_column in symbol_columns: symbol_column.draw(background) # Fade effect adjustment if ( not pygame.time.get_ticks() % Config.FADE_RATE and Config.STARTING_ALPHA < Config.ALPHA_LIMIT ): Config.STARTING_ALPHA += Config.FADE_ADJUSTMENT background.set_alpha(Config.STARTING_ALPHA) # Toggle drawing with Enter key keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_RETURN]: toggle_drawing = not toggle_drawing pygame.display.update() clock.tick(Config.FPS_LIMIT) pygame.display.quit() pygame.quit() # Run the application if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python -m src.main ") sys.exit(1) run_matrix_rain(sys.argv[1]) ``` -------------------------------- ### Image Debug Visualization - Python Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt This Python snippet demonstrates how to use the `Image` module in debug mode to visualize calculated character positions from an image. It loads an image, scales it, sets up a Pygame window, and then calls `calculate_all_threshold_positions`. This allows developers to see the computed block shape for character placement. Dependencies include Pygame, config, and the image module. ```python import sys import pygame from config import Config from image import Image # Enable debug mode Config.debug = True # Load and process image img = Image("images/logo.png") img.scale_image(0.6) width, height = img.get_dimensions() win = pygame.display.set_mode((width, height)) pygame.display.set_caption("Image to font boxes calculated") # Calculate positions with debug output img.calculate_all_threshold_positions(Config.FONT_SIZE, Config.ISOLATE_COLOR) # Output: "block shape: (10, 10)" ``` -------------------------------- ### Validate Configuration Settings (Python) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt This snippet provides a Python function to validate application configuration settings. It checks for mutually exclusive display modes (JUST_DISPLAY_MODE and RAIN_ACCUMULATION_MODE) and image processing modes (DRAW_LINES_OF_IMAGE and SINGLE_COLOR_SELECTION). It also validates that exactly one command-line argument (the image path) is provided. Errors raise ValueErrors. ```python import sys from config import Config def validate_config(): # Check for mutually exclusive display modes if Config.JUST_DISPLAY_MODE and Config.RAIN_ACCUMULATION_MODE: raise ValueError("CAN'T HAVE BOTH MODES ACTIVATED!, CHECK config.py") # Check for mutually exclusive image processing modes if Config.DRAW_LINES_OF_IMAGE and Config.SINGLE_COLOR_SELECTION: raise ValueError("Can't select more than one picture processing mode") # Validate command line arguments if len(sys.argv) != 2: raise ValueError("Must add image to input in command line argument") return True # Usage try: validate_config() print("Configuration valid") except ValueError as e: print(f"Configuration error: {e}") sys.exit(1) ``` -------------------------------- ### Generate Character Surfaces (Pygame) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt This snippet demonstrates generating renderable character surfaces using Pygame and a custom symbol module. It loads a Matrix font and creates surfaces for specified character sets and colors. The `get_char_surfaces` function handles missing glyphs automatically. The generated surfaces can then be used for rendering on the screen. ```python import pygame from pygame.font import Font from symbol import get_char_surfaces from config import Config pygame.init() # Load Matrix font font = pygame.font.Font(Config.FONT_PATH, Config.FONT_SIZE) # Generate white character surfaces white_chars = get_char_surfaces( font=font, char_set=['a', 'b', 'c', '0', '1', '2'], char_color=pygame.Color('white') ) # Returns: List of pygame.Surface objects # Generate green character surfaces with error handling green_chars = get_char_surfaces( font=font, char_set=Config.CHARACTER_SET, # a-z char_color=(40, 220, 40) ) # Characters with missing glyphs are automatically skipped print(f"Generated {len(green_chars)} character surfaces") # Use surfaces in rendering screen = pygame.display.set_mode((400, 300)) x_pos = 10 for surface in white_chars[:5]: screen.blit(surface, (x_pos, 10)) x_pos += Config.FONT_SIZE pygame.display.update() ``` -------------------------------- ### Application Configuration with Config Class (Python) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt The Config class centralizes all application settings, including display modes, image processing options, and screen parameters. These settings control the visual output and behavior of the Matrix Rain effect. ```python from config import Config # Display modes (mutually exclusive) Config.RAIN_ACCUMULATION_MODE = True # Characters fall and lock into position Config.JUST_DISPLAY_MODE = False # Display all characters instantly # Image processing modes (mutually exclusive) Config.SINGLE_COLOR_SELECTION = True # Detect specific color Config.DRAW_LINES_OF_IMAGE = False # Detect edges/outlines Config.LINE_THICKNESS = 3 # For edge detection mode # Screen settings Config.SCREEN_WIDTH = 1260 Config.SCREEN_HEIGHT = 800 Config.FPS_LIMIT = 60 ``` -------------------------------- ### Image Processing and Position Calculation with Python Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt The Image class handles loading, scaling, and analyzing images to determine character placement. It uses OpenCV for processing and calculates positions based on specified parameters like font size and color. ```python from config import Config from image import Image # Load and process an image img = Image("images/profile.jpg") # Scale the image to 80% of original size img.scale_image(0.8) # Calculate positions where characters should appear # font_size: size of character grid cells # isolate_color: RGB color to detect (255, 255, 255 for white) img.calculate_all_threshold_positions( font_size=10, color=(255, 255, 255) ) # Get dimensions of processed image width, height = img.get_dimensions() print(f"Image dimensions: {width}x{height}") # Center the image on screen screen_center_x, screen_center_y = 630, 400 img_center_x, img_center_y = img.get_centre() offset_x = round((screen_center_x - img_center_x) / 10) offset_y = round((screen_center_y - img_center_y) / 10) img.translate_points_by_vector((offset_x * 10, offset_y * 10)) # Access column positions for x_pos, y_positions in img.column_positions.items(): print(f"Column {x_pos}: {len(y_positions)} positions") ``` -------------------------------- ### Draw White Squares on Black Background (Pygame) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt This snippet demonstrates drawing white squares on a black background using Pygame. It iterates through calculated column positions and draws rectangles to create a visible grid. It then enters a Pygame event loop to keep the window open until closed. ```python import pygame # Assume Config and img are defined elsewhere # win = pygame.display.set_mode((width, height)) # Check if positions were found if not img.columns_left_to_place(): print("Couldn't calculate any positions to draw") else: # Draw white squares at calculated positions white_square_size = (Config.FONT_SIZE, Config.FONT_SIZE) black_square_size = (Config.FONT_SIZE - 1, Config.FONT_SIZE - 1) for x, y_positions in img.column_positions.items(): for y in y_positions: # Create visible grid with black background and white squares win.fill((0, 0, 0), pygame.Rect((x, y), white_square_size)) win.fill((255, 255, 255), pygame.Rect((x, y), black_square_size)) pygame.display.update() # Wait for window close clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False clock.tick(Config.FADE_RATE) pygame.quit() ``` -------------------------------- ### Configure Edge Detection Mode (Python with OpenCV) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt This snippet configures the application for edge detection mode using OpenCV. It modifies configuration settings to enable line drawing, disable single color selection, and sets line thickness. The image is loaded, processed for edges (grayscale, Canny, contours), and positions are calculated only for edge pixels. ```python from config import Config from image import Image import cv2 # Configure for edge detection mode Config.DRAW_LINES_OF_IMAGE = True Config.SINGLE_COLOR_SELECTION = False Config.LINE_THICKNESS = 3 Config.debug = True # Load image (edge detection happens automatically) img = Image("images/portrait.jpg") # Internally applies: # 1. Convert to grayscale # 2. Canny edge detection with thresholds (10, 200) # 3. Find contours # 4. Draw contours with specified thickness # 5. Convert back to RGB img.scale_image(0.7) # Calculate positions on detected edges img.calculate_all_threshold_positions(Config.FONT_SIZE, (255, 255, 255)) # Debug window shows processed edge image # cv2.imshow("Image converted", img.img_object) # cv2.waitKey(0) # Positions are now calculated for edge pixels only print(f"Columns with edge data: {len(img.column_positions)}") ``` -------------------------------- ### SymbolColumn Class for Cascading Characters (Pygame) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt The SymbolColumn class manages a vertical array of symbols, controlling their cascade down the screen. It handles symbol updates, alpha gradients, static placed symbols, and continuous column movement. ```python import pygame from symbol import SymbolColumn from config import Config pygame.init() # Placeable positions where white symbols should lock in place placeable_positions = [500, 450, 400, 350, 300] # Create a column starting at x=100, y=0 with specified lockable positions column = SymbolColumn( pos_x=100, start_y=0, placeable_positions_list=placeable_positions ) # Get the leading white symbol white_symbol = column.get_white_symbol() print(f"White symbol at Y: {white_symbol.get_y_position()}") # Lock white symbol in place when it reaches target position if white_symbol.get_y_position() == 500: column.place_white_symbol() # Draw entire column to surface screen = pygame.display.set_mode((800, 600)) background = pygame.Surface((800, 600)) column.draw(background) # Column automatically manages: # - Symbol updates and character changes # - Alpha gradients (bright at top, dim at bottom) # - Placed symbols that remain static # - Continuous column movement ``` -------------------------------- ### Symbol Class for Individual Matrix Characters (Pygame) Source: https://context7.com/izucked/matrix-rain-an-image/llms.txt The Symbol class models a single falling character in the Matrix effect. It manages position, speed, color, and appearance, with methods for updating its state and drawing it to the screen. ```python import pygame from symbol import Symbol pygame.init() # Create a white symbol at position (100, 50) moving at speed 5 symbol = Symbol(x=100, y=50, speed=5, color=pygame.Color('white')) # Create a green symbol with random variations green_symbol = Symbol(x=200, y=100, speed=3, color=(40, 200, 40)) # Update symbol state and change character randomly symbol.update() # Draw symbol to a surface screen = pygame.display.set_mode((800, 600)) background = pygame.Surface((800, 600)) symbol.draw(background) # Get current Y position current_y = symbol.get_y_position() print(f"Symbol Y position: {current_y}") # Stop symbol from moving (when it reaches target position) symbol.stop_moving() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.