tkneko—Animating the Neko on a Canvas

A more interesting task is emulating Masayuki Koba’s xneko game, where a neko chases after the cursor, running up, down, left, right, and in circles, stopping only when the cursor stops. If the cursor stays motionless long enough, the neko falls into a deep sleep. When the cursor moves again, the neko awakens and resumes chasing the cursor. The neko is confined to the MainWindow, but if the cursor leads him to a window edge, he scratches to get free and eventually either falls asleep or resumes running.

To simulate motion, we display images of the neko at various positions on the Canvas at tenth of a second intervals (anything slower presents unacceptable flicker). The images we have to work with are shown in Figure 17-14. To make the neko run left, we repeatedly display the left1.ppm and left2.ppm images. (If the images display at the same Canvas coordinate, the neko runs in place. We might as well have used Tk::Animation if we wanted that effect.)

The neko’s actions are state driven.[3]

There are in fact five distinct states: the neko is either waking, moving, stopping, scratching, or sleeping. The tkneko states are encoded in a Perl hash with compiled (for efficiency) regular expressions as keys and code references (the state processors) as values:

%states = ( qr/AWAKE/ => \&do_awake, qr/UP|UPRIGHT|RIGHT|DWRIGHT|DOWN|DWLEFT|LEFT|UPLEFT/ => \&do_move, qr/STOP/ => \&do_stop, qr/UTOGI|RTOGI|DTOGI|LTOGI/ => \&do_togi, qr/SLEEP/ => \&do_sleep, ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.