Wednesday, February 14, 2007

Chase the Pig

I was surprised to find that Wikipedia currently lacks an entry for the card game 拱豬 (Gong Zhu). This four-player trick-taking Hearts-like game is often played by my relatives on my mother's side, and I assume it's relatively well-known amongst the Chinese.

John McLeod maintains a page describing various rulesets for Gong Zhu (in particular the variants involving exposing cards sound highly intriguing to me), but none of them exactly match the one I was taught. For posterity I'll record my family's rules here.

For the first deal, the player with the seven of spades leads the first trick. The lead can be any card, not necessarily the seven of spades. In subsequent deals, the player that took the Queen of Spades in the previous deal leads the first trick. This player is sometimes nicknamed "The Pig". As in Hearts, there are no trumps, and the winner of the trick leads the next trick.

Why the seven of spades and not the two? Because another card game popular amongst my aunts and uncles involved building sequences starting with seven, and the first card played in that game had to be a seven. They adopted this rule for consistency.

My family always played a predetermined number of hands (e.g. 4) and the winner was the player(s) with the highest total score, but the more standard convention seems to be that one keeps playing until someone has a total score of -1000 or lower, and then the player(s) with the highest score is the winner. (I'm guessing they did this because when playing for stakes, payoffs occur more frequently with this scheme.)

The values of the cards are as follows:

  • Jack of Diamonds, or goat (羊): +100
  • Queen of Spades, or pig (豬): -200
  • Ten of Clubs: doubles your score, unless you have won no other cards in which case it is worth +50
  • Hearts: two to ten are worth minus their pip value, except for four which is worth -10. The Jack is -20, Queen -30, King -40 and Ace -50. The other cards are worth nothing.

I was taught a couple of mnemonics for the Four of Hearts being -10. Firstly, 4 is an unlucky number amongst the Chinese (I was told this is because the word for 4 sounds similar to the verb "to die" in Mandarin, and also in other variants of Chinese), so that's why its penalty value is worse than it should be.

Secondly, the word for 4 and the word for 10 in Mandarin sound similar. If you know a Mandarin speaker, get them to say "44 is 44" to hear for yourself!

If a player wins all the hearts, then the values of the hearts are reversed in sign, that is, they are positive instead of negative, and it can be checked that they are worth 200 points in total. Furthermore, if that same player also wins the pig, the pig is now worth +200 points.

If you win every card with a value, then you receive 100 points for the goat, 200 for the sheep, 200 for all the hearts, and finally your score gets doubled by the Ten of Clubs, giving a total of 1000 points. This is is the best possible score. The worst possible score is -796, when all but the Jack of Diamonds and Two of Hearts is taken.

Naturally, the name of the game refers to the practice of leading low spades in an attempt to flush out the pig: eventually the holder of the Queen of Spades may be forced to play it and take the trick.

Comparison with Hearts

I prefer this game to Hearts. There is something special about every suit in this game, whereas in Hearts, the clubs and diamonds tricks feel like filler. Winning the Jack of Diamonds is always good, and winning the Ten of Clubs sometimes helps, so even if you're not going for all the hearts there is something to do.

I never liked the Hearts rule preventing players from "breaking into" hearts, and I'm glad that Gong Zhu is free from this restriction.

Scoring is more complicated as each heart has a different penalty value. However I found after several hands I enjoyed the less trivial mental arithmetic, even missing it when playing Hearts.

Generally, I feel the game experience is richer because there are more important cards than Hearts, yet the additional complexity is not overly random nor overwhelming. In contrast, while playing Hearts if I'm not trying to shoot the moon, my play feels almost forced, as my only goal is to avoid the Queen of Spades and as many hearts a possible. Sometimes I can choose who to penalize more by playing in a certain way, but this aspect of the game is limited and unrewarding.

Even when shooting the moon, the strategy is often clear, a drawback that I feel is exacerbated by the prohibition on breaking into penalty cards.

I'm ambivalent about the Hearts convention of passing three cards before the game starts. Sometimes it's extremely helpful since some people I've played with are rather predictable, allowing me to mold hands which I can easily shoot the moon with. On the other hand, this does reduce the challenge, and in general getting extra information about opponent's hands detracts from the game experience.

The internal conflicts are more intense and exciting. I can feel my greed fight my fear. Do I save high cards to win the goat? What if this causes me to wind up with the pig and/or a bunch of high hearts as well? Do I go for the double? It's 50 points on its own, but how sure am I that I won't pick up any hearts later on?

Other Fun Card Games

I recall being enthralled when introduced to playing cards as a child. Nothing but fifty-two bits of pasteboard, yet the possibilities are legion. Games of pure skill. Games of pure chance. Games that fell in between, and it seemed that a game existed for any given skill/luck ratio. And they can be played almost anywhere, with any number of people, even alone. Such power, and I could hold it in one hand. Merely shuffling and performing sleights at once soothed and inspired me. To this day I often carry a pack of cards on my person.

One of my well-loved books from my childhood was "The Book of Games" by Richard Sharp and John Piggott (ISBN 0883653893). I read it cover to cover countless times, though not necessarily in order, marvelling at the illustrations and fascinated by the history. I tried out many of the games within, goading whoever was around me to learn their obscure rules so I could play.

(I took offence to one sentence however: in the entry on Mah Jong it describes the Chinese as "devious". I don't think they're inherently better at games than other races!)

If only the internet and Wikipedia existed back then! I was frustrated by rules they omitted, not to mention the games they left out. Sometimes the descriptions were too concise due to space limitations. Today the rules of just about any game with some following are at one's fingertips, and one can sometimes even find free programs for an instant opponent, instructor and umpire. Unfortunately, this came after my heaviest gaming days (at least, games that don't involve computers!), so the games below are mostly from the above book.

