Chip's Tips for Developers

Contains coding, but not narcotic.

Rattus Reinhardtius: The Rat Race on Django

March 29th, 2010 5:34:50 pm pst by Sterling Camden

image It’s been almost four years since I released the rats upon the unsuspecting world of Ruby on Rails.  Since then, I’ve learned a lot about writing web applications – so I’ve been meaning to update this fun little game with some of the tricks I’ve learned.  But, you know, it hasn’t been exactly a priority.

Then a few weeks ago a prospective client asked me about Django.  I had never used it before, so prior to a conference call with them I downloaded it and worked through a couple of tutorials.

Python is not my favorite language, though it’s far from my least favorite.  A lot about Python is really clean, but some of it just seems anal-retentive – especially the indentation rules.  Oh, it’s consistent all right, but it just strikes me as a Simon Says Rule.  I mean, c’mon – you can’t even use tabs instead of spaces?  Between that and always forgetting the colons I end up wasting a lot of time on simple syntax errors.  At least the interpreter gives helpful error messages.

The web development framework Django seems to be a study in powerful simplicity.  It makes the usual things dead easy, and the less usual things still easy — just a little less so.  A web project requires a lot less scaffolding to sort through than in Rails.  The project/application generator writes a lot less code for you (almost none, in fact), not only because the design of the framework is simpler, but also because it relies more on inheritance and less on generated code.  I have never lost track of where code lives in a Django project the way I used to forget where I put my Rails code.

As an exercise, I decided to rewrite the Rat Race in Django, which you can download below.  This version also makes liberal use of JavaScript, especially the jQuery library (which I’ve included in the directory where the app expects to find it).  If you try to run the race with JavaScript disabled in your browser, you’ll get a nice red and yellow banner telling you that you need it.

To try this app out, unzip the download wherever you like.  Make sure you have Python and Django installed.  I’d recommend using the latest versions (Python 2.6, Django 1.1.1), as I haven’t tested with any others.  Go to the “ratrace” directory and start the included server:

manage.py runserver

Now you can bring up a browser (anything except Internet Explorer) and navigate to http://127.0.0.1:8000/ — which should start the next race.  I’ve included a sqlite3 database containing 72 rats.  You can administer this database by navigating to http://127.0.0.1:8000/admin/ – and if you don’t like my rats, you can just delete the database (rats.sqlite), regenerate it:

manage.py syncdb

and enter your own.  You must have at least three rats to run the race.

In this version of the rat race (back story here), I use the Ajax and JSON capabilities of jQuery and Django to drive the race.  jQuery’s animation lets me smooth the rat movements so you don’t get quite the jumpy effect of my earlier versions, and it allows me to ping the server for updates a little less frequently.  You can run multiple browsers pointed at the same server and get essentially the same race except for unimportant rat gestures.  I’ve tested it with the latest versions of Chrome, Firefox, Safari, Opera (some minor display issues) and Internet Explorer (no worky, not sweating it).

As in all earlier versions, each rat’s likelihood of moving forward or backwards in the race is controlled by a random number generator that’s biased according to their track record.  So a rat that has done well in the past is more likely to do well in the future.  But that isn’t set in stone, and I’ve introduced another random factor that can’t be seen by the user.  Instead of basing the odds strictly on that bias, I now simulate between $200 and $10,000 in bets of $2, $5, or $10 each.  Each bet is randomly chosen, but skewed according to the rat’s track record and an additional random factor.  This is intended to simulate a hunch, a whim, or individual knowledge that may or may not be in line with the additional random factor controlling the rat’s performance in that particular race.  The result is, I think, fairly close to true life experience – in which the best rat usually does well but doesn’t always win, while the poorer rats hardly ever place but sometimes surprise everyone.

Some interesting coincidences with real life fell out of algorithmic decisions I made.  In order to avoid divide-by-zero errors, I added one to the number of races run and then offset that by a random number.  This has the result of making the track record count more for more experienced rats, and conversely newer rats are less predictable.

I placed a chunk of cheese at the end of the race as an incentive for the rats.  When they reach it, they appear to eat it by overlapping its image.  At that point, I change the motion algorithm to avoid backing up (and thus regurgitating the cheese), and also slow it down a little.  This increases the excitement at the end of the race, because even if a rat reaches the cheese first, another rat may still be able to come up and polish off his/her chunk of cheddar to win.  The transition from the normal speed down to the eating phase also improves the favoring of rats with a better bias, so the rats who got near the end on sheer luck may not be able to hold out all the way to reaching the cheese.

The only thing I might add in the future is the ability to track bets from the user.

Enjoy the races.  For background music, may I recommend the works of Django’s namesake?

download

Posted in AJAX, Django, JSON, JavaScript, Python, Web, jQuery | 1 Comment » RSS 2.0 | Sphere it!

JSON for Synergy/DE

March 18th, 2010 1:49:09 pm pst by Sterling Camden

In modern web applications, JavaScript Object Notation (JSON) has become a popular syntax for exchanging information between client and server, because (as you might guess from its name) it plays well with JavaScript.  Therefore, parsers and emitters for JSON exist for a wide variety of server-side programming languages.  Synergy/DE should be no different in this respect.

