This repository contains the code for a video tutorial on creating a Falling Sand Simulation using Python and Pygame.
🎥 Watch the Video Tutorial on YouTube
| 📺 My YouTube Channel
| 🌍 My Website |
In this tutorial, we build an interactive Falling Sand Simulation from scratch. The tutorial walks you through each step, from setting up the grid to implementing various particle behaviors like falling sand and immovable rocks. Along the way, you'll learn Python programming, Pygame basics, and simulation design techniques.
- Realistic Particle Physics: Sand particles fall naturally and interact with rocks to form realistic patterns.
- Multiple Particle Types: Add sand, rocks, or erase particles using different modes.
- Interactive Tools: Use your mouse and keyboard to dynamically add, remove, and modify particles.
- Customizable Brush Size: Create larger patterns with the adjustable brush tool.
- Dynamic Cursor Feedback: A custom cursor indicates the selected tool and mode.
- Optimized Performance: Grid-based updates ensure smooth simulation even with many particles.
- main.py: The entry point of the project. It sets up the Pygame window, handles user input, and manages the simulation.
- grid.py: Contains the
Grid
class, which manages the particle grid and its updates. - particle.py: Defines the
SandParticle
andRockParticle
classes, along with their behaviors and properties. - simulation.py: Contains the
Simulation
class, which integrates all components and handles interactions.
-
Clone this repository:
git clone https://github.com./educ8s/Python-Falling-Sand-with-pygame.git cd Python-Falling-Sand-with-pygame
-
Ensure you have Python and Pygame installed. Install Pygame using pip:
pip install pygame
-
Run the
main.py
script:python main.py
This project is divided into 10 steps:
- Install Pygame: Set up your environment and install the Pygame library.
- Create the Window & Simulation Loop: Set up the Pygame window and define the simulation loop.
- Build the Grid: Create a two-dimensional grid to manage particles.
- Add Sand Particles: Implement the SandParticle class and their visual representation.
- Add Simulation Logic: Define how particles fall and interact with their surroundings.
- Optimize Performance: Refactor the simulation loop for better efficiency.
- Add Keyboard Controls: Use keys to switch between Sand, Rock, and Eraser modes.
- Add Rock Particles: Introduce immovable rocks that interact with sand.
- Add Eraser Tool: Implement a tool to remove particles dynamically.
- Add a Cursor Indicator: Show a dynamic cursor that represents the selected tool.
- Mouse Left Click: Add particles or erase them based on the current mode.
- Keyboard Keys:
- S: Switch to Sand mode.
- R: Switch to Rock mode.
- E: Switch to Eraser mode.
- Spacebar: Clear the entire grid.
- Python 3.x
- Pygame (Community Edition recommended for better performance)