Though I'll mention card games of many species, some bias will be noticeable since I'm fond of lightweight teamless trick-taking games. Player ability varies wildly in some circles, making partner selection problematic in games such as bridge and canasta.

If there are four players, I almost always enjoy playing Hearts and Chase the Pig. Big Two is another favourite.

When there are three players, Knaves is a good choice if I'm in the mood for something like Hearts. It is also a no-trump trick-taking game with penalty cards, but also gives one an incentive to win as many tricks as possible. Sergeant Major is an entertaining diversion for three, especially for those newer to trick-taking games. My friends and family found David Parlett's Ninety-nine refreshingly unique and challenging. (We played the original rules, as described in The Book of Games.)

I never found two-player card games appealing, though I feel like I could if I dedicated more time to them. In particular, I feel like I should like Cribbage, Bezique and Piquet. I've tried some novel two-player games described in "The Pan Book of Card Games" by Hubert Philips, but never grew attached to them.

For five players or above, I'd play poker, or in a less serious crowd, Bartog.

Also, Napoleon is a five-player trick-taking game whose gimmick is the existence of a secret partnership: the identity of highest bidder, Napoleon, is known, but his secretary is determined by the holder of a particular card that is not revealed until played during a trick. Thus it is a two-versus-three game where initially no one knows the composition of the teams.

I had forgotten the details of this game. But thanks to Google, I rediscovered this old friend, and learned a lot more. Apparently, my parents left out at least half the rules when they taught it to me. Also, it seems Napoleon is a popular Japanese card game.

As for patience/solitaire for one, I'd recommend downloading a program like PySol and exploring.

Saturday, November 25, 2006

Inkscape and Valgrind

I spend a lot more time at the PBC (Pairing-Based Cryptography) library site than I would like since I maintain those pages. I bet most webmasters have similar complaints.

I began to tire of seeing page after page of text, so I broke the monotony by adding a site logo. It serves no other purpose, but who knows? Maybe one day I'll be hawking coffee mugs and T-shirts emblazoned with this graphic!

PBC logo

I went through several ideas before selecting a shape, during which I gained respect for professional logo designers. Some famous logos seem so simple that I feel I could have designed them. But on further examination, they insiduously invade and reside in one's memory, are pleasing to the eye (or at least are not eyesores), and in fact satisfy many constraints.

After a few attempts I discovered that it is extremely diffcult to find symbols with the necessary properties, and in my case, to even judge how effective a given image is. Thus I settled on a design as soon as I sketched one that I could tolerate.

I recall the path I took. At one point I was experimenting with a stylized "P(B,C)". I removed the letters to get "(,)" and played around with the parentheses and comma until I arrived at the current logo.

