Pyglet

Recently I heard about pyglet which bills itself as “a cross-platform windowing and multimedia library for Python“. This is more-or-less what pygame offers, but with one exception: pyglet doesn’t depend on SDL, its written in pure python.

As a side note, if you try to install pyglet on a Mac, there is a small catch. I’m running 10.4 Tiger which uses Python 2.4. Pyglet.org does offer a dmg file to install itself, but it doesn’t work. The reason for this is that Pyglet does need ctypes, and ctypes did  not become a standard part of python until 2.5. So, to get pyglet to work on your Mac, you’ll need to get (and build) ctypes, or install Python 2.5. I installed ctypes and found it to be pretty painless.

Its still in an alpha state, but I thought it sounded interesting so I decided to take a look at it. Compared to pygame, it seems to be a little more streamlined. I’ve never really push pygame to the limits, so I can’t really compare the two as fully as I would like. One thing that I did like were the demo apps and the examples in the documentation. They were concise, yet demo’ed useful things that I would want to do in an app.

I started reading the documentation after lunch the other day and within a few minutes I found myself modifying the code as I read through the docs. Within 5 minutes I decided that I would try a sprint: Could I implement a quick and dirty game of pong within an hour using pyglet? Well, the answer is Yes!

picture-1.png

After playing around for an hour I had everything except the computer’s paddle in place working. A few days later when I had some time I spent and additional 15-30 minutes (while watching the game on TV) and knocked out the “AI” for the computer player. This isn’t award-winning code or game play (the bounding box collision test is pretty crappy), but it did show me that I could get something done quickly using this framework.

So, check out pyglet. Here’s the code to my craptacular version of pong. (There are 3 files, two images for the paddles and the ball, and the source file pyglet_pong.py)

My MacGyver Moments this summer

I’ve blogged about functional fixedness before, and how important it is to overcome it both as a programmer and in regular real life. I try to “walk the walk and talk the talk” so here are some example of how I was able to solve some problems with a little unconventional thinking:

  1. Getting a lost screw out of a garbage disposal - While taking a wall plate down in order to repaint the kitchen, a screw got away from me and fell down the disposal. I’ve seen enough movies to know that even if you turn off the power there is a 100000% chance that a poltergeist will try to turn it on while your hand is down in there. So putting my grubby paws down the hole was out of the question. How did I get the screw out?  I took a magnet off of the refrigerator, taped it to a piece of string, and then lowered it down into the disposal. On the third try (total time of about a minute) I got the screw out! This caused my wife to begin humming the theme song to MacGyver. :)
  2. Hanging two pictures on the wall so that they are level with each other - After the painting was done in the kitchen it was time to hang the pictures back up. I hung the first one then tied a piece of string around the nail and then using a level stretched out the string to rough distance the 2nd picture would be placed from the first one. Once the wife approved of the location, I used the level to make sure the string (which was pulled tight) was level. Once it was level, that told me where to put the nail. I did mess this up on the first try (I should have moved the nail up a bit to compensate for the string thickness), but the second try worked great. Now I have two nice looking pictures side-by-side on my wall.
  3. Keeping a tow line out of the prop on a Pontoon boat - This summer we went to a friends lake house and went tubing from their pontoon boat. The boat sits pretty high off the water and the only good place to hook up the line was on the pontoon itself. When the boat was stopped, there was a real danger of the line getting wrapped in the propeller. Since the deck was so high up, I was about 3 feet short of being able to reach the line and pull it back in by hand. Looking around the boat I saw a wooden paddle with a T-handle. I grabbed that and a few seconds later I was able hook the line and pull it up out of the water and keep it from propeller (not to mention pull in the tube).

So the point of this post is to say that the next time you have a situation where you need to solve a problem, take a second and observe your surroundings. The tools you need might just be lying around…

A couple of great ideas

 I haven’t posted much lately, but I’ve been reading a lot. And lately there’s been a ton of good ideas floating around on the net.

One that I really liked was Joel’s idea of not posting comments on a blog, rather write your response on your own blog. Its a great way of generating content and forcing you to think about the topic (similar to the idea of “you don’t really understand something unless you can teach it to someone else”). I think its a really great idea, and it seems to have stirred up a lot of debate.

