Monday, September 24, 2007

Link: Web 2.0 ... The Machine is Us/ing Us

Kelly Yancey linked to this video: Web 2.0 ... The Machine is Us/ing Us. Just in case you missed it like I did, I'm linking to it too ;)

Friday, September 21, 2007

Browsers

So it seems like Firefox is having problems and everyone has been complaining about it a lot. I sure hope they fix it quickly. It's crashing on me constantly when I indulge in my YouTube addiction, and it uses up an ever-increasing amount of memory. A lot of my friends are enjoying Opera, but I just can't bring myself to install a proprietary browser.

I decided to give KDE and Konqueror another shot. I'm actually pretty pleased with it. Although Konqueror doesn't support two of my favorite Web sites, GMail and YouTube, it is very stable and very snappy. Even better, it uses half as much memory. It has a menu option to open the current page in Firefox, which is helpful for the times it doesn't work. This matches what a lot of Mac users do: they use a mix of Firefox and Safari.

On the other hand, something strange happened when I was installing KDE. I accidentally uninstalled the Ubuntu flashplugin-nonfree package. Today, when I went to YouTube, Firefox asked me to install the Flash plugin locally (i.e. not system-wide). Since all I had to do was hit OK, I did. Voila, Firefox stopped crashing all the time. Weird.

Wednesday, September 12, 2007

Computer Science: Prototypal Match Templates

In object-oriented programming languages, you can subclass an existing class and override a few of its methods. This allows you to take an existing piece of code and tweak it for your own use. However, it's only as granular as the methods that you are overriding. If you want to change one line in a 30 line method, you either have to refactor that 30 line method into several methods (which is the right thing to do if you're in control of the code) or you have to copy the 30 lines and modify that one line (which may be the only thing you can do if you're not in control of the code). Sometimes I actually do both. If I'm using a third-party library that has a 30 line function that I want to change one line of, I copy the whole function into my class, and then refactor it there as if I were refactoring the superclass.

Genshi has a cool mechanism called match templates. I assume XSLT has this too, but since I don't know XSLT, I can't say for certain. Genshi's mechanism let's you write an HTML template and say things like "Every time you see HTML that matches this XPath expression, replace it with this HTML". It turns out that this is a really flexible way of doing templating. It makes it really easy to setup a global look-and-feel and then customize it however you want on a per-template basis. You just write match templates that "tweak" the global look-and-feel. Unlike the template design pattern, the person writing the global look-and-feel doesn't need to do anything to set you up. He doesn't need to create "hook" divs for you to override or anything like that. You can tweak anything you like.

I wonder if the same thing might be useful as a replacement for object-oriented inheritance. Instead of subclassing a class and then overriding some of its methods, you subclass a class and then write match templates that "tweak" the code in the superclass. I think "prototypal match templates" are a good name for this, because you're taking a prototype piece of code and then tweaking it to your needs as if you were doing text substitutions. You would need something like XPath that would make sense for the programming language you're using, but that's not too hard to imagine.

Ok, let me show you what I have in mind. Let's start with how I would do things today:
class Greeter:

"""Let's pretend this is in a third-party module."""

def greet(self, sex):
print 'Howdy,',
if sex == 'female':
print 'good looking!'
else:
print 'stranger.'
Here's my subclass:
class PoliticallyCorrectGreeter(Greeter):

def greet(self, sex):
"""I either have to refactor or I have to duplicate code here."""
print 'Howdy,',
if sex == 'female':
print 'person of the opposite sex.'
else:
print 'stranger.'
If I had prototypal match templates (including some sort of XPath-like syntax for Python syntax), I could write something like:
class PoliticallyCorrectGreeter(Greeter):

match def[name='greet']/if/print[args[0]]:
'person of the opposite sex.'
Ok, I can imagine that many people are going to hate this idea. That's why I'm turning off comments...just joking ;)

One valid complaint is that this breaks encapsulation. I'm overriding a method in a way that requires knowledge of the implementation. That's a fair point. However, I'd like to punt on this issue. When I'm subclassing something, I often need to understand the implementation of the superclass anyway to do what I need to do. I think that if you subclass a class, you're "closer" to that class than if you were just using it. If the superclass's implementation changes, it'll break my code. That's okay. I can look at how it's changed and fix it. That's just a normal part of my life as a modern programmer. Furthermore, I think there are smart ways to use this feature and not-so-smart ways to use this feature. It's a hammer--don't hit yourself over the head with it ;)

