Physics in PyGame and Python
I’m on week two of my seven week sabbatical (yay), and part of what I’ve been up to is learning more about PyGame (see previous posts). I have nothing major to show yet: I started a ‘PyGame’ wiki (not yet online) and have a “tank” game where you can drive them around, bump into each other and obstacles, and I just got the ability to add independently transforming “turrets” to them (my son has had fun making the sprite graphics for them in Gimp). My goal is to have them all powered via pseudo-accurate 2d (top down) physics. I started developing this based on web-examples… but I quickly figured out a couple things:
- I don’t know anything about physics, really.
- Online examples only take you so far.
To help remedy this, and since I’m a sucker for paper in my hand, and have purchased these informative volumes:
- The Cartoon Guide To Physics : I really enjoy this “cartoon” series of books. I also have the one on chemistry…
- Physics For Dummies : I have a lot of the “Dummies” and “Idiots” books, always a good starting point.
- Physics For Game Programmers : (currently en-route to my home via Amazon…) Looks like good practical programming reference.
Before I start in earnest though, it’s always good to see what other people have done, and I tracked down these two 2d physics engines for Python\PyGame:
- PyMunk: A Python wrapper around the Chipmunk engine.
- PyBox2D: A Python wrapper around the Box2D engine.
Since I like the name “munk” more than “box”, I’ve recently installed PyMunk, and the examples were up and running in no time. I look forward to strapping this into my PyGame projects.
Concurrent with that, I’ve just started reading the first two of my physics books, and to help me learn the actual nature of physics, I’ve been authoring some Python classes along with them. Below are a few examples of what I’ve been up to. And for me, it’s been both a good learning experience with simple physics, and for making Python classes themselves. Especially the operator overloading stuff.
In the below example, I make several objects to represent different “units” of measurement:
- Distance
- Mass (omitted from below example)
- Weight (omitted from below example)
- Time
- more to come… (volume, etc…)
All of these objects have a superclass called ‘MeasureBase’, which defines their behaviors (mainly the operator overloading stuff). Each class stores its data, no matter what type it is, in an attribute called ‘units’. This allows me to multiply distance by time, for example. Each class stores its units as a certain kind of units: Distance stores everything as meters, no matter if you pass in inches, centimeters, miles, or kilometers. Time stores everything as seconds, even if you pass in hours or days.
Finally, I have a class that actually does something interesting (hopefully the first of many) with all these units, called ‘DistanceFallen’: You pass in how long something has fallen, and it will return back how far it has fallen. See code below (WordPress seems to be messing up the indentation… )
I’ll conclude with: This is just a start, for fun, on a Saturday afternoon. But I think it’ll be a good learning tool moving forward, both for programming PyGame, and for physics concepts in general.
# units.py import math # gravitational constant: 9.8m/sec2 GRAVITY = 9.8 class MeasureBase(object): # Superclass inherited by measurement types. Defines some default behavior. # self.units & .unitType is defined by subclasses inchToMeter = 39.3700787 footToMeter = 3.2808399 yardToMeter = 0.9144 mileToMeter = 609.344 ounceToKilogram = 0.0283495231 poundToKilogram = 0.45359237 def __str__(self): return "%s %s" %(self.units, self.unitType) def __repr__(self): return str(self.units) def __float__(self): return self.units def __int__(self): return int(self.units) def __add__(self, dist): return self.__class__(self.units + float(dist)) def __sub__(self, dist): return self.__class__(self.units - float(dist)) def __mul__(self, dist): return self.__class__(self.units * float(dist)) def __div__(self, dist): return self.__class__(self.units / float(dist)) def __pow__(self, val): return math.pow(self.units, float(val)) def __abs__(self): return self.__class__(abs(self.units)) class Distance(MeasureBase): # Internal measurements are stored as meters def __init__(self, units=0.0): MeasureBase.__init__(self) self.unitType = "meters" self.units = float(units) def apply_mm(self, mm): self.units += mm/1000.0 def apply_cm(self, cm): self.units += cm/100.0 def apply_dm(self, dm): self.units += dm/10.0 def apply_m(self, m): self.units += m def apply_km(self, km): self.units += km*1000.0 def apply_inch(self, inch): self.units += inch / MeasureBase.inchToMeter def apply_foot(self, foot): self.units += foot / MeasureBase.footToMeter def apply_yard(self, yard): self.units ++ yard / MeasureBase.yardToMeter def apply_mile(self, mile): self.units += mile / MeasureBase.mileToMeter class Time(MeasureBase): # Internal measurements are stored as seconds def __init__(self, units=1.0): MeasureBase.__init__(self) self.unitType = "seconds" self.units = float(units) def apply_miliseconds(self, ms): self.units += ms*.001 def apply_seconds(self, s): self.units += s def apply_minutes(self, m): self.units += m*60 def apply_hours(self, h): self.units += h*3600 def apply_days(self, d): self.units += d*86400 def apply_years(self, y): self.units += y*31104000 class DistanceFallen(object): def __init__(self, time, grav=GRAVITY): # time is either in seconds, or a Time object self.time = Time(time) self.grav = Distance(grav) self.calcDistance() def __str__(self): return "Fallen %s in %s" %(self.distance, self.time) def set_time(self, time): # time is either in seconds, or a Time object self.time = Time(time) def set_gravity(self, grav): self.grav= Distance(grav) def calcDistance(self): self.distance = (self.grav * math.pow(float(self.time), 2)) * .5 def getDistance(self): self.calcDistance() return self.distance
Based on that, here’s a simple example of it in action:
time = Time(4) print time fallen = DistanceFallen(time) print fallen
The result printed is:
4.0 seconds Fallen 78.4 meters in 4.0 seconds
self,