I Like Programming

Who says Python doesn’t have function static variables?

If you want to store internal state in a python function, most people would say you need to create a class and use class or instance attributes. Of course you don’t. Python 3 introduces “nonlocal” as a keyword for creating static variables, but you can already make them without this help.

In fact, you might even create them accidentally, due to this weird behavior with default arguments. Python only evaluates default arguments once, so if your default argument is mutable complex type, you have yourself some internal state.

>>> def counter(count=[0]):
...   count[0] += 1
...   return count[0]
... 
>>> counter()
1
>>> counter()
2
>>> counter()
3

Well, that’s kind of a hack. A better way to do this is to use function attributes. Yes, functions can have attributes, just like classes.

def counter():
  counter.count += 1
  return counter.count
counter.count = 0

Building a Good New User Experience for Elemental Chess

People don’t like to log in to things until they’re convinced it’s worth it.  That’s a given.  My first thought was to just make a sandbox mode for my game, where you can play it purely on the client side, with a friend or against the computer.  If you wanted to play against other players online, you’d need to log in with an openid provider.

I showed off my new sandbox mode at Google IO.  It didn’t have AI or checkmate detection yet, since I couldn’t decide whether to implement that on the client side or the server side.  Google Web Toolkit seems like a nice solution for client/server code sharing that I will definitely pursue.  But then I thought, I can solve this code sharing problem and provide a better user experience, if I get a little more ambitious with my user account handling.  I’ll let users do anything they want except hang onto their history if they’re not logged in.

When a user hits the site without a user in their session cookie, I’ll create a brand new user for them with a randomized name (and plenty of invitation to change it).  This is a full-featured user, with one caveat: it can expire, at about the time their cookie-based session should.  To keep it from expiring, all the user has to do is associate it with an OpenID.  This is exactly the same thing as logging in.

Okay, but what if a lazy user who already has a saved account comes along and plays a few games without logging in?  Easy.  When they eventually do log in, we can delete their temporary account and replace every instance of it with the real one!  Talk about awesome.

Since I’m totally overloading my Login button to function as “Login”, “Register”, “Save”, and “Merge Accounts”, I think it’s appropriate to call it something else.  “Recognize Me” sounds pretty good!

Rebuilding

I’ve lost tons of work in the past in almost every way imaginable, from melted or crushed hard disks to raid failures and unreliable hosts.  I thought redundancy would save me, but these failures always seem to happen in pairs.  I could fill a graveyard with all the work I’ve lost.

But I’m not gonig to let this get me down.  I can still remember how I made most of those old things, and some of them were pretty good simple ideas, so it might be fun to re-make them better stronger faster than before!

In the future, I’ll use reliable backup sites like github, amazon s3, and I’ll look into Mozy.  Their commercial is spot on, after all.  Fortunately, not all of my data is gone.  A good hunk of it survived on my 120GB WD Passport, which includes things as far back as 2005. I better back this up before I lose it!

Reduce by Any Other Name

One of my favorite functions is `reduce`.  It’s the perfect way to represent anything like sum, product, factorial, reverse, that walks along a list accumulating the values it finds.  Unfortunately, it’s hard to share my love of reduce when every language calls it something different.  Observe:

# Python - reduce
# reduce(function, iterable[, initializer])
def factorial(n):
return reduce(lambda acc,x: acc*x, range(1,n), 1)

# Ruby - inject
# Enumerable#inject(init) {|result, item| ...}
def factorial(n)
(1..n).inject(1) {|acc,x| acc*x}
end

-- Haskell - fold
-- foldl :: (a -> b -> a) -> a -> [b] -> a
factorial n = foldl (*) 1 [1..n]

// C# - Aggregate
// Enumerable.Aggregate<(Of <(TSource, TAccumulate>)>)
//   Method (IEnumerable<(Of <(TSource>)>),
//     TAccumulate, Func<(Of <(TAccumulate, TSource, TAccumulate>)>))
// (This type signature is pretty ridiculous)
int factorial(int n){
return Enumerable.Range(1, n).Aggegate(1, (acc,x) => acc*x);
}

Board Game Abstraction

How would you model a board game in a sql database?  I’ve been overthinking this.  I’d probably have a Game model to keep track of whose turn it is, with a lot of Pieces associated with it.  But that’s obvious.

To be totally generic, a Piece could consist of string:kind, string:space, and string:color.  But what if you were playing a game like chess with a 2D board?  You could name the space something like 2-2.  What if the piece has meta information like rank and class?  You could encode it in the kind, like fire-2.  Why bother using data types other than string if you’re just going to fetch all pieces and assemble the board whenever you compute a move?

Or is there a reason to query on meta information and board positions?  Would you optimize your game logic by not constructing the whole board each time?  Should you create a new model for the kind of piece that exists in each game, like a monopoly piece which moves around the board linearly versus a checkers piece which traverses in two dimensions and can be kinged?  Do you want many small tables or few large ones?

Ruby Doesn’t Have Inner Functions

Ruby syntax allows you to write something that looks a lot like an inner function in other languages. However, it really isn’t. Lets explore this odd behavior.

class Foo
  def bar
    x = "scoped variable"
    def baz
      puts x
    end
  end
end

This looks like a pretty standard test of closures. One might expect the bar method to define a function baz with access to bar’s scope, namely the variable x. Lets see what really happens.

puts Foo.instance_methods.include?("bar") # true
puts Foo.instance_methods.include?("baz") # false

Still consistent with our expectations, we see we have created an instance method bar, but not baz. Lets test out bar on an instance.

instance = Foo.new
instance.bar
puts Foo.instance_methods.include?("baz") # true

Oho, where did this baz method come from that wasn’t there before? Running bar created it! In fact, calling `bar’ in our instance even changed the global class definition to include it! Lets try it out!

instance.baz # NameError: undefined local variable or method ‘x’ for #<Foo:0x1cee4>

So much for closures. It seems baz doesn’t have access to bar’s scope. It’s just a plain old instance method that we’ve defined.

Well, it doesn’t behave much like other languages, but this behavior could still be useful. You could use it to evaluate method definitions conditionally, or just wait and create some of your methods after others have run. It’s not all that useful, but it’s still good to know so you don’t accidentally use this syntax wrong.