Pygame physics simulation


Feb. 1, 2010 Code on Github

Contents

This series of tutorials demonstrates how to create a physical simulation using Python and Pygame. The tutorials start with the very basics and build up to a final simulation of a classical physics problem: the trajectory of a cannonball.

If you're not interested in the mechanics of the program, you can skip ahead to tutorial 10 and download the PyParticles module and particle_tutorial_10.py, which demonstrates how to use it from the Github link at the top of the page.

Example

This is an example of the program we'll be making, but the code can be easily adapted for a number of simulations, such as a cloud of gas collapsing under its own gravity to form a solar system (tutorial 12), or soft body physics with springs (tutorial 14).

Requirements

For this tutorial, you'll need:

  • Python2.7, which can be downloaded here. Getting this to work with Python3 shouldn't be too hard, but I haven't tried.
  • A basic knowledge of Python, if you are complete beginner you should probably read through some other tutorials first. At the very least, you’ll need to know how to run a Python script.
  • Pygame, which can find here. It's easiest to install with Pip.

It would also be advantageous if you had a grounding in basic mathematics, specifically trigonometry. The tutorial includes some simple mathematical tricks that can be surprisingly powerful. These tricks took me a while to work out and I'll do my best to explain how how they work. If you want, you can blindly copy the code, but if you later want to change the behaviour of the simulation, it would be a good idea to understand how the mathematics works.

If you're interested in learning more about the mathematics or the physics then I can recommend the Khan Academy, which has an amazing collection of educational videos [full disclosure - since writing this, I have started working for Khan Academy].

You won’t however, require any prior knowledge of Pygame; this tutorial will start from the very basics, demonstrating how to use Pygame to create a graphical display, update it, and make it to respond to user inputs.