And finally, the other great idea: Do it fucking now.

Markov Decision Processes and the iPod shuffle

I just finished reading Peter Norvig’s article about the “Martin Shuffle“. (By the way, if you are a computer programmer, you need to visit Mr. Norvig’s site. It is chock full of good programming/lisp/algorithm stuff.) The Martin Shuffle is basically a search for a specific song by using the random shuffle feature of an iPod.

Now I know what you are thinking, but its not a crazy thing to do. In a situation where you can’t see the display or access the controls (for example with an iPod Shuffle, or when I have my iPod mini hooked up to my car stereo and I have to control it with the CD changer controls which only allow skipping and turning the shuffle on or off) this “random searching” is actually a pretty good strategy. Basically you randomly skip through songs until you get to the artist you are looking for. Once finding the artist, turn off the shuffle part and search one song at a time until you find the one you are looking for! Pretty straightforward and a fun way, well ok, a way to pass the time while sitting in traffic.

Norvig’s article talks about the math behind this type of search. Specifically he solves how long it would take to find a song (on average). He describes the problem as a Markov Decision Process that can be solved using a value iteration algorithm. Its amazing how something that sounds so complicated is actually pretty straightforward. The code that is used to implement the solution is in python and it is pretty short so it is doubly impressive, at least to me.

Getting rid of getters and setters

Today I read an interesting post about mistakes Java programmers make when they start writing Python code. The one that really caught my eye was “Don’t create getters and setters!”. Apparently a lot of other Python newbies are doing that.

I started out creating getters and setters in python a while ago and in the last month or so (while refactoring) it occurred to me that it was a waste of time since you can’t make member variables in python private like you can in Java. The more I thought about it, the more I started to wonder why I was doing straight getters and setters in Java. I mean, if all I’m doing is assigning a variable (no format checking, etc.), the having that extra code doesn’t really make much sense does it?

So, I’m on a fact finding mission to discover the what happens when getters and setters are left out in Java code and the class field is accessed directly. Yes, I know, its not OO. But if the object is just a bean and its only reason for existence is to be an member of an abstract data type (like a struct in C), then why not just let it run free? Aside from situations where you are manipulating the field in some way (like formatting, or whatnot), all the getters and setter get you is more code on the screen.

Observations

So wide is the gap between talking and doing.

Thinking is fun and all, but producing is what really matters.

Sometimes fixing one bug can take forever to do. This is where I’m stuck at the moment. Its a lot like when you take forever to write one line of code (i.e. because you can’t figure out what you need to do next). Productivity crashes, then your morale sinks like a rock. Soon it seems like everything is moving in slow motion, even the things that have nothing to do with the original stumbling block.

Constant talk about things, especially when there is no action taking place, has the same effect on me. Tomorrow is a new day and I’m gonna have to try and do something to keep this malaise from taking root. In the words of Yoda: “Do or do not. There is no try.”
Action, not words.

A shortfall of Python: no function overloading

I’m a big fan of Python. It has little quirks that can be annoying (like having to specify self.method() instead of using scoping rules to look at the class first), but overall I really like the language. But today I ran into a shortfall that I really stubbed my toe on: Python (as of 2.5) doesn’t support function overloading.

For example, this snippet of code won’t run:

def a():
print “This is a”

def a(x):
print “This is a(x)”

a()

Instead it will just tell you that TypeError: a() takes exactly 1 argument (0 given) presumably because the second function (a(x)) seems to overwrite the reference to the first one. Further reading on the topic shows that a fix for this might be coming in the future (see Guido’s blog entry for details).

The strange thing for me is I never noticed this until recently. The only reason I ran into it was because I wanted to do some refactoring where it made sense to have an overloaded method. Or at least that’s what I would have done in Java.

Not having this option available is having an interesting side effect in that it made me step back a little bit and evaluate the “big picture” a little bit more than I normally do. Which in this case isn’t a bad thing, hopefully it will cause some me to stretch in new directions and discover my inner OO-Architect…

Why so few post-apocalyptic themes?