Next, I'm sure there's a Lisp programmer out there somewhere saying, "Yeah, been there done that. Haven't you heard of macros?" That's a good point too. Lisp is nice because the syntax tree is just Lisp data. That's one of the nicest things about Lisp syntax. However, an XPath-like syntax for navigating an AST for, say, Python would let Python programmers use some of the same tricks that Lisp programmers use. McCarthy said, "Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified bug-ridden slow implementation of half of Common Lisp," but I sure do like the way that Python makes Lisp-based ideas more readable and accessible to the masses. Back when Lisp was created, doing things like what I'm talking about just didn't make sense. Making the AST normal Lisp data was a brilliant move. These days with strong reflection in scripting languages, it does make sense to play with the AST in your code. You can have your syntax and tweak it too :-D

Tuesday, September 11, 2007

Python: PyWeek


I just finished PyWeek! (Here's the code.) It's a contest where you have one week to write a video game using PyGame. We also used PGU, which is a pretty helpful library for writing video games. This time, my buddy Adam Ulvi participated with me. We took two days off from work and wrote about 800 lines of code. I'm proud to say we created what I think is a pretty impressive and fun game.

I leaned pretty heavily on object-oriented programming this time. I know a lot of people like to talk smack about OOP, but I often find it helpful. The player, the enemies, and even the artillery all subclass a class called SuperSprite that takes care of things like integrating per-frame movement, per-frame animation, collisions, etc. OOP lets me say "these guys should all act exactly the same except in these slightly different ways." Often times, the subclass is no more than a few class-level constants, like a different image. Sometimes they behave slightly differently, which is achieved by overriding a single method.

Since I'm also a fan of functional programming, I also relied heavily on closures for doing animation. Each subclass of SuperSprite has an animator_func function. It's a pointer to whatever function I happen to be using for animation at the time. Hence, when you destroy an enemy, I set that enemy's animator_func to a closure that animates the enemy's explosion:
    def create_destroyed_animator(self):

"""This is the animator for when the enemy is damaged.

And by "damaged" I mean exploding. This function returns a closure.

"""

def f():
f.count += 1
n = f.count / 3
if n <= 2:
self.image = self.g.images['explosion-%s' % n][0]
else:
self.after_destroyed_func()

def task():
self.invincible = True

play_wav('explosion.wav')
f.count = 0
self.g.post_frame_tasks.append(task)
return f
The closure plays number games with the frame count to switch images every few frames and then finally go away. This made it really easy to animate explosions using three successive images. We used this same trick to animate a bunch of different things.

Another neat thing is that the turrets always turn to face you when they shoot. My trigonometry is pretty rusty and I was pretty tired when I came up with that code, so I'm just glad that I was able to remember sohcahtoa.

All in all, I'm pretty thrilled about what we came up with. There are many programmers in the world who are far more talented than I am, but it's nice to actually create something in so short a time span and say, "Hey, look what I can do!"

Thursday, September 06, 2007

Python: Useful Utility for PGU's leveledit

I'm participating in PyWeek right now, and I'm using PGU. If you're not using PGU, you can skip this post.

If you're like me, you sometimes get confused about when you're editing the tiles and when you're editing the background. My buddy drew an entire level, and the tiles and background were totally messed up. Rather than redo the entire level, I wrote a little utility to force all the tiles into the background. It's quick-and-dirty, but quite useful when you need it:
#!/usr/bin/env python
#
# Copyright 2007 Adam Ulvi, Shannon Behrens
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

"""Take a TGA file, and force any tiles onto the background.

This is to make up for UI interface "difficulties" in PGU's leveledit.

"""

import os
import sys

import pygame

__docformat__ = "restructuredtext"


try:
if (not len(sys.argv) == 3 or
not os.path.isfile(sys.argv[1])):
raise ValueError
except: # Catch all exceptions, not just ValueErrors.
print >> sys.stderr, "usage: force_background.py INPUT.tga OUTPUT.tga"
sys.exit(2)

in_f, out_f = sys.argv[1], sys.argv[2]
in_img = pygame.image.load(in_f)
out_img = in_img.copy()
w, h = in_img.get_width(), in_img.get_height()
for y in range(h):
for x in range(w):
(tile, bg, code, alpha) = in_img.get_at((x, y))
if tile:
bg, tile = tile, 0
out_img.set_at((x, y), (tile, bg, code, alpha))
pygame.image.save(out_img, out_f)