The download below includes classes for generating and parsing JSON in Synergy/DE.  The parser converts JSON into Synergy/DE objects, using a Mapper (or a DefaultMapper if none is provided) to control how that conversion takes place.  Conversely, the Mapper also determines how to convert Synergy/DE objects into JSON.  You can also combine the effects of different Mappers together, so you don’t have to reinvent anything.

I have added these classes to the Synthesis library, which is now at version 2.1.3.

download

Posted in AJAX, JSON, SynergyDE | 1 Comment » RSS 2.0 | Sphere it!

OPML Browser 2.0 for WordPress

May 11th, 2009 4:38:37 pm pst by Sterling Camden

Yes, this is such a major upgrade to my OPML Browser plugin for WordPress that it warrants bumping the initial digit in the version number.  Here’s what changed:

  1. The plugin now expects to be installed in its own folder: (siteurl)/wp-content/plugins/opml-browser
  2. JavaScript and CSS have been separated into their own files.
  3. JavaScript events are now hooked on window load instead of in the HTML.
  4. Added “alt” attribute to all “img” tags.
  5. Images are now looked for in (siteurl)/wp-content/plugins/opml-browser/images
  6. If an image cannot be found, it will be replaced by the supplied unknown.png (a question mark).
  7. Added “Sort items?” option.  This sorts within categories, unless the “flatten” option is enabled (see next item).
  8. Added the “Flatten hierarchy?” option.  This combines all items into one level.  If sorting, all items get sorted together.
  9. The OPML description attribute is now displayed as a tooltip (as in the OPML Blogroll widget, but it also works in IE and Opera now!).

As far as I know, the OPML Browser can now do everything that the OPML Blogroll widget could do (items 7 through 9 filled that out), so I am herewith declaring the OPML Blogroll widget retired from further upgrades.  Please use this plugin’s widget instead from now on.  Let me know if I’ve forgotten any functionality that you need.

A big “thank you” to all of my users who requested various features and reported bugs.  This plugin would not be what it is today without your input. 

Posted in AJAX, ATOM, CSS, JavaScript, OPML, PHP, RSS, WordPress | 1 Comment » RSS 2.0 | Sphere it!

The Rat Race! Ruby on Rails and AJAX on Amphetamines

June 20th, 2006 7:04:43 pm pst by Sterling Camden

This little Ruby on Rails application demonstrates some of the capabilities of AJAX with Rails.

The Game

Ten rats, chosen at random from a database, race against each other along a laned track to reach the cheese. Sometimes they move backwards, but ultimately one of them wins, another one places, and a third one shows. Their movements are controlled by a random number generator, biased according to their race history. That is, rats that have done well in the past are favored, which is reflected in their displayed odds. The race is updated once a second (or thereabouts), via XmlHTTPRequest (aka AJAX) in the standard Rails fashion using ActionView::Helpers::JavaScriptHelper#periodically_call_remote.

Quick Start

First, install Ruby and Rails. Unzip the download into a directory. Load the “ratrace” database from ratrace.sql. The database.yml file in the rats\config directory is setup to use MySQL, username “root”, no password. Make any changes you need to that file. cd into the “rats” directory, and startup the WEBrick server which is included by Rails. On Windows, this would be accomplished with the command:

ruby script\server

Now bring up your favorite browser and navigate to http://localhost:3000/rats/run. Make sure that if you have a firewall enabled, you are not blocking local access to port 3000.

Performance

Even though updating the race only once per second gives the game’s animation a distinctly “freeze-frame” flavor, it still seems to be a bit too quick for a browser-based applicaton. To see this, start the race. Let the rats get going a bit, then try clicking on the “Rats” link near the top of the page. On my system (1.8 Ghz P4 running XP SP2) using a local WEBrick server, I get the following very unscientific results with different browsers:

Browser Version Time to load Rats:list page
Maxthon 1.5.2 22 seconds
Internet Explorer 6.0.2900.2180 16 seconds
Opera 8.51 build 7712 13 seconds
Opera 9.00 build 8501 13 seconds
Firefox 1.5.0.4 5 seconds

I haven’t tried the IE 7 beta yet. By viewing the WEBrick server’s output, I can see that Maxthon and IE6 have queued up many of the “update_race” calls, and these continue to be invoked even after successfully navigating to the Rats:list page. If you let the race run long enough, you can get so many of these queued up that you can’t ever get to the Rats:list page, and even after you close the browser the calls continue to come into the server. Several extra “update_race” calls occur with Opera, and only a few in Firefox. Thus it would seem that Firefox either manages to more quickly terminate the timer on navigation away from the page, or else it allows fewer calls to become queued. I don’t think it is processing the calls any faster, because the race appears to run at about the same pace in all of the browsers — although that is difficult to benchmark, given the random nature of the application.

This game has a long and fun history for me beginning in the 1970′s. See my blog on that here.

Posted in AJAX, Rails, Ruby, Web, Wildly popular | 2 Comments » RSS 2.0 | Sphere it!

Better Tag Cloud