As for the colour scheme, to pay homage to my current university, I let Stanford's design guidelines on colour dictate my choices. Thus the logo is predominantly cardinal, with sandstone and black playing secondary roles. On most desktops, many screen elements are white and hence all four Stanford "Identity Colors" appear.

The result reminds me of a symbol featured in the movie "The Incredibles". I hope this causes people to think the PBC library is incredible, at least subconsciously!

I used Inkscape to realize my idea. I had never tried Inkscape before. I was surprised at how easy it was for a newbie to use and how quickly I became comfortable and efficient with its interface.

(Strictly speaking, this is false. Many moons ago I fired up Inkscape's ancestor Sodipodi, but I was unable to do much without reading documentation. Either Sodipodi has since made great advances, or the fork was worth the trouble.)

While I'm on my soapbox lauding software, let me also praise Valgrind. I first heard of this program years ago. If only I had tried it years ago.

Finding memory leaks in my C projects had always been troublesome. Thanks to geek machismo [isn't this an oxymoron?], I chose the hard way, namely, to code wrappers around standard memory allocation functions that recorded statistics which I would then analyze to detect leaks.

Since my leak detection code would need to be bug-free itself for this to work, I would restrict myself to primitive designs to simplify implementation details, ultimately leaving much of the sleuthing to the developer. Furthermore, toggling leak detection was so annoying I rarely checked for leaks.

As I recently discovered, Valgrind magically gives detailed reports on where the leak is and what is being leaked [insert HP joke here]. And to use Valgrind one only needs to invoke gcc with different options during compilation.

Valgrind has other features too, but I haven't tried them yet.

Sunday, October 29, 2006

Pi Music

I must have spent most of my life facing one keyboard or another. Over a year ago, while facing a musical kind, I was in a weird whimsical mood and I wrote a tune based on the digits of pi.

It did not surprise me when I discovered I was on a well-beaten path, as a search on Google quickly reveals. After all, many pi-inspired feats have been accomplished, such as setting Edgar Allen Poe's poem "The Raven" to the digits of pi. See also the honourable mention in this ray-tracing competition.

The pi music I found was quite abstract, whereas I want mine to sound more standard. I chose to have the digits 1-7 represent the tones of the C minor scale, altered if necessary, while 8 and 9 wrap around, that is, I encoded 8 and 1 the same way, as well as 9 and 2. Accordingly, I would have treated a 0 as a 7 but the tune ends just before reaching the first 0. (Thus 31 decimal places are encoded, this number fortunately corresponding with the first two digits of pi.)

This is akin to jianpu, a numbered musical notation system which I see in many Chinese books, but have never encountered in the Western world though supposedly it has seem some use in Europe. My scheme differs in that with jianpu, one would normally notate a minor key starting from 6, not 1.

It's a shame jianpu is not more widespread. It is well-suited for quickly and concisely jotting down simple melodies. A blank piece of paper suffices: there is no need to rule a music staff first. Writing numbers and dashes can be done extremely fast and most people are accustomed to this, unlike drawing geometric figures. More sloppiness is tolerated, as it is easier to identify scrawled digits and dashes than it is to figure out which line or space a hastily-scribbled note lies on, or whether a certain dot belongs to a note or was just a slip of then pen. Jianpu is also easy to learn due to its logic and simplicity. (Of course, jianpu performs terribly for even a slightly complex piece.)

(To be precise, jianpu-like notation is in fact employed in Western music. For example, when one writes "C6" to denote a chord, the "6" refers to the sixth note of the major scale.)

I added extra notes in order to produce a repeated motif typical of tunes. Following the digits exactly produces a melody that sounds a little too random for my tastes.

I chose conventional chord progressions. The A section uses a chromatically descending bassline, and the bridge mostly follows the cycle of fifths.

The time signature is 3/4, as this resembles 3.14 superficially. Also, in early (Western) musical notation, this time signature was represented with a circle.

I had intended to post it only once I had made some recordings (ideally after working on Bliss) but I have enough on my plate as it is. Maybe next Pi Day.

Anyway, it feels like an auspicious time to release it, as I happened to have recently released version 0.3.14 of the PBC library. And not too long ago Akira Haraguchi broke the world record after memorizing 100,000 digits of pi.

The lead sheets were created using Lilypond. The Lilypond website convincingly argues that their software automatically produces better sheet music than their major competitors, including commercial ones. It's also easy to integrate its output with HTML:

Incidently, around the same time I also penned a tune that loosely encodes a friend's name, but using a different method:

Wednesday, September 27, 2006

CMake and Autotools

I'm very grateful that somebody (Joe Cooley) contributed Autoconf and Automake files for the PBC library that I maintain. The GNU Autotools are almost essential because many people expect its presence and are used to compiling packages on Unix by typing ./configure followed by make. For the same reason, the Autotools give the project a more mature appearance. And they really do allow painless compilation on many systems.

But there is a dark side to using the GNU build system. The PBC source packages increased by several hundred kilobytes. I notice this extra weight because I often use wireless networks. Additionally, build times are at least twice as slow. On one run, it took 37 seconds to compile PBC, compared to 13 seconds with the original handwritten Makefile. And that's not counting the 13 seconds for ./configure and the 4 seconds for ./setup.

Furthermore, one has to be fluent in m4 and various configuration file formats, and understand how the toolchain works to create and maintain the build system. I was never motivated enough to learn all this, and I haven't changed. Any modifications I make to the Autoconf and Automake files are based on what I see there already, or a brief Google search.

It seems some people were sufficiently dissatisfied with the Autotools that they offered a substantial sum to anyone who wrote a better build tool. The winning project was SCons, which I experimented with last time I needed a build tool with more features than make.

But now a different tool has caught my attention, ever since I read this article. The KDE project ran into trouble with the Autotools, and began searching for alternatives. Like me, they found SCons promising, but after further investigation decided to switch to CMake.

Porting KDE to different platforms is highly nontrivial, so I reasoned that if CMake worked for such a substantial project, odds are good that it would work for my tiny library. I'm following by example I guess, and it certainly isn't the first time. I use git because it works for managing the Linux kernel source, and I use C because it works for countless important parts of the system (including of course the kernel), and for many well-respected programmers across several generations.

While researching CMake I found more arguments for switching: autoconf/automake is insane, glowing reviews of CMake (in the comments section), another endorsement and an interview with a CMake author.

I had a CMakeLists.txt file up and running fairly quickly, as the syntax is quite simple. Running times are much better: CMake took a couple of seconds to generate a Makefile, which in turn only took a second longer than my handwritten one to compile PBC. I was also pleased by the clean and colourful output.

Unfortunately, CMake is not installed on many systems. And it must be relatively untested. How does it compare to the Autotools on less mainstream platforms? And what about the more obscure tasks that the Autotools excel at? For example, is it difficult to get CMake to cross-compile a project?

For now, I'll have to maintain two sets of build configuration files in parallel, but I hope one day CMake will be equally well-known and widespread so I can jettison the autoconf/automake baggage.

Thursday, September 21, 2006

A Tale of Two Hacks

Years ago I wrote rcenter which has long been superseded by the LIRC project. I finally switched to LIRC myself. I wonder if anyone out there is still using rcenter.

It took me a while to figure out that LIRC does not work with OSS drivers unless Stephen Beahm's midi poll patch has been applied. I decided to switch to the ALSA drivers to avoid this issue. But then I had to set some other module options: snd-emu10k1 enable_ir=1 extin="0x3fc3" extout="0x1fff".

I wrote xmmspipe almost simultaneously, and in contrast, this project isn't obsolete yet. In fact, I recently discovered it has been an official Gentoo Linux package for some time when I received a bugfix for it.

It's times like these when I feel warm and fuzzy. I get to experience first-hand some of the touted benefits of free software. Having the source open means thankfully someone else can solve the problem. Even if I managed to fix the bug myself, I probably would've spent hours doing so.

On the other hand, I wouldn't mind if xmmspipe were obsolete and named pipes came with XMMS by default. I'm reminded of a quote from Doug McIlroy:

This is the Unix philosophy. Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.

and one from Rob Pike:

There has been much talk about component architectures, but only one true success: Unix pipes.

Thursday, September 14, 2006

Mental Feats

Michael Curtis (who commented on a previous posting) has written several articles on mental feats involving memory and mathematics.

Coincidently, I too read about the Trachtenberg system (a method for performing mental arithmetic) many years ago.

Reading his site reminded me of a time when I'd relieve boredom during occasions such as high school assemblies by squaring 2-digit numbers in my head using the techniques I had read about.

Today, I'd still use Trachtenberg's method for numbers ending in 5, based on the equation (10 a + 5)^2 = 100 a (a+1) + 25. However I have since found faster methods for other numbers, which I haven't seen described on the web. They only require additions and subtractions, but one has more to memorize.

Let n be the 2-digit number to be squared. Then if n lies in the range:

  1. 0-25: Memorize these answers.
  2. 25-50: Work out how far n is from 50 and how far n is from 25. Then the answer is 100(n - 25) + (50 - n)^2.
  3. 50-75: Compute 100((n-50) + 25) + (n-50)^2. (This is also Trachtenberg's method for squaring fifty-somethings.)
  4. 75-100: Compute 100(100 - 2(100-n)) + (100-n)^2

While I'm at it, I'll record a method for finding square roots (of squares of 2-digit numbers):

  1. Remove the last two digits of the square. Then the first digit of the answer is the largest digit whose square is less than this number.
  2. The last digit of the square tells us what the last digit of the answer could be. If it is 0 or 5, then so is the last digit of the answer and we are done, otherwise:
  3. Let the first digit of the answer is a. Compare the square with the square of 10a+5. If larger, then the last digit of the answer is between 6 and 9, and if smaller, it is between 1 and 4. Luckily, in base 10, the squares of 1 to 4 have distinct last digits. Also the squares of a and (10-a) end in the same digit, so it is now easy to determine the last digit of the answer.

The corresponding algorithm for cube roots is much simpler, because the cube of each digit has a distinct last digit (and similarly with other odd powers).

Friday, August 18, 2006

Slideshows in Firefox

Like many geeks, I frequently use text-based interfaces where normal people use GUIs, with a sense of smug self-satisfaction. Instead of a WYSIAYG word processor I use typesetting software like LaTeX. No fancy website creators for me, I use gvim to edit HTML files. Spreadsheets? I keep data in flat text files and write scripts to process them.

How about presentations? I had used MagicPoint for a few, but I wasn't completely satisfied. For instance, equations were fiddly: I had to write a script that would run TeX to render the equations to encapsulated PostScript and embed the resulting image in the slideshow. I briefly thought about writing my own program. Very briefly. Then I thought about exploiting existing programs instead.

I had come across PinPoint which uses GIMP to produce great-looking slides from a few lines. GIMP was designed to manipulate and display text and images, and is scriptable. But for live presentations, and for certain features I wanted, other programs or scripts would be needed, requiring a fair amount of work.

An idea hit me. MagicPoint can convert slides to HTML. How difficult would it be to modify things slightly so that presentations can be done in a web browser? After all, web browsers also manipulate and display text and images from a simple language. Not only that, they were designed to show different pages in succession. They are also ubiquitous.

One would just need to display pages in fullscreen, and perhaps using Javascript, have certain keypresses cause certain actions such as changing slides and triggering animations and other effects. Soon after experimenting with this, I discovered I was definitely not the first to think about web-based presentations.

The Opera browser has long had a slide show feature (the Opera Show Format), but unfortunately it is not supported by other browsers. I want it to work on Firefox.

Luckily, an alternative, the S5 project, has surfaced, which creates slideshows from a few lines of XHTML, and should work on any standards-compliant browser.

S5 was just what I was looking for. Webpages can contain images, text, visual effects, animations, and so on, and in theory S5 presentations should be able to as well.

MathML in S5

I want to display equations via MathML, but at present one cannot simply embed MathML (or SVG) and change the MIME type of S5 slides accordingly, though a fix exists and will be released.

As a workaround, I use ASCIIMathML. Perhaps this is a good thing. I had intended to put LaTeX style equations in the middle of the HTML and use itex2mml to convert it to MathML, but since ASCIIMathML converts to MathML on-the-fly using JavaScript, I can skip the compilation step. (Other tools to convert human-friendly text to MathML are blahtex, TexToMathML, and TtM.)

There's still the matter of getting the equations to display on Firefox. Until the STIX Fonts are ready, extra mathematical fonts have to be manually installed.

Also, for months now, MathML does not display correctly on certain Linux systems, though a workaround exists [also described here]. And for some reason, S5 is extremely slow on my Debian system, but runs fine on the Windows build of Firefox.