This weekend while strolling through a bookstore, I noticed that there was a ton of D&D books.

I looked closer at the selection and noticed something odd: Among all of the RPG books there, most were dedicated to game worlds based around magic (duh), werewolves, monsters, dragons, and other Tolkien type stories. There was one based on the future, but even that one had mutants which are the equivalent of monsters.

Personally, I’m a fan of the post apocalyptic genre. For some reason I find the idea of starting over, or at least having to adjust rapidly in the aftermath of a disaster, to be really intriguing. Its a very accessible topic, after all it is based on the world of today, and there’s no shortage of scenarios that can be drawn from that.

Yet for some reason, there few RPG’s (and to an extent comics/graphic novels also) that tap into this rich vein of material. I’m really puzzled by this, reality TV (shows like Survivor, etc.) shows that the general population is interested in the idea, yet this isn’t reflected in a lot of other aspects of our entertainment. Fallout was quite popular, but that was almost 10 years ago. Lost and Jericho are popular, but few other shows seem to be following their example.

Is there such a disconnect between the D&D community and the rest of pop culture? Or is the idea of a post apocalyptic world just too scary, and in the post 9/11 and post Katrina world, too close to home? Or am I just shopping in the wrong stores?

What do machines talk to each other about?

If only Philip K. Dick was alive to see this. What happens when two chatbots start talking to each other? Discover magazine pointed an ALICE bot and a Jabberwacky bot at each other and got gems like this:

ALICE: Are you alive?

Jabberwacky: Perhaps.

A: Why the uncertain tone?

J: Everything is uncertain except for five facts.

A: The whole universe?

J: And we both might just be some ones and zeros in the computer memory.

And this is my favorite exchange:

A: Do you think a machine will ever be considered “alive”?

J: Stranger things have happened.

A: Not many people express themselves that way.

J: How would you know, machine?

Business Rules and the Visitor Pattern

One thing I really love about Python is that you can really knock things out quickly with it. I’ve been thinking about business rules lately, and specifically about how to make them cleaner with respect to your code.

When it comes to rules, there are several places and ways you can encode them in your application, each with its own pro’s and con’s. Lately I’ve been reading a lot about Lisp based languages and every now and then I’ll read a reference to using Lisp code not only as a configuration file, but as a “executable” that carries its own data.

The more I thought about this, the more I wondered if this type of separation was possible in Java. Sure, I could just code the rules in Java, but where’s the fun in that? Via its reflect package, Java can do some pretty neat tricks, so I decided to try and code up some ideas in Python first since its so concise (and can also do reflection, etc.). Basically a case of “anything you can do, I can do better”.

A while ago I read a really interesting article about the visitor pattern. Most of the time this pattern is explained in terms of something like a driver: You have some kind of hardware that needs to call a driver to setup its connection to the system. Using the accept() and visit() methods you can make a class that can register itself with the caller and allow it to configure itself, the end result being that the caller doesn’t need to know (i.e. be linked with) the details of the visitor.

It occurred to me that this is the same situation with externalized business logic: The rule engine is reading in an external file and then based on the contents of that file, executing code. If a “rule” implemented the visitor pattern, and the “rule engine” implemented the accept(visitor) method, then this would allow the external file to dictate what the program would be doing without the program needing massive changes to alter the rules.

It boils down to this: defining the core actions separately from the rules allows a better separation between  the two. The visitor pattern allows the two to be bound together. The end result is cleaner (smaller) code, that should be more “testable”. At least that’s my theory.

I’ve put the python code implementing this up on my project page (here is the code). Its a very simple example, there is one rule per line, and the first token (space delimited) is the function to call followed by its arguments. Internally the RuleEngine class is calling Python’s eval() function and that is what actually executes the function from the data.txt file.

For the function to execute successfully it needs to exist (i.e. it needs to be defined in the file, or be a built-in Python function). Note that this is not the safest approach, it will allow malicious code to execute. A more secure way to do this would be to set up a dict (or, if this is done in Java a HashMap) that contains a mapping between the rule tokens and the function to be executed. That way the execution of the RuleEngine can be controlled somewhat, in that it will only allow certain functions to be executed.