Archive for September, 2009

The Chaos Game

After getting the book “INTRODUCING Fractal Geometry“, I thought it’d make a good learning project to tackle “The Chaos Game“, as coined by the mathematician Michael Barnsley. Seemed simple enough to grasp, and would be fun to code up in Python\PyGame.

What attracted me to it was that while it was a seemingly simple problem, a few things outside my realm of knowledge were needed: Find a random point inside of a triangle. After a bit of web searching, I ran across the post on Wolfram Mathworld describing ‘Triangle Point Picking‘. It shows how to find points based on a quadrilateral (2x triangle). Using that code, and a Python specific post called “Deciding if a Point is Inside a Polygon“, I was able to combine them with the game rules to achieve success, the Sierpinski triangle!

While the end result is nothing special to look at, Sierpinski triangles have been around for a long time, it was the fun of actually making the whole thing work through Python that kept me at it on Sunday afternoon 😉

  • Python source code HERE.
    • Its expecting to use this Vec2D class.
  • .zip with Windows executable HERE.

Now has its own page on the blog.

The Matrix

Since I never ‘went to school’ for any kind of programming, I’ve had to pick it up as needed throughout my career.  One of the ‘great mysteries’ has been matrix math.  I’m a visual person, and that includes learning math.  Last night, while reading chapter 9 in my PyGame book ‘Beginning Game Development with Python and PyGame: From Novice to Professional‘, the whole ‘matrix thing’ finally made sense in my brain.  So much in fact, I couldn’t fall asleep I was mulling it over so much.  Waking up, I decided to dive into it, and made some psuedo-code showing how matrix multiplication happens.  But it was still really hard to physically visualize what was going on.  So, working in GIMP, I made a graphical layout of what is going on.  It is a work of beauty :)

Couple things are presumed:  It is a description of multiplying two 4×4 matrices, with their translation along the bottom row, not the right column.  In each of the sixteen blocks, the sub-matrices (‘matrixA’ on the left, ‘matrixB’ on the right) are multiplied left to right, and added top to bottom to get the final result of each block.  Time for a t-shirt!

visualMatrixMult02Click through (twice) for a larger version.
You can find it on flickr here as well.

Bubblepaint 0.1.3

bubblePaint.0016Based on my previous post, I’ve got a usable version of Bubblepaint ready for the masses.

In a nutshell, it’s a simple ‘paint program’ using 2d physics.  You ‘paint’ with ‘bubbles’ that collide with each other.  Good fun.  It’s implemented via Python through PyGame (graphics) using PyMunk (physics).  It’s documentation is on a toggleable layer on the main screen once it starts.

You can find a zipped Windows executable here:

You can find the updated Python source here:

Put a few pics on up Flickr here.

I’d love to hear some feedback.  I don’t have many plans to develop it much further, but you never know 😉

How can I increment numbers on saved files in Python?

Originally posted on my Python Wiki.

This is a function I had made for my BubblePaint program in PyGame. In a nutshell, it will save the screen to a png image, and increment the filename with each image in the dir.  User can keep saving images, and this will keep incrementing the number of the newly saved file.

import glob, os, re

def saveImage():
    """
    Save the current image to the working directory of the program.
    """
    currentImages = glob.glob("*.png")
    numList = [0]
    for img in currentImages:
        i = os.path.splitext(img)[0]
        try:
            num = re.findall('[0-9]+$', i)[0]
            numList.append(int(num))
        except IndexError:
            pass
    numList = sorted(numList)
    newNum = numList[-1]+1
    saveName = 'bubblePaint.%04d.png' % newNum
    print "Saving %s" % saveName
    pygame.image.save(screen, saveName)

Will save out files like this:

bubblePaint.0001.png
bubblePaint.0002.png
etc...

How can I modify a Python attribute any time it is accessed?

Originally posted on my Python Wiki

I was designing a UI for a PyGame program I am working on, and needed a way to pass a value defining a “row height” into the functions that rendered my text to the screen. Since the UI could change, I didn’t want to have to hard-code positions into each element, later to modify it and have to redo all the positions.
What I came up with was a simple class with a single usable attribute, called val. Through using properties, I’m able to control how the attr behavies at time time its value is queried:

class Row(object):
    # class to store the current row location in the UI
    # Each time it is called, it will increment its value
    def __init__(self, val):
        self._val = 0
        self.orig = val
    @property
    def val(self):
        self._val = self._val + self.orig
        return self._val
row = Row(16)

print row.val, row.val, row.val, row.val
# 16 32 48 64

Properties have getter, setter, and deleter methods, but the default is getter, which I used above. So as you can see, each time I call to print, it accesses the val property (via the getter), and updates the internal counter.
This is a PyGame code snippet showing it in use:

overlay.blit(bubble, (8, row.val))
overlay.blit(toggleText, (8, row.val))
overlay.blit(lmb, (8, row.val))

Rather than having to specify a Y value for the last arg of the tuple, I can simply pass in my object, and it passes out the current new position, based on how many times it was called before.

I have no doubt there is probably some slicker way in Python, but it’s what I came up with on